three.webgpu.js 1.7 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543
  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, EventDispatcher, MathUtils, WebGLCoordinateSystem, WebGPUCoordinateSystem, ColorManagement, SRGBTransfer, NoToneMapping, StaticDrawUsage, InterleavedBuffer, InterleavedBufferAttribute, DynamicDrawUsage, NoColorSpace, Texture, UnsignedIntType, IntType, NearestFilter, Sphere, BackSide, 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, DoubleSide, Camera, DepthStencilFormat, DepthFormat, UnsignedInt248Type, UnsignedByteType, Plane, Object3D, LinearMipMapLinearFilter, Float32BufferAttribute, UVMapping, VSMShadowMap, LessCompare, RGFormat, BasicShadowMap, SphereGeometry, LinearMipmapNearestFilter, NearestMipmapLinearFilter, Float16BufferAttribute, REVISION, ArrayCamera, PlaneGeometry, FrontSide, CustomBlending, AddEquation, ZeroFactor, CylinderGeometry, Quaternion, WebXRController, RAD2DEG, PCFShadowMap, FrustumArray, Frustum, DataTexture, RedIntegerFormat, RedFormat, ShortType, ByteType, UnsignedShortType, RGIntegerFormat, RGBIntegerFormat, RGBFormat, RGBAIntegerFormat, warnOnce, 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, 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, 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, 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, TimestampQuery, TorusGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeGeometry, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform, UniformsGroup, VectorKeyframeTrack, VideoFrameTexture, VideoTexture, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGLRenderTarget, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroSlopeEnding } 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. * This class is used by {@link WebGPURenderer} as management component.
  66. * It's primary purpose is to determine whether render objects require a
  67. * refresh right before they are going to be rendered or not.
  68. */
  69. class NodeMaterialObserver {
  70. /**
  71. * Constructs a new node material observer.
  72. *
  73. * @param {NodeBuilder} builder - The node builder.
  74. */
  75. constructor( builder ) {
  76. /**
  77. * A node material can be used by more than one render object so the
  78. * monitor must maintain a list of render objects.
  79. *
  80. * @type {WeakMap<RenderObject,Object>}
  81. */
  82. this.renderObjects = new WeakMap();
  83. /**
  84. * Whether the material uses node objects or not.
  85. *
  86. * @type {boolean}
  87. */
  88. this.hasNode = this.containsNode( builder );
  89. /**
  90. * Whether the node builder's 3D object is animated or not.
  91. *
  92. * @type {boolean}
  93. */
  94. this.hasAnimation = builder.object.isSkinnedMesh === true;
  95. /**
  96. * A list of all possible material uniforms
  97. *
  98. * @type {Array<string>}
  99. */
  100. this.refreshUniforms = refreshUniforms;
  101. /**
  102. * Holds the current render ID from the node frame.
  103. *
  104. * @type {number}
  105. * @default 0
  106. */
  107. this.renderId = 0;
  108. }
  109. /**
  110. * Returns `true` if the given render object is verified for the first time of this observer.
  111. *
  112. * @param {RenderObject} renderObject - The render object.
  113. * @return {boolean} Whether the given render object is verified for the first time of this observer.
  114. */
  115. firstInitialization( renderObject ) {
  116. const hasInitialized = this.renderObjects.has( renderObject );
  117. if ( hasInitialized === false ) {
  118. this.getRenderObjectData( renderObject );
  119. return true;
  120. }
  121. return false;
  122. }
  123. /**
  124. * Returns `true` if the current rendering produces motion vectors.
  125. *
  126. * @param {Renderer} renderer - The renderer.
  127. * @return {boolean} Whether the current rendering produces motion vectors or not.
  128. */
  129. needsVelocity( renderer ) {
  130. const mrt = renderer.getMRT();
  131. return ( mrt !== null && mrt.has( 'velocity' ) );
  132. }
  133. /**
  134. * Returns monitoring data for the given render object.
  135. *
  136. * @param {RenderObject} renderObject - The render object.
  137. * @return {Object} The monitoring data.
  138. */
  139. getRenderObjectData( renderObject ) {
  140. let data = this.renderObjects.get( renderObject );
  141. if ( data === undefined ) {
  142. const { geometry, material, object } = renderObject;
  143. data = {
  144. material: this.getMaterialData( material ),
  145. geometry: {
  146. id: geometry.id,
  147. attributes: this.getAttributesData( geometry.attributes ),
  148. indexVersion: geometry.index ? geometry.index.version : null,
  149. drawRange: { start: geometry.drawRange.start, count: geometry.drawRange.count }
  150. },
  151. worldMatrix: object.matrixWorld.clone()
  152. };
  153. if ( object.center ) {
  154. data.center = object.center.clone();
  155. }
  156. if ( object.morphTargetInfluences ) {
  157. data.morphTargetInfluences = object.morphTargetInfluences.slice();
  158. }
  159. if ( renderObject.bundle !== null ) {
  160. data.version = renderObject.bundle.version;
  161. }
  162. if ( data.material.transmission > 0 ) {
  163. const { width, height } = renderObject.context;
  164. data.bufferWidth = width;
  165. data.bufferHeight = height;
  166. }
  167. this.renderObjects.set( renderObject, data );
  168. }
  169. return data;
  170. }
  171. /**
  172. * Returns an attribute data structure holding the attributes versions for
  173. * monitoring.
  174. *
  175. * @param {Object} attributes - The geometry attributes.
  176. * @return {Object} An object for monitoring the versions of attributes.
  177. */
  178. getAttributesData( attributes ) {
  179. const attributesData = {};
  180. for ( const name in attributes ) {
  181. const attribute = attributes[ name ];
  182. attributesData[ name ] = {
  183. version: attribute.version
  184. };
  185. }
  186. return attributesData;
  187. }
  188. /**
  189. * Returns `true` if the node builder's material uses
  190. * node properties.
  191. *
  192. * @param {NodeBuilder} builder - The current node builder.
  193. * @return {boolean} Whether the node builder's material uses node properties or not.
  194. */
  195. containsNode( builder ) {
  196. const material = builder.material;
  197. for ( const property in material ) {
  198. if ( material[ property ] && material[ property ].isNode )
  199. return true;
  200. }
  201. if ( builder.renderer.overrideNodes.modelViewMatrix !== null || builder.renderer.overrideNodes.modelNormalViewMatrix !== null )
  202. return true;
  203. return false;
  204. }
  205. /**
  206. * Returns a material data structure holding the material property values for
  207. * monitoring.
  208. *
  209. * @param {Material} material - The material.
  210. * @return {Object} An object for monitoring material properties.
  211. */
  212. getMaterialData( material ) {
  213. const data = {};
  214. for ( const property of this.refreshUniforms ) {
  215. const value = material[ property ];
  216. if ( value === null || value === undefined ) continue;
  217. if ( typeof value === 'object' && value.clone !== undefined ) {
  218. if ( value.isTexture === true ) {
  219. data[ property ] = { id: value.id, version: value.version };
  220. } else {
  221. data[ property ] = value.clone();
  222. }
  223. } else {
  224. data[ property ] = value;
  225. }
  226. }
  227. return data;
  228. }
  229. /**
  230. * Returns `true` if the given render object has not changed its state.
  231. *
  232. * @param {RenderObject} renderObject - The render object.
  233. * @return {boolean} Whether the given render object has changed its state or not.
  234. */
  235. equals( renderObject ) {
  236. const { object, material, geometry } = renderObject;
  237. const renderObjectData = this.getRenderObjectData( renderObject );
  238. // world matrix
  239. if ( renderObjectData.worldMatrix.equals( object.matrixWorld ) !== true ) {
  240. renderObjectData.worldMatrix.copy( object.matrixWorld );
  241. return false;
  242. }
  243. // material
  244. const materialData = renderObjectData.material;
  245. for ( const property in materialData ) {
  246. const value = materialData[ property ];
  247. const mtlValue = material[ property ];
  248. if ( value.equals !== undefined ) {
  249. if ( value.equals( mtlValue ) === false ) {
  250. value.copy( mtlValue );
  251. return false;
  252. }
  253. } else if ( mtlValue.isTexture === true ) {
  254. if ( value.id !== mtlValue.id || value.version !== mtlValue.version ) {
  255. value.id = mtlValue.id;
  256. value.version = mtlValue.version;
  257. return false;
  258. }
  259. } else if ( value !== mtlValue ) {
  260. materialData[ property ] = mtlValue;
  261. return false;
  262. }
  263. }
  264. if ( materialData.transmission > 0 ) {
  265. const { width, height } = renderObject.context;
  266. if ( renderObjectData.bufferWidth !== width || renderObjectData.bufferHeight !== height ) {
  267. renderObjectData.bufferWidth = width;
  268. renderObjectData.bufferHeight = height;
  269. return false;
  270. }
  271. }
  272. // geometry
  273. const storedGeometryData = renderObjectData.geometry;
  274. const attributes = geometry.attributes;
  275. const storedAttributes = storedGeometryData.attributes;
  276. const storedAttributeNames = Object.keys( storedAttributes );
  277. const currentAttributeNames = Object.keys( attributes );
  278. if ( storedGeometryData.id !== geometry.id ) {
  279. storedGeometryData.id = geometry.id;
  280. return false;
  281. }
  282. if ( storedAttributeNames.length !== currentAttributeNames.length ) {
  283. renderObjectData.geometry.attributes = this.getAttributesData( attributes );
  284. return false;
  285. }
  286. // compare each attribute
  287. for ( const name of storedAttributeNames ) {
  288. const storedAttributeData = storedAttributes[ name ];
  289. const attribute = attributes[ name ];
  290. if ( attribute === undefined ) {
  291. // attribute was removed
  292. delete storedAttributes[ name ];
  293. return false;
  294. }
  295. if ( storedAttributeData.version !== attribute.version ) {
  296. storedAttributeData.version = attribute.version;
  297. return false;
  298. }
  299. }
  300. // check index
  301. const index = geometry.index;
  302. const storedIndexVersion = storedGeometryData.indexVersion;
  303. const currentIndexVersion = index ? index.version : null;
  304. if ( storedIndexVersion !== currentIndexVersion ) {
  305. storedGeometryData.indexVersion = currentIndexVersion;
  306. return false;
  307. }
  308. // check drawRange
  309. if ( storedGeometryData.drawRange.start !== geometry.drawRange.start || storedGeometryData.drawRange.count !== geometry.drawRange.count ) {
  310. storedGeometryData.drawRange.start = geometry.drawRange.start;
  311. storedGeometryData.drawRange.count = geometry.drawRange.count;
  312. return false;
  313. }
  314. // morph targets
  315. if ( renderObjectData.morphTargetInfluences ) {
  316. let morphChanged = false;
  317. for ( let i = 0; i < renderObjectData.morphTargetInfluences.length; i ++ ) {
  318. if ( renderObjectData.morphTargetInfluences[ i ] !== object.morphTargetInfluences[ i ] ) {
  319. morphChanged = true;
  320. }
  321. }
  322. if ( morphChanged ) return true;
  323. }
  324. // center
  325. if ( renderObjectData.center ) {
  326. if ( renderObjectData.center.equals( object.center ) === false ) {
  327. renderObjectData.center.copy( object.center );
  328. return true;
  329. }
  330. }
  331. // bundle
  332. if ( renderObject.bundle !== null ) {
  333. renderObjectData.version = renderObject.bundle.version;
  334. }
  335. return true;
  336. }
  337. /**
  338. * Checks if the given render object requires a refresh.
  339. *
  340. * @param {RenderObject} renderObject - The render object.
  341. * @param {NodeFrame} nodeFrame - The current node frame.
  342. * @return {boolean} Whether the given render object requires a refresh or not.
  343. */
  344. needsRefresh( renderObject, nodeFrame ) {
  345. if ( this.hasNode || this.hasAnimation || this.firstInitialization( renderObject ) || this.needsVelocity( nodeFrame.renderer ) )
  346. return true;
  347. const { renderId } = nodeFrame;
  348. if ( this.renderId !== renderId ) {
  349. this.renderId = renderId;
  350. return true;
  351. }
  352. const isStatic = renderObject.object.static === true;
  353. const isBundle = renderObject.bundle !== null && renderObject.bundle.static === true && this.getRenderObjectData( renderObject ).version === renderObject.bundle.version;
  354. if ( isStatic || isBundle )
  355. return false;
  356. const notEqual = this.equals( renderObject ) !== true;
  357. return notEqual;
  358. }
  359. }
  360. // cyrb53 (c) 2018 bryc (github.com/bryc). License: Public domain. Attribution appreciated.
  361. // A fast and simple 64-bit (or 53-bit) string hash function with decent collision resistance.
  362. // Largely inspired by MurmurHash2/3, but with a focus on speed/simplicity.
  363. // See https://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript/52171480#52171480
  364. // https://github.com/bryc/code/blob/master/jshash/experimental/cyrb53.js
  365. function cyrb53( value, seed = 0 ) {
  366. let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;
  367. if ( value instanceof Array ) {
  368. for ( let i = 0, val; i < value.length; i ++ ) {
  369. val = value[ i ];
  370. h1 = Math.imul( h1 ^ val, 2654435761 );
  371. h2 = Math.imul( h2 ^ val, 1597334677 );
  372. }
  373. } else {
  374. for ( let i = 0, ch; i < value.length; i ++ ) {
  375. ch = value.charCodeAt( i );
  376. h1 = Math.imul( h1 ^ ch, 2654435761 );
  377. h2 = Math.imul( h2 ^ ch, 1597334677 );
  378. }
  379. }
  380. h1 = Math.imul( h1 ^ ( h1 >>> 16 ), 2246822507 );
  381. h1 ^= Math.imul( h2 ^ ( h2 >>> 13 ), 3266489909 );
  382. h2 = Math.imul( h2 ^ ( h2 >>> 16 ), 2246822507 );
  383. h2 ^= Math.imul( h1 ^ ( h1 >>> 13 ), 3266489909 );
  384. return 4294967296 * ( 2097151 & h2 ) + ( h1 >>> 0 );
  385. }
  386. /**
  387. * Computes a hash for the given string.
  388. *
  389. * @method
  390. * @param {string} str - The string to be hashed.
  391. * @return {number} The hash.
  392. */
  393. const hashString = ( str ) => cyrb53( str );
  394. /**
  395. * Computes a hash for the given array.
  396. *
  397. * @method
  398. * @param {Array<number>} array - The array to be hashed.
  399. * @return {number} The hash.
  400. */
  401. const hashArray = ( array ) => cyrb53( array );
  402. /**
  403. * Computes a hash for the given list of parameters.
  404. *
  405. * @method
  406. * @param {...number} params - A list of parameters.
  407. * @return {number} The hash.
  408. */
  409. const hash$1 = ( ...params ) => cyrb53( params );
  410. /**
  411. * Computes a cache key for the given node.
  412. *
  413. * @method
  414. * @param {Object|Node} object - The object to be hashed.
  415. * @param {boolean} [force=false] - Whether to force a cache key computation or not.
  416. * @return {number} The hash.
  417. */
  418. function getCacheKey$1( object, force = false ) {
  419. const values = [];
  420. if ( object.isNode === true ) {
  421. values.push( object.id );
  422. object = object.getSelf();
  423. }
  424. for ( const { property, childNode } of getNodeChildren( object ) ) {
  425. values.push( cyrb53( property.slice( 0, -4 ) ), childNode.getCacheKey( force ) );
  426. }
  427. return cyrb53( values );
  428. }
  429. /**
  430. * This generator function can be used to iterate over the node children
  431. * of the given object.
  432. *
  433. * @generator
  434. * @param {Object} node - The object to be hashed.
  435. * @param {boolean} [toJSON=false] - Whether to return JSON or not.
  436. * @yields {Object} A result node holding the property, index (if available) and the child node.
  437. */
  438. function* getNodeChildren( node, toJSON = false ) {
  439. for ( const property in node ) {
  440. // Ignore private properties.
  441. if ( property.startsWith( '_' ) === true ) continue;
  442. const object = node[ property ];
  443. if ( Array.isArray( object ) === true ) {
  444. for ( let i = 0; i < object.length; i ++ ) {
  445. const child = object[ i ];
  446. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  447. yield { property, index: i, childNode: child };
  448. }
  449. }
  450. } else if ( object && object.isNode === true ) {
  451. yield { property, childNode: object };
  452. } else if ( typeof object === 'object' ) {
  453. for ( const subProperty in object ) {
  454. const child = object[ subProperty ];
  455. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  456. yield { property, index: subProperty, childNode: child };
  457. }
  458. }
  459. }
  460. }
  461. }
  462. const typeFromLength = /*@__PURE__*/ new Map( [
  463. [ 1, 'float' ],
  464. [ 2, 'vec2' ],
  465. [ 3, 'vec3' ],
  466. [ 4, 'vec4' ],
  467. [ 9, 'mat3' ],
  468. [ 16, 'mat4' ]
  469. ] );
  470. const dataFromObject = /*@__PURE__*/ new WeakMap();
  471. /**
  472. * Returns the data type for the given the length.
  473. *
  474. * @method
  475. * @param {number} length - The length.
  476. * @return {string} The data type.
  477. */
  478. function getTypeFromLength( length ) {
  479. return typeFromLength.get( length );
  480. }
  481. /**
  482. * Returns the typed array for the given data type.
  483. *
  484. * @method
  485. * @param {string} type - The data type.
  486. * @return {TypedArray} The typed array.
  487. */
  488. function getTypedArrayFromType( type ) {
  489. // Handle component type for vectors and matrices
  490. if ( /[iu]?vec\d/.test( type ) ) {
  491. // Handle int vectors
  492. if ( type.startsWith( 'ivec' ) ) return Int32Array;
  493. // Handle uint vectors
  494. if ( type.startsWith( 'uvec' ) ) return Uint32Array;
  495. // Default to float vectors
  496. return Float32Array;
  497. }
  498. // Handle matrices (always float)
  499. if ( /mat\d/.test( type ) ) return Float32Array;
  500. // Basic types
  501. if ( /float/.test( type ) ) return Float32Array;
  502. if ( /uint/.test( type ) ) return Uint32Array;
  503. if ( /int/.test( type ) ) return Int32Array;
  504. throw new Error( `THREE.NodeUtils: Unsupported type: ${type}` );
  505. }
  506. /**
  507. * Returns the length for the given data type.
  508. *
  509. * @method
  510. * @param {string} type - The data type.
  511. * @return {number} The length.
  512. */
  513. function getLengthFromType( type ) {
  514. if ( /float|int|uint/.test( type ) ) return 1;
  515. if ( /vec2/.test( type ) ) return 2;
  516. if ( /vec3/.test( type ) ) return 3;
  517. if ( /vec4/.test( type ) ) return 4;
  518. if ( /mat2/.test( type ) ) return 4;
  519. if ( /mat3/.test( type ) ) return 9;
  520. if ( /mat4/.test( type ) ) return 16;
  521. console.error( 'THREE.TSL: Unsupported type:', type );
  522. }
  523. /**
  524. * Returns the gpu memory length for the given data type.
  525. *
  526. * @method
  527. * @param {string} type - The data type.
  528. * @return {number} The length.
  529. */
  530. function getMemoryLengthFromType( type ) {
  531. if ( /float|int|uint/.test( type ) ) return 1;
  532. if ( /vec2/.test( type ) ) return 2;
  533. if ( /vec3/.test( type ) ) return 3;
  534. if ( /vec4/.test( type ) ) return 4;
  535. if ( /mat2/.test( type ) ) return 4;
  536. if ( /mat3/.test( type ) ) return 12;
  537. if ( /mat4/.test( type ) ) return 16;
  538. console.error( 'THREE.TSL: Unsupported type:', type );
  539. }
  540. /**
  541. * Returns the byte boundary for the given data type.
  542. *
  543. * @method
  544. * @param {string} type - The data type.
  545. * @return {number} The byte boundary.
  546. */
  547. function getByteBoundaryFromType( type ) {
  548. if ( /float|int|uint/.test( type ) ) return 4;
  549. if ( /vec2/.test( type ) ) return 8;
  550. if ( /vec3/.test( type ) ) return 16;
  551. if ( /vec4/.test( type ) ) return 16;
  552. if ( /mat2/.test( type ) ) return 8;
  553. if ( /mat3/.test( type ) ) return 48;
  554. if ( /mat4/.test( type ) ) return 64;
  555. console.error( 'THREE.TSL: Unsupported type:', type );
  556. }
  557. /**
  558. * Returns the data type for the given value.
  559. *
  560. * @method
  561. * @param {any} value - The value.
  562. * @return {?string} The data type.
  563. */
  564. function getValueType( value ) {
  565. if ( value === undefined || value === null ) return null;
  566. const typeOf = typeof value;
  567. if ( value.isNode === true ) {
  568. return 'node';
  569. } else if ( typeOf === 'number' ) {
  570. return 'float';
  571. } else if ( typeOf === 'boolean' ) {
  572. return 'bool';
  573. } else if ( typeOf === 'string' ) {
  574. return 'string';
  575. } else if ( typeOf === 'function' ) {
  576. return 'shader';
  577. } else if ( value.isVector2 === true ) {
  578. return 'vec2';
  579. } else if ( value.isVector3 === true ) {
  580. return 'vec3';
  581. } else if ( value.isVector4 === true ) {
  582. return 'vec4';
  583. } else if ( value.isMatrix2 === true ) {
  584. return 'mat2';
  585. } else if ( value.isMatrix3 === true ) {
  586. return 'mat3';
  587. } else if ( value.isMatrix4 === true ) {
  588. return 'mat4';
  589. } else if ( value.isColor === true ) {
  590. return 'color';
  591. } else if ( value instanceof ArrayBuffer ) {
  592. return 'ArrayBuffer';
  593. }
  594. return null;
  595. }
  596. /**
  597. * Returns the value/object for the given data type and parameters.
  598. *
  599. * @method
  600. * @param {string} type - The given type.
  601. * @param {...any} params - A parameter list.
  602. * @return {any} The value/object.
  603. */
  604. function getValueFromType( type, ...params ) {
  605. const last4 = type ? type.slice( -4 ) : undefined;
  606. if ( params.length === 1 ) { // ensure same behaviour as in NodeBuilder.format()
  607. if ( last4 === 'vec2' ) params = [ params[ 0 ], params[ 0 ] ];
  608. else if ( last4 === 'vec3' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ] ];
  609. else if ( last4 === 'vec4' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ], params[ 0 ] ];
  610. }
  611. if ( type === 'color' ) {
  612. return new Color( ...params );
  613. } else if ( last4 === 'vec2' ) {
  614. return new Vector2( ...params );
  615. } else if ( last4 === 'vec3' ) {
  616. return new Vector3( ...params );
  617. } else if ( last4 === 'vec4' ) {
  618. return new Vector4( ...params );
  619. } else if ( last4 === 'mat2' ) {
  620. return new Matrix2( ...params );
  621. } else if ( last4 === 'mat3' ) {
  622. return new Matrix3( ...params );
  623. } else if ( last4 === 'mat4' ) {
  624. return new Matrix4( ...params );
  625. } else if ( type === 'bool' ) {
  626. return params[ 0 ] || false;
  627. } else if ( ( type === 'float' ) || ( type === 'int' ) || ( type === 'uint' ) ) {
  628. return params[ 0 ] || 0;
  629. } else if ( type === 'string' ) {
  630. return params[ 0 ] || '';
  631. } else if ( type === 'ArrayBuffer' ) {
  632. return base64ToArrayBuffer( params[ 0 ] );
  633. }
  634. return null;
  635. }
  636. /**
  637. * Gets the object data that can be shared between different rendering steps.
  638. *
  639. * @param {Object} object - The object to get the data for.
  640. * @return {Object} The object data.
  641. */
  642. function getDataFromObject( object ) {
  643. let data = dataFromObject.get( object );
  644. if ( data === undefined ) {
  645. data = {};
  646. dataFromObject.set( object, data );
  647. }
  648. return data;
  649. }
  650. /**
  651. * Converts the given array buffer to a Base64 string.
  652. *
  653. * @method
  654. * @param {ArrayBuffer} arrayBuffer - The array buffer.
  655. * @return {string} The Base64 string.
  656. */
  657. function arrayBufferToBase64( arrayBuffer ) {
  658. let chars = '';
  659. const array = new Uint8Array( arrayBuffer );
  660. for ( let i = 0; i < array.length; i ++ ) {
  661. chars += String.fromCharCode( array[ i ] );
  662. }
  663. return btoa( chars );
  664. }
  665. /**
  666. * Converts the given Base64 string to an array buffer.
  667. *
  668. * @method
  669. * @param {string} base64 - The Base64 string.
  670. * @return {ArrayBuffer} The array buffer.
  671. */
  672. function base64ToArrayBuffer( base64 ) {
  673. return Uint8Array.from( atob( base64 ), c => c.charCodeAt( 0 ) ).buffer;
  674. }
  675. var NodeUtils = /*#__PURE__*/Object.freeze({
  676. __proto__: null,
  677. arrayBufferToBase64: arrayBufferToBase64,
  678. base64ToArrayBuffer: base64ToArrayBuffer,
  679. getByteBoundaryFromType: getByteBoundaryFromType,
  680. getCacheKey: getCacheKey$1,
  681. getDataFromObject: getDataFromObject,
  682. getLengthFromType: getLengthFromType,
  683. getMemoryLengthFromType: getMemoryLengthFromType,
  684. getNodeChildren: getNodeChildren,
  685. getTypeFromLength: getTypeFromLength,
  686. getTypedArrayFromType: getTypedArrayFromType,
  687. getValueFromType: getValueFromType,
  688. getValueType: getValueType,
  689. hash: hash$1,
  690. hashArray: hashArray,
  691. hashString: hashString
  692. });
  693. /**
  694. * Possible shader stages.
  695. *
  696. * @property {string} VERTEX The vertex shader stage.
  697. * @property {string} FRAGMENT The fragment shader stage.
  698. */
  699. const NodeShaderStage = {
  700. VERTEX: 'vertex',
  701. FRAGMENT: 'fragment'
  702. };
  703. /**
  704. * Update types of a node.
  705. *
  706. * @property {string} NONE The update method is not executed.
  707. * @property {string} FRAME The update method is executed per frame.
  708. * @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.
  709. * @property {string} OBJECT The update method is executed per {@link Object3D} that uses the node for rendering.
  710. */
  711. const NodeUpdateType = {
  712. NONE: 'none',
  713. FRAME: 'frame',
  714. RENDER: 'render',
  715. OBJECT: 'object'
  716. };
  717. /**
  718. * Data types of a node.
  719. *
  720. * @property {string} BOOLEAN Boolean type.
  721. * @property {string} INTEGER Integer type.
  722. * @property {string} FLOAT Float type.
  723. * @property {string} VECTOR2 Two-dimensional vector type.
  724. * @property {string} VECTOR3 Three-dimensional vector type.
  725. * @property {string} VECTOR4 Four-dimensional vector type.
  726. * @property {string} MATRIX2 2x2 matrix type.
  727. * @property {string} MATRIX3 3x3 matrix type.
  728. * @property {string} MATRIX4 4x4 matrix type.
  729. */
  730. const NodeType = {
  731. BOOLEAN: 'bool',
  732. INTEGER: 'int',
  733. FLOAT: 'float',
  734. VECTOR2: 'vec2',
  735. VECTOR3: 'vec3',
  736. VECTOR4: 'vec4',
  737. MATRIX2: 'mat2',
  738. MATRIX3: 'mat3',
  739. MATRIX4: 'mat4'
  740. };
  741. /**
  742. * Access types of a node. These are relevant for compute and storage usage.
  743. *
  744. * @property {string} READ_ONLY Read-only access
  745. * @property {string} WRITE_ONLY Write-only access.
  746. * @property {string} READ_WRITE Read and write access.
  747. */
  748. const NodeAccess = {
  749. READ_ONLY: 'readOnly',
  750. WRITE_ONLY: 'writeOnly',
  751. READ_WRITE: 'readWrite',
  752. };
  753. const defaultShaderStages = [ 'fragment', 'vertex' ];
  754. const defaultBuildStages = [ 'setup', 'analyze', 'generate' ];
  755. const shaderStages = [ ...defaultShaderStages, 'compute' ];
  756. const vectorComponents = [ 'x', 'y', 'z', 'w' ];
  757. const _parentBuildStage = {
  758. analyze: 'setup',
  759. generate: 'analyze'
  760. };
  761. let _nodeId = 0;
  762. /**
  763. * Base class for all nodes.
  764. *
  765. * @augments EventDispatcher
  766. */
  767. class Node extends EventDispatcher {
  768. static get type() {
  769. return 'Node';
  770. }
  771. /**
  772. * Constructs a new node.
  773. *
  774. * @param {?string} nodeType - The node type.
  775. */
  776. constructor( nodeType = null ) {
  777. super();
  778. /**
  779. * The node type. This represents the result type of the node (e.g. `float` or `vec3`).
  780. *
  781. * @type {?string}
  782. * @default null
  783. */
  784. this.nodeType = nodeType;
  785. /**
  786. * The update type of the node's {@link Node#update} method. Possible values are listed in {@link NodeUpdateType}.
  787. *
  788. * @type {string}
  789. * @default 'none'
  790. */
  791. this.updateType = NodeUpdateType.NONE;
  792. /**
  793. * The update type of the node's {@link Node#updateBefore} method. Possible values are listed in {@link NodeUpdateType}.
  794. *
  795. * @type {string}
  796. * @default 'none'
  797. */
  798. this.updateBeforeType = NodeUpdateType.NONE;
  799. /**
  800. * The update type of the node's {@link Node#updateAfter} method. Possible values are listed in {@link NodeUpdateType}.
  801. *
  802. * @type {string}
  803. * @default 'none'
  804. */
  805. this.updateAfterType = NodeUpdateType.NONE;
  806. /**
  807. * The UUID of the node.
  808. *
  809. * @type {string}
  810. * @readonly
  811. */
  812. this.uuid = MathUtils.generateUUID();
  813. /**
  814. * The version of the node. The version automatically is increased when {@link Node#needsUpdate} is set to `true`.
  815. *
  816. * @type {number}
  817. * @readonly
  818. * @default 0
  819. */
  820. this.version = 0;
  821. /**
  822. * Whether this node is global or not. This property is relevant for the internal
  823. * node caching system. All nodes which should be declared just once should
  824. * set this flag to `true` (a typical example is {@link AttributeNode}).
  825. *
  826. * @type {boolean}
  827. * @default false
  828. */
  829. this.global = false;
  830. /**
  831. * Create a list of parents for this node during the build process.
  832. *
  833. * @type {boolean}
  834. * @default false
  835. */
  836. this.parents = false;
  837. /**
  838. * This flag can be used for type testing.
  839. *
  840. * @type {boolean}
  841. * @readonly
  842. * @default true
  843. */
  844. this.isNode = true;
  845. // private
  846. /**
  847. * The cache key of this node.
  848. *
  849. * @private
  850. * @type {?number}
  851. * @default null
  852. */
  853. this._cacheKey = null;
  854. /**
  855. * The cache key 's version.
  856. *
  857. * @private
  858. * @type {number}
  859. * @default 0
  860. */
  861. this._cacheKeyVersion = 0;
  862. Object.defineProperty( this, 'id', { value: _nodeId ++ } );
  863. }
  864. /**
  865. * Set this property to `true` when the node should be regenerated.
  866. *
  867. * @type {boolean}
  868. * @default false
  869. * @param {boolean} value
  870. */
  871. set needsUpdate( value ) {
  872. if ( value === true ) {
  873. this.version ++;
  874. }
  875. }
  876. /**
  877. * The type of the class. The value is usually the constructor name.
  878. *
  879. * @type {string}
  880. * @readonly
  881. */
  882. get type() {
  883. return this.constructor.type;
  884. }
  885. /**
  886. * Convenient method for defining {@link Node#update}.
  887. *
  888. * @param {Function} callback - The update method.
  889. * @param {string} updateType - The update type.
  890. * @return {Node} A reference to this node.
  891. */
  892. onUpdate( callback, updateType ) {
  893. this.updateType = updateType;
  894. this.update = callback.bind( this.getSelf() );
  895. return this;
  896. }
  897. /**
  898. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  899. * this method automatically sets the update type to `FRAME`.
  900. *
  901. * @param {Function} callback - The update method.
  902. * @return {Node} A reference to this node.
  903. */
  904. onFrameUpdate( callback ) {
  905. return this.onUpdate( callback, NodeUpdateType.FRAME );
  906. }
  907. /**
  908. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  909. * this method automatically sets the update type to `RENDER`.
  910. *
  911. * @param {Function} callback - The update method.
  912. * @return {Node} A reference to this node.
  913. */
  914. onRenderUpdate( callback ) {
  915. return this.onUpdate( callback, NodeUpdateType.RENDER );
  916. }
  917. /**
  918. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  919. * this method automatically sets the update type to `OBJECT`.
  920. *
  921. * @param {Function} callback - The update method.
  922. * @return {Node} A reference to this node.
  923. */
  924. onObjectUpdate( callback ) {
  925. return this.onUpdate( callback, NodeUpdateType.OBJECT );
  926. }
  927. /**
  928. * Convenient method for defining {@link Node#updateReference}.
  929. *
  930. * @param {Function} callback - The update method.
  931. * @return {Node} A reference to this node.
  932. */
  933. onReference( callback ) {
  934. this.updateReference = callback.bind( this.getSelf() );
  935. return this;
  936. }
  937. /**
  938. * The `this` reference might point to a Proxy so this method can be used
  939. * to get the reference to the actual node instance.
  940. *
  941. * @return {Node} A reference to the node.
  942. */
  943. getSelf() {
  944. // Returns non-node object.
  945. return this.self || this;
  946. }
  947. /**
  948. * Nodes might refer to other objects like materials. This method allows to dynamically update the reference
  949. * to such objects based on a given state (e.g. the current node frame or builder).
  950. *
  951. * @param {any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  952. * @return {any} The updated reference.
  953. */
  954. updateReference( /*state*/ ) {
  955. return this;
  956. }
  957. /**
  958. * By default this method returns the value of the {@link Node#global} flag. This method
  959. * can be overwritten in derived classes if an analytical way is required to determine the
  960. * global cache referring to the current shader-stage.
  961. *
  962. * @param {NodeBuilder} builder - The current node builder.
  963. * @return {boolean} Whether this node is global or not.
  964. */
  965. isGlobal( /*builder*/ ) {
  966. return this.global;
  967. }
  968. /**
  969. * Generator function that can be used to iterate over the child nodes.
  970. *
  971. * @generator
  972. * @yields {Node} A child node.
  973. */
  974. * getChildren() {
  975. for ( const { childNode } of getNodeChildren( this ) ) {
  976. yield childNode;
  977. }
  978. }
  979. /**
  980. * Calling this method dispatches the `dispose` event. This event can be used
  981. * to register event listeners for clean up tasks.
  982. */
  983. dispose() {
  984. this.dispatchEvent( { type: 'dispose' } );
  985. }
  986. /**
  987. * Callback for {@link Node#traverse}.
  988. *
  989. * @callback traverseCallback
  990. * @param {Node} node - The current node.
  991. */
  992. /**
  993. * Can be used to traverse through the node's hierarchy.
  994. *
  995. * @param {traverseCallback} callback - A callback that is executed per node.
  996. */
  997. traverse( callback ) {
  998. callback( this );
  999. for ( const childNode of this.getChildren() ) {
  1000. childNode.traverse( callback );
  1001. }
  1002. }
  1003. /**
  1004. * Returns the cache key for this node.
  1005. *
  1006. * @param {boolean} [force=false] - When set to `true`, a recomputation of the cache key is forced.
  1007. * @return {number} The cache key of the node.
  1008. */
  1009. getCacheKey( force = false ) {
  1010. force = force || this.version !== this._cacheKeyVersion;
  1011. if ( force === true || this._cacheKey === null ) {
  1012. this._cacheKey = hash$1( getCacheKey$1( this, force ), this.customCacheKey() );
  1013. this._cacheKeyVersion = this.version;
  1014. }
  1015. return this._cacheKey;
  1016. }
  1017. /**
  1018. * Generate a custom cache key for this node.
  1019. *
  1020. * @return {number} The cache key of the node.
  1021. */
  1022. customCacheKey() {
  1023. return 0;
  1024. }
  1025. /**
  1026. * Returns the references to this node which is by default `this`.
  1027. *
  1028. * @return {Node} A reference to this node.
  1029. */
  1030. getScope() {
  1031. return this;
  1032. }
  1033. /**
  1034. * Returns the hash of the node which is used to identify the node. By default it's
  1035. * the {@link Node#uuid} however derived node classes might have to overwrite this method
  1036. * depending on their implementation.
  1037. *
  1038. * @param {NodeBuilder} builder - The current node builder.
  1039. * @return {string} The hash.
  1040. */
  1041. getHash( /*builder*/ ) {
  1042. return this.uuid;
  1043. }
  1044. /**
  1045. * Returns the update type of {@link Node#update}.
  1046. *
  1047. * @return {NodeUpdateType} The update type.
  1048. */
  1049. getUpdateType() {
  1050. return this.updateType;
  1051. }
  1052. /**
  1053. * Returns the update type of {@link Node#updateBefore}.
  1054. *
  1055. * @return {NodeUpdateType} The update type.
  1056. */
  1057. getUpdateBeforeType() {
  1058. return this.updateBeforeType;
  1059. }
  1060. /**
  1061. * Returns the update type of {@link Node#updateAfter}.
  1062. *
  1063. * @return {NodeUpdateType} The update type.
  1064. */
  1065. getUpdateAfterType() {
  1066. return this.updateAfterType;
  1067. }
  1068. /**
  1069. * Certain types are composed of multiple elements. For example a `vec3`
  1070. * is composed of three `float` values. This method returns the type of
  1071. * these elements.
  1072. *
  1073. * @param {NodeBuilder} builder - The current node builder.
  1074. * @return {string} The type of the node.
  1075. */
  1076. getElementType( builder ) {
  1077. const type = this.getNodeType( builder );
  1078. const elementType = builder.getElementType( type );
  1079. return elementType;
  1080. }
  1081. /**
  1082. * Returns the node member type for the given name.
  1083. *
  1084. * @param {NodeBuilder} builder - The current node builder.
  1085. * @param {string} name - The name of the member.
  1086. * @return {string} The type of the node.
  1087. */
  1088. getMemberType( /*builder, name*/ ) {
  1089. return 'void';
  1090. }
  1091. /**
  1092. * Returns the node's type.
  1093. *
  1094. * @param {NodeBuilder} builder - The current node builder.
  1095. * @return {string} The type of the node.
  1096. */
  1097. getNodeType( builder ) {
  1098. const nodeProperties = builder.getNodeProperties( this );
  1099. if ( nodeProperties.outputNode ) {
  1100. return nodeProperties.outputNode.getNodeType( builder );
  1101. }
  1102. return this.nodeType;
  1103. }
  1104. /**
  1105. * This method is used during the build process of a node and ensures
  1106. * equal nodes are not built multiple times but just once. For example if
  1107. * `attribute( 'uv' )` is used multiple times by the user, the build
  1108. * process makes sure to process just the first node.
  1109. *
  1110. * @param {NodeBuilder} builder - The current node builder.
  1111. * @return {Node} The shared node if possible. Otherwise `this` is returned.
  1112. */
  1113. getShared( builder ) {
  1114. const hash = this.getHash( builder );
  1115. const nodeFromHash = builder.getNodeFromHash( hash );
  1116. return nodeFromHash || this;
  1117. }
  1118. /**
  1119. * Represents the setup stage which is the first step of the build process, see {@link Node#build} method.
  1120. * This method is often overwritten in derived modules to prepare the node which is used as the output/result.
  1121. * The output node must be returned in the `return` statement.
  1122. *
  1123. * @param {NodeBuilder} builder - The current node builder.
  1124. * @return {?Node} The output node.
  1125. */
  1126. setup( builder ) {
  1127. const nodeProperties = builder.getNodeProperties( this );
  1128. let index = 0;
  1129. for ( const childNode of this.getChildren() ) {
  1130. nodeProperties[ 'node' + index ++ ] = childNode;
  1131. }
  1132. // return a outputNode if exists or null
  1133. return nodeProperties.outputNode || null;
  1134. }
  1135. /**
  1136. * Represents the analyze stage which is the second step of the build process, see {@link Node#build} method.
  1137. * This stage analyzes the node hierarchy and ensures descendent nodes are built.
  1138. *
  1139. * @param {NodeBuilder} builder - The current node builder.
  1140. * @param {?Node} output - The target output node.
  1141. */
  1142. analyze( builder, output = null ) {
  1143. const usageCount = builder.increaseUsage( this );
  1144. if ( this.parents === true ) {
  1145. const nodeData = builder.getDataFromNode( this, 'any' );
  1146. nodeData.stages = nodeData.stages || {};
  1147. nodeData.stages[ builder.shaderStage ] = nodeData.stages[ builder.shaderStage ] || [];
  1148. nodeData.stages[ builder.shaderStage ].push( output );
  1149. }
  1150. if ( usageCount === 1 ) {
  1151. // node flow children
  1152. const nodeProperties = builder.getNodeProperties( this );
  1153. for ( const childNode of Object.values( nodeProperties ) ) {
  1154. if ( childNode && childNode.isNode === true ) {
  1155. childNode.build( builder, this );
  1156. }
  1157. }
  1158. }
  1159. }
  1160. /**
  1161. * Represents the generate stage which is the third step of the build process, see {@link Node#build} method.
  1162. * This state builds the output node and returns the resulting shader string.
  1163. *
  1164. * @param {NodeBuilder} builder - The current node builder.
  1165. * @param {?string} output - Can be used to define the output type.
  1166. * @return {?string} The generated shader string.
  1167. */
  1168. generate( builder, output ) {
  1169. const { outputNode } = builder.getNodeProperties( this );
  1170. if ( outputNode && outputNode.isNode === true ) {
  1171. return outputNode.build( builder, output );
  1172. }
  1173. }
  1174. /**
  1175. * The method can be implemented to update the node's internal state before it is used to render an object.
  1176. * The {@link Node#updateBeforeType} property defines how often the update is executed.
  1177. *
  1178. * @abstract
  1179. * @param {NodeFrame} frame - A reference to the current node frame.
  1180. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1181. */
  1182. updateBefore( /*frame*/ ) {
  1183. console.warn( 'Abstract function.' );
  1184. }
  1185. /**
  1186. * The method can be implemented to update the node's internal state after it was used to render an object.
  1187. * The {@link Node#updateAfterType} property defines how often the update is executed.
  1188. *
  1189. * @abstract
  1190. * @param {NodeFrame} frame - A reference to the current node frame.
  1191. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1192. */
  1193. updateAfter( /*frame*/ ) {
  1194. console.warn( 'Abstract function.' );
  1195. }
  1196. /**
  1197. * The method can be implemented to update the node's internal state when it is used to render an object.
  1198. * The {@link Node#updateType} property defines how often the update is executed.
  1199. *
  1200. * @abstract
  1201. * @param {NodeFrame} frame - A reference to the current node frame.
  1202. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1203. */
  1204. update( /*frame*/ ) {
  1205. console.warn( 'Abstract function.' );
  1206. }
  1207. /**
  1208. * This method performs the build of a node. The behavior and return value depend on the current build stage:
  1209. * - **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.
  1210. * - **analyze**: Analyzes the node hierarchy for optimizations in the code generation stage. Returns `null`.
  1211. * - **generate**: Generates the shader code for the node. Returns the generated shader string.
  1212. *
  1213. * @param {NodeBuilder} builder - The current node builder.
  1214. * @param {string|Node|null} [output=null] - Can be used to define the output type.
  1215. * @return {Node|string|null} The result of the build process, depending on the build stage.
  1216. */
  1217. build( builder, output = null ) {
  1218. const refNode = this.getShared( builder );
  1219. if ( this !== refNode ) {
  1220. return refNode.build( builder, output );
  1221. }
  1222. //
  1223. const nodeData = builder.getDataFromNode( this );
  1224. nodeData.buildStages = nodeData.buildStages || {};
  1225. nodeData.buildStages[ builder.buildStage ] = true;
  1226. const parentBuildStage = _parentBuildStage[ builder.buildStage ];
  1227. if ( parentBuildStage && nodeData.buildStages[ parentBuildStage ] !== true ) {
  1228. // force parent build stage (setup or analyze)
  1229. const previousBuildStage = builder.getBuildStage();
  1230. builder.setBuildStage( parentBuildStage );
  1231. this.build( builder );
  1232. builder.setBuildStage( previousBuildStage );
  1233. }
  1234. //
  1235. builder.addNode( this );
  1236. builder.addChain( this );
  1237. /* Build stages expected results:
  1238. - "setup" -> Node
  1239. - "analyze" -> null
  1240. - "generate" -> String
  1241. */
  1242. let result = null;
  1243. const buildStage = builder.getBuildStage();
  1244. if ( buildStage === 'setup' ) {
  1245. this.updateReference( builder );
  1246. const properties = builder.getNodeProperties( this );
  1247. if ( properties.initialized !== true ) {
  1248. //const stackNodesBeforeSetup = builder.stack.nodes.length;
  1249. properties.initialized = true;
  1250. properties.outputNode = this.setup( builder ) || properties.outputNode || null;
  1251. /*if ( isNodeOutput && builder.stack.nodes.length !== stackNodesBeforeSetup ) {
  1252. // !! no outputNode !!
  1253. //outputNode = builder.stack;
  1254. }*/
  1255. for ( const childNode of Object.values( properties ) ) {
  1256. if ( childNode && childNode.isNode === true ) {
  1257. if ( childNode.parents === true ) {
  1258. const childProperties = builder.getNodeProperties( childNode );
  1259. childProperties.parents = childProperties.parents || [];
  1260. childProperties.parents.push( this );
  1261. }
  1262. childNode.build( builder );
  1263. }
  1264. }
  1265. }
  1266. result = properties.outputNode;
  1267. } else if ( buildStage === 'analyze' ) {
  1268. this.analyze( builder, output );
  1269. } else if ( buildStage === 'generate' ) {
  1270. const isGenerateOnce = this.generate.length === 1;
  1271. if ( isGenerateOnce ) {
  1272. const type = this.getNodeType( builder );
  1273. const nodeData = builder.getDataFromNode( this );
  1274. result = nodeData.snippet;
  1275. if ( result === undefined ) {
  1276. if ( nodeData.generated === undefined ) {
  1277. nodeData.generated = true;
  1278. result = this.generate( builder ) || '';
  1279. nodeData.snippet = result;
  1280. } else {
  1281. console.warn( 'THREE.Node: Recursion detected.', this );
  1282. result = '';
  1283. }
  1284. } else if ( nodeData.flowCodes !== undefined && builder.context.nodeBlock !== undefined ) {
  1285. builder.addFlowCodeHierarchy( this, builder.context.nodeBlock );
  1286. }
  1287. result = builder.format( result, type, output );
  1288. } else {
  1289. result = this.generate( builder, output ) || '';
  1290. }
  1291. }
  1292. builder.removeChain( this );
  1293. builder.addSequentialNode( this );
  1294. return result;
  1295. }
  1296. /**
  1297. * Returns the child nodes as a JSON object.
  1298. *
  1299. * @return {Array<Object>} An iterable list of serialized child objects as JSON.
  1300. */
  1301. getSerializeChildren() {
  1302. return getNodeChildren( this );
  1303. }
  1304. /**
  1305. * Serializes the node to JSON.
  1306. *
  1307. * @param {Object} json - The output JSON object.
  1308. */
  1309. serialize( json ) {
  1310. const nodeChildren = this.getSerializeChildren();
  1311. const inputNodes = {};
  1312. for ( const { property, index, childNode } of nodeChildren ) {
  1313. if ( index !== undefined ) {
  1314. if ( inputNodes[ property ] === undefined ) {
  1315. inputNodes[ property ] = Number.isInteger( index ) ? [] : {};
  1316. }
  1317. inputNodes[ property ][ index ] = childNode.toJSON( json.meta ).uuid;
  1318. } else {
  1319. inputNodes[ property ] = childNode.toJSON( json.meta ).uuid;
  1320. }
  1321. }
  1322. if ( Object.keys( inputNodes ).length > 0 ) {
  1323. json.inputNodes = inputNodes;
  1324. }
  1325. }
  1326. /**
  1327. * Deserializes the node from the given JSON.
  1328. *
  1329. * @param {Object} json - The JSON object.
  1330. */
  1331. deserialize( json ) {
  1332. if ( json.inputNodes !== undefined ) {
  1333. const nodes = json.meta.nodes;
  1334. for ( const property in json.inputNodes ) {
  1335. if ( Array.isArray( json.inputNodes[ property ] ) ) {
  1336. const inputArray = [];
  1337. for ( const uuid of json.inputNodes[ property ] ) {
  1338. inputArray.push( nodes[ uuid ] );
  1339. }
  1340. this[ property ] = inputArray;
  1341. } else if ( typeof json.inputNodes[ property ] === 'object' ) {
  1342. const inputObject = {};
  1343. for ( const subProperty in json.inputNodes[ property ] ) {
  1344. const uuid = json.inputNodes[ property ][ subProperty ];
  1345. inputObject[ subProperty ] = nodes[ uuid ];
  1346. }
  1347. this[ property ] = inputObject;
  1348. } else {
  1349. const uuid = json.inputNodes[ property ];
  1350. this[ property ] = nodes[ uuid ];
  1351. }
  1352. }
  1353. }
  1354. }
  1355. /**
  1356. * Serializes the node into the three.js JSON Object/Scene format.
  1357. *
  1358. * @param {?Object} meta - An optional JSON object that already holds serialized data from other scene objects.
  1359. * @return {Object} The serialized node.
  1360. */
  1361. toJSON( meta ) {
  1362. const { uuid, type } = this;
  1363. const isRoot = ( meta === undefined || typeof meta === 'string' );
  1364. if ( isRoot ) {
  1365. meta = {
  1366. textures: {},
  1367. images: {},
  1368. nodes: {}
  1369. };
  1370. }
  1371. // serialize
  1372. let data = meta.nodes[ uuid ];
  1373. if ( data === undefined ) {
  1374. data = {
  1375. uuid,
  1376. type,
  1377. meta,
  1378. metadata: {
  1379. version: 4.7,
  1380. type: 'Node',
  1381. generator: 'Node.toJSON'
  1382. }
  1383. };
  1384. if ( isRoot !== true ) meta.nodes[ data.uuid ] = data;
  1385. this.serialize( data );
  1386. delete data.meta;
  1387. }
  1388. // TODO: Copied from Object3D.toJSON
  1389. function extractFromCache( cache ) {
  1390. const values = [];
  1391. for ( const key in cache ) {
  1392. const data = cache[ key ];
  1393. delete data.metadata;
  1394. values.push( data );
  1395. }
  1396. return values;
  1397. }
  1398. if ( isRoot ) {
  1399. const textures = extractFromCache( meta.textures );
  1400. const images = extractFromCache( meta.images );
  1401. const nodes = extractFromCache( meta.nodes );
  1402. if ( textures.length > 0 ) data.textures = textures;
  1403. if ( images.length > 0 ) data.images = images;
  1404. if ( nodes.length > 0 ) data.nodes = nodes;
  1405. }
  1406. return data;
  1407. }
  1408. }
  1409. /**
  1410. * Base class for representing element access on an array-like
  1411. * node data structures.
  1412. *
  1413. * @augments Node
  1414. */
  1415. class ArrayElementNode extends Node { // @TODO: If extending from TempNode it breaks webgpu_compute
  1416. static get type() {
  1417. return 'ArrayElementNode';
  1418. }
  1419. /**
  1420. * Constructs an array element node.
  1421. *
  1422. * @param {Node} node - The array-like node.
  1423. * @param {Node} indexNode - The index node that defines the element access.
  1424. */
  1425. constructor( node, indexNode ) {
  1426. super();
  1427. /**
  1428. * The array-like node.
  1429. *
  1430. * @type {Node}
  1431. */
  1432. this.node = node;
  1433. /**
  1434. * The index node that defines the element access.
  1435. *
  1436. * @type {Node}
  1437. */
  1438. this.indexNode = indexNode;
  1439. /**
  1440. * This flag can be used for type testing.
  1441. *
  1442. * @type {boolean}
  1443. * @readonly
  1444. * @default true
  1445. */
  1446. this.isArrayElementNode = true;
  1447. }
  1448. /**
  1449. * This method is overwritten since the node type is inferred from the array-like node.
  1450. *
  1451. * @param {NodeBuilder} builder - The current node builder.
  1452. * @return {string} The node type.
  1453. */
  1454. getNodeType( builder ) {
  1455. return this.node.getElementType( builder );
  1456. }
  1457. generate( builder ) {
  1458. const indexType = this.indexNode.getNodeType( builder );
  1459. const nodeSnippet = this.node.build( builder );
  1460. const indexSnippet = this.indexNode.build( builder, ! builder.isVector( indexType ) && builder.isInteger( indexType ) ? indexType : 'uint' );
  1461. return `${ nodeSnippet }[ ${ indexSnippet } ]`;
  1462. }
  1463. }
  1464. /**
  1465. * This module is part of the TSL core and usually not used in app level code.
  1466. * It represents a convert operation during the shader generation process
  1467. * meaning it converts the data type of a node to a target data type.
  1468. *
  1469. * @augments Node
  1470. */
  1471. class ConvertNode extends Node {
  1472. static get type() {
  1473. return 'ConvertNode';
  1474. }
  1475. /**
  1476. * Constructs a new convert node.
  1477. *
  1478. * @param {Node} node - The node which type should be converted.
  1479. * @param {string} convertTo - The target node type. Multiple types can be defined by separating them with a `|` sign.
  1480. */
  1481. constructor( node, convertTo ) {
  1482. super();
  1483. /**
  1484. * The node which type should be converted.
  1485. *
  1486. * @type {Node}
  1487. */
  1488. this.node = node;
  1489. /**
  1490. * The target node type. Multiple types can be defined by separating them with a `|` sign.
  1491. *
  1492. * @type {string}
  1493. */
  1494. this.convertTo = convertTo;
  1495. }
  1496. /**
  1497. * This method is overwritten since the implementation tries to infer the best
  1498. * matching type from the {@link ConvertNode#convertTo} property.
  1499. *
  1500. * @param {NodeBuilder} builder - The current node builder.
  1501. * @return {string} The node type.
  1502. */
  1503. getNodeType( builder ) {
  1504. const requestType = this.node.getNodeType( builder );
  1505. let convertTo = null;
  1506. for ( const overloadingType of this.convertTo.split( '|' ) ) {
  1507. if ( convertTo === null || builder.getTypeLength( requestType ) === builder.getTypeLength( overloadingType ) ) {
  1508. convertTo = overloadingType;
  1509. }
  1510. }
  1511. return convertTo;
  1512. }
  1513. serialize( data ) {
  1514. super.serialize( data );
  1515. data.convertTo = this.convertTo;
  1516. }
  1517. deserialize( data ) {
  1518. super.deserialize( data );
  1519. this.convertTo = data.convertTo;
  1520. }
  1521. generate( builder, output ) {
  1522. const node = this.node;
  1523. const type = this.getNodeType( builder );
  1524. const snippet = node.build( builder, type );
  1525. return builder.format( snippet, type, output );
  1526. }
  1527. }
  1528. /**
  1529. * This module uses cache management to create temporary variables
  1530. * if the node is used more than once to prevent duplicate calculations.
  1531. *
  1532. * The class acts as a base class for many other nodes types.
  1533. *
  1534. * @augments Node
  1535. */
  1536. class TempNode extends Node {
  1537. static get type() {
  1538. return 'TempNode';
  1539. }
  1540. /**
  1541. * Constructs a temp node.
  1542. *
  1543. * @param {?string} nodeType - The node type.
  1544. */
  1545. constructor( nodeType = null ) {
  1546. super( nodeType );
  1547. /**
  1548. * This flag can be used for type testing.
  1549. *
  1550. * @type {boolean}
  1551. * @readonly
  1552. * @default true
  1553. */
  1554. this.isTempNode = true;
  1555. }
  1556. /**
  1557. * Whether this node is used more than once in context of other nodes.
  1558. *
  1559. * @param {NodeBuilder} builder - The node builder.
  1560. * @return {boolean} A flag that indicates if there is more than one dependency to other nodes.
  1561. */
  1562. hasDependencies( builder ) {
  1563. return builder.getDataFromNode( this ).usageCount > 1;
  1564. }
  1565. build( builder, output ) {
  1566. const buildStage = builder.getBuildStage();
  1567. if ( buildStage === 'generate' ) {
  1568. const type = builder.getVectorType( this.getNodeType( builder, output ) );
  1569. const nodeData = builder.getDataFromNode( this );
  1570. if ( nodeData.propertyName !== undefined ) {
  1571. return builder.format( nodeData.propertyName, type, output );
  1572. } else if ( type !== 'void' && output !== 'void' && this.hasDependencies( builder ) ) {
  1573. const snippet = super.build( builder, type );
  1574. const nodeVar = builder.getVarFromNode( this, null, type );
  1575. const propertyName = builder.getPropertyName( nodeVar );
  1576. builder.addLineFlowCode( `${ propertyName } = ${ snippet }`, this );
  1577. nodeData.snippet = snippet;
  1578. nodeData.propertyName = propertyName;
  1579. return builder.format( nodeData.propertyName, type, output );
  1580. }
  1581. }
  1582. return super.build( builder, output );
  1583. }
  1584. }
  1585. /**
  1586. * This module is part of the TSL core and usually not used in app level code.
  1587. * It represents a join operation during the shader generation process.
  1588. * For example in can compose/join two single floats into a `vec2` type.
  1589. *
  1590. * @augments TempNode
  1591. */
  1592. class JoinNode extends TempNode {
  1593. static get type() {
  1594. return 'JoinNode';
  1595. }
  1596. /**
  1597. * Constructs a new join node.
  1598. *
  1599. * @param {Array<Node>} nodes - An array of nodes that should be joined.
  1600. * @param {?string} [nodeType=null] - The node type.
  1601. */
  1602. constructor( nodes = [], nodeType = null ) {
  1603. super( nodeType );
  1604. /**
  1605. * An array of nodes that should be joined.
  1606. *
  1607. * @type {Array<Node>}
  1608. */
  1609. this.nodes = nodes;
  1610. }
  1611. /**
  1612. * This method is overwritten since the node type must be inferred from the
  1613. * joined data length if not explicitly defined.
  1614. *
  1615. * @param {NodeBuilder} builder - The current node builder.
  1616. * @return {string} The node type.
  1617. */
  1618. getNodeType( builder ) {
  1619. if ( this.nodeType !== null ) {
  1620. return builder.getVectorType( this.nodeType );
  1621. }
  1622. return builder.getTypeFromLength( this.nodes.reduce( ( count, cur ) => count + builder.getTypeLength( cur.getNodeType( builder ) ), 0 ) );
  1623. }
  1624. generate( builder, output ) {
  1625. const type = this.getNodeType( builder );
  1626. const maxLength = builder.getTypeLength( type );
  1627. const nodes = this.nodes;
  1628. const primitiveType = builder.getComponentType( type );
  1629. const snippetValues = [];
  1630. let length = 0;
  1631. for ( const input of nodes ) {
  1632. if ( length >= maxLength ) {
  1633. console.error( `THREE.TSL: Length of parameters exceeds maximum length of function '${ type }()' type.` );
  1634. break;
  1635. }
  1636. let inputType = input.getNodeType( builder );
  1637. let inputTypeLength = builder.getTypeLength( inputType );
  1638. let inputSnippet;
  1639. if ( length + inputTypeLength > maxLength ) {
  1640. console.error( `THREE.TSL: Length of '${ type }()' data exceeds maximum length of output type.` );
  1641. inputTypeLength = maxLength - length;
  1642. inputType = builder.getTypeFromLength( inputTypeLength );
  1643. }
  1644. length += inputTypeLength;
  1645. inputSnippet = input.build( builder, inputType );
  1646. const inputPrimitiveType = builder.getComponentType( inputType );
  1647. if ( inputPrimitiveType !== primitiveType ) {
  1648. inputSnippet = builder.format( inputSnippet, inputPrimitiveType, primitiveType );
  1649. }
  1650. snippetValues.push( inputSnippet );
  1651. }
  1652. const snippet = `${ builder.getType( type ) }( ${ snippetValues.join( ', ' ) } )`;
  1653. return builder.format( snippet, type, output );
  1654. }
  1655. }
  1656. const _stringVectorComponents = vectorComponents.join( '' );
  1657. /**
  1658. * This module is part of the TSL core and usually not used in app level code.
  1659. * `SplitNode` represents a property access operation which means it is
  1660. * used to implement any `.xyzw`, `.rgba` and `stpq` usage on node objects.
  1661. * For example:
  1662. * ```js
  1663. * const redValue = color.r;
  1664. * ```
  1665. *
  1666. * @augments Node
  1667. */
  1668. class SplitNode extends Node {
  1669. static get type() {
  1670. return 'SplitNode';
  1671. }
  1672. /**
  1673. * Constructs a new split node.
  1674. *
  1675. * @param {Node} node - The node that should be accessed.
  1676. * @param {string} [components='x'] - The components that should be accessed.
  1677. */
  1678. constructor( node, components = 'x' ) {
  1679. super();
  1680. /**
  1681. * The node that should be accessed.
  1682. *
  1683. * @type {Node}
  1684. */
  1685. this.node = node;
  1686. /**
  1687. * The components that should be accessed.
  1688. *
  1689. * @type {string}
  1690. */
  1691. this.components = components;
  1692. /**
  1693. * This flag can be used for type testing.
  1694. *
  1695. * @type {boolean}
  1696. * @readonly
  1697. * @default true
  1698. */
  1699. this.isSplitNode = true;
  1700. }
  1701. /**
  1702. * Returns the vector length which is computed based on the requested components.
  1703. *
  1704. * @return {number} The vector length.
  1705. */
  1706. getVectorLength() {
  1707. let vectorLength = this.components.length;
  1708. for ( const c of this.components ) {
  1709. vectorLength = Math.max( vectorComponents.indexOf( c ) + 1, vectorLength );
  1710. }
  1711. return vectorLength;
  1712. }
  1713. /**
  1714. * Returns the component type of the node's type.
  1715. *
  1716. * @param {NodeBuilder} builder - The current node builder.
  1717. * @return {string} The component type.
  1718. */
  1719. getComponentType( builder ) {
  1720. return builder.getComponentType( this.node.getNodeType( builder ) );
  1721. }
  1722. /**
  1723. * This method is overwritten since the node type is inferred from requested components.
  1724. *
  1725. * @param {NodeBuilder} builder - The current node builder.
  1726. * @return {string} The node type.
  1727. */
  1728. getNodeType( builder ) {
  1729. return builder.getTypeFromLength( this.components.length, this.getComponentType( builder ) );
  1730. }
  1731. generate( builder, output ) {
  1732. const node = this.node;
  1733. const nodeTypeLength = builder.getTypeLength( node.getNodeType( builder ) );
  1734. let snippet = null;
  1735. if ( nodeTypeLength > 1 ) {
  1736. let type = null;
  1737. const componentsLength = this.getVectorLength();
  1738. if ( componentsLength >= nodeTypeLength ) {
  1739. // needed expand the input node
  1740. type = builder.getTypeFromLength( this.getVectorLength(), this.getComponentType( builder ) );
  1741. }
  1742. const nodeSnippet = node.build( builder, type );
  1743. if ( this.components.length === nodeTypeLength && this.components === _stringVectorComponents.slice( 0, this.components.length ) ) {
  1744. // unnecessary swizzle
  1745. snippet = builder.format( nodeSnippet, type, output );
  1746. } else {
  1747. snippet = builder.format( `${nodeSnippet}.${this.components}`, this.getNodeType( builder ), output );
  1748. }
  1749. } else {
  1750. // ignore .components if .node returns float/integer
  1751. snippet = node.build( builder, output );
  1752. }
  1753. return snippet;
  1754. }
  1755. serialize( data ) {
  1756. super.serialize( data );
  1757. data.components = this.components;
  1758. }
  1759. deserialize( data ) {
  1760. super.deserialize( data );
  1761. this.components = data.components;
  1762. }
  1763. }
  1764. /**
  1765. * This module is part of the TSL core and usually not used in app level code.
  1766. * `SetNode` represents a set operation which means it is used to implement any
  1767. * `setXYZW()`, `setRGBA()` and `setSTPQ()` method invocations on node objects.
  1768. * For example:
  1769. * ```js
  1770. * materialLine.colorNode = color( 0, 0, 0 ).setR( float( 1 ) );
  1771. * ```
  1772. *
  1773. * @augments TempNode
  1774. */
  1775. class SetNode extends TempNode {
  1776. static get type() {
  1777. return 'SetNode';
  1778. }
  1779. /**
  1780. * Constructs a new set node.
  1781. *
  1782. * @param {Node} sourceNode - The node that should be updated.
  1783. * @param {string} components - The components that should be updated.
  1784. * @param {Node} targetNode - The value node.
  1785. */
  1786. constructor( sourceNode, components, targetNode ) {
  1787. super();
  1788. /**
  1789. * The node that should be updated.
  1790. *
  1791. * @type {Node}
  1792. */
  1793. this.sourceNode = sourceNode;
  1794. /**
  1795. * The components that should be updated.
  1796. *
  1797. * @type {string}
  1798. */
  1799. this.components = components;
  1800. /**
  1801. * The value node.
  1802. *
  1803. * @type {Node}
  1804. */
  1805. this.targetNode = targetNode;
  1806. }
  1807. /**
  1808. * This method is overwritten since the node type is inferred from {@link SetNode#sourceNode}.
  1809. *
  1810. * @param {NodeBuilder} builder - The current node builder.
  1811. * @return {string} The node type.
  1812. */
  1813. getNodeType( builder ) {
  1814. return this.sourceNode.getNodeType( builder );
  1815. }
  1816. generate( builder ) {
  1817. const { sourceNode, components, targetNode } = this;
  1818. const sourceType = this.getNodeType( builder );
  1819. const componentType = builder.getComponentType( targetNode.getNodeType( builder ) );
  1820. const targetType = builder.getTypeFromLength( components.length, componentType );
  1821. const targetSnippet = targetNode.build( builder, targetType );
  1822. const sourceSnippet = sourceNode.build( builder, sourceType );
  1823. const length = builder.getTypeLength( sourceType );
  1824. const snippetValues = [];
  1825. for ( let i = 0; i < length; i ++ ) {
  1826. const component = vectorComponents[ i ];
  1827. if ( component === components[ 0 ] ) {
  1828. snippetValues.push( targetSnippet );
  1829. i += components.length - 1;
  1830. } else {
  1831. snippetValues.push( sourceSnippet + '.' + component );
  1832. }
  1833. }
  1834. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  1835. }
  1836. }
  1837. /**
  1838. * This module is part of the TSL core and usually not used in app level code.
  1839. * It represents a flip operation during the shader generation process
  1840. * meaning it flips normalized values with the following formula:
  1841. * ```
  1842. * x = 1 - x;
  1843. * ```
  1844. * `FlipNode` is internally used to implement any `flipXYZW()`, `flipRGBA()` and
  1845. * `flipSTPQ()` method invocations on node objects. For example:
  1846. * ```js
  1847. * uvNode = uvNode.flipY();
  1848. * ```
  1849. *
  1850. * @augments TempNode
  1851. */
  1852. class FlipNode extends TempNode {
  1853. static get type() {
  1854. return 'FlipNode';
  1855. }
  1856. /**
  1857. * Constructs a new flip node.
  1858. *
  1859. * @param {Node} sourceNode - The node which component(s) should be flipped.
  1860. * @param {string} components - The components that should be flipped e.g. `'x'` or `'xy'`.
  1861. */
  1862. constructor( sourceNode, components ) {
  1863. super();
  1864. /**
  1865. * The node which component(s) should be flipped.
  1866. *
  1867. * @type {Node}
  1868. */
  1869. this.sourceNode = sourceNode;
  1870. /**
  1871. * The components that should be flipped e.g. `'x'` or `'xy'`.
  1872. *
  1873. * @type {string}
  1874. */
  1875. this.components = components;
  1876. }
  1877. /**
  1878. * This method is overwritten since the node type is inferred from the source node.
  1879. *
  1880. * @param {NodeBuilder} builder - The current node builder.
  1881. * @return {string} The node type.
  1882. */
  1883. getNodeType( builder ) {
  1884. return this.sourceNode.getNodeType( builder );
  1885. }
  1886. generate( builder ) {
  1887. const { components, sourceNode } = this;
  1888. const sourceType = this.getNodeType( builder );
  1889. const sourceSnippet = sourceNode.build( builder );
  1890. const sourceCache = builder.getVarFromNode( this );
  1891. const sourceProperty = builder.getPropertyName( sourceCache );
  1892. builder.addLineFlowCode( sourceProperty + ' = ' + sourceSnippet, this );
  1893. const length = builder.getTypeLength( sourceType );
  1894. const snippetValues = [];
  1895. let componentIndex = 0;
  1896. for ( let i = 0; i < length; i ++ ) {
  1897. const component = vectorComponents[ i ];
  1898. if ( component === components[ componentIndex ] ) {
  1899. snippetValues.push( '1.0 - ' + ( sourceProperty + '.' + component ) );
  1900. componentIndex ++;
  1901. } else {
  1902. snippetValues.push( sourceProperty + '.' + component );
  1903. }
  1904. }
  1905. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  1906. }
  1907. }
  1908. /**
  1909. * Base class for representing data input nodes.
  1910. *
  1911. * @augments Node
  1912. */
  1913. class InputNode extends Node {
  1914. static get type() {
  1915. return 'InputNode';
  1916. }
  1917. /**
  1918. * Constructs a new input node.
  1919. *
  1920. * @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).
  1921. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  1922. */
  1923. constructor( value, nodeType = null ) {
  1924. super( nodeType );
  1925. /**
  1926. * This flag can be used for type testing.
  1927. *
  1928. * @type {boolean}
  1929. * @readonly
  1930. * @default true
  1931. */
  1932. this.isInputNode = true;
  1933. /**
  1934. * The value of this node. This can be any JS primitive, functions, array buffers or even three.js objects (vector, matrices, colors).
  1935. *
  1936. * @type {any}
  1937. */
  1938. this.value = value;
  1939. /**
  1940. * The precision of the value in the shader.
  1941. *
  1942. * @type {?('low'|'medium'|'high')}
  1943. * @default null
  1944. */
  1945. this.precision = null;
  1946. }
  1947. getNodeType( /*builder*/ ) {
  1948. if ( this.nodeType === null ) {
  1949. return getValueType( this.value );
  1950. }
  1951. return this.nodeType;
  1952. }
  1953. /**
  1954. * Returns the input type of the node which is by default the node type. Derived modules
  1955. * might overwrite this method and use a fixed type or compute one analytically.
  1956. *
  1957. * A typical example for different input and node types are textures. The input type of a
  1958. * normal RGBA texture is `texture` whereas its node type is `vec4`.
  1959. *
  1960. * @param {NodeBuilder} builder - The current node builder.
  1961. * @return {string} The input type.
  1962. */
  1963. getInputType( builder ) {
  1964. return this.getNodeType( builder );
  1965. }
  1966. /**
  1967. * Sets the precision to the given value. The method can be
  1968. * overwritten in derived classes if the final precision must be computed
  1969. * analytically.
  1970. *
  1971. * @param {('low'|'medium'|'high')} precision - The precision of the input value in the shader.
  1972. * @return {InputNode} A reference to this node.
  1973. */
  1974. setPrecision( precision ) {
  1975. this.precision = precision;
  1976. return this;
  1977. }
  1978. serialize( data ) {
  1979. super.serialize( data );
  1980. data.value = this.value;
  1981. if ( this.value && this.value.toArray ) data.value = this.value.toArray();
  1982. data.valueType = getValueType( this.value );
  1983. data.nodeType = this.nodeType;
  1984. if ( data.valueType === 'ArrayBuffer' ) data.value = arrayBufferToBase64( data.value );
  1985. data.precision = this.precision;
  1986. }
  1987. deserialize( data ) {
  1988. super.deserialize( data );
  1989. this.nodeType = data.nodeType;
  1990. this.value = Array.isArray( data.value ) ? getValueFromType( data.valueType, ...data.value ) : data.value;
  1991. this.precision = data.precision || null;
  1992. if ( this.value && this.value.fromArray ) this.value = this.value.fromArray( data.value );
  1993. }
  1994. generate( /*builder, output*/ ) {
  1995. console.warn( 'Abstract function.' );
  1996. }
  1997. }
  1998. const _regNum = /float|u?int/;
  1999. /**
  2000. * Class for representing a constant value in the shader.
  2001. *
  2002. * @augments InputNode
  2003. */
  2004. class ConstNode extends InputNode {
  2005. static get type() {
  2006. return 'ConstNode';
  2007. }
  2008. /**
  2009. * Constructs a new input node.
  2010. *
  2011. * @param {any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color).
  2012. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2013. */
  2014. constructor( value, nodeType = null ) {
  2015. super( value, nodeType );
  2016. /**
  2017. * This flag can be used for type testing.
  2018. *
  2019. * @type {boolean}
  2020. * @readonly
  2021. * @default true
  2022. */
  2023. this.isConstNode = true;
  2024. }
  2025. /**
  2026. * Generates the shader string of the value with the current node builder.
  2027. *
  2028. * @param {NodeBuilder} builder - The current node builder.
  2029. * @return {string} The generated value as a shader string.
  2030. */
  2031. generateConst( builder ) {
  2032. return builder.generateConst( this.getNodeType( builder ), this.value );
  2033. }
  2034. generate( builder, output ) {
  2035. const type = this.getNodeType( builder );
  2036. if ( _regNum.test( type ) && _regNum.test( output ) ) {
  2037. return builder.generateConst( output, this.value );
  2038. }
  2039. return builder.format( this.generateConst( builder ), type, output );
  2040. }
  2041. }
  2042. /**
  2043. * Base class for representing member access on an object-like
  2044. * node data structures.
  2045. *
  2046. * @augments Node
  2047. */
  2048. class MemberNode extends Node {
  2049. static get type() {
  2050. return 'MemberNode';
  2051. }
  2052. /**
  2053. * Constructs an array element node.
  2054. *
  2055. * @param {Node} node - The array-like node.
  2056. * @param {string} property - The property name.
  2057. */
  2058. constructor( node, property ) {
  2059. super();
  2060. /**
  2061. * The array-like node.
  2062. *
  2063. * @type {Node}
  2064. */
  2065. this.node = node;
  2066. /**
  2067. * The property name.
  2068. *
  2069. * @type {Node}
  2070. */
  2071. this.property = property;
  2072. /**
  2073. * This flag can be used for type testing.
  2074. *
  2075. * @type {boolean}
  2076. * @readonly
  2077. * @default true
  2078. */
  2079. this.isMemberNode = true;
  2080. }
  2081. getNodeType( builder ) {
  2082. return this.node.getMemberType( builder, this.property );
  2083. }
  2084. generate( builder ) {
  2085. const propertyName = this.node.build( builder );
  2086. return propertyName + '.' + this.property;
  2087. }
  2088. }
  2089. let currentStack = null;
  2090. const NodeElements = new Map();
  2091. function addMethodChaining( name, nodeElement ) {
  2092. if ( NodeElements.has( name ) ) {
  2093. console.warn( `THREE.TSL: Redefinition of method chaining '${ name }'.` );
  2094. return;
  2095. }
  2096. if ( typeof nodeElement !== 'function' ) throw new Error( `THREE.TSL: Node element ${ name } is not a function` );
  2097. NodeElements.set( name, nodeElement );
  2098. }
  2099. const parseSwizzle = ( props ) => props.replace( /r|s/g, 'x' ).replace( /g|t/g, 'y' ).replace( /b|p/g, 'z' ).replace( /a|q/g, 'w' );
  2100. const parseSwizzleAndSort = ( props ) => parseSwizzle( props ).split( '' ).sort().join( '' );
  2101. const shaderNodeHandler = {
  2102. setup( NodeClosure, params ) {
  2103. const inputs = params.shift();
  2104. return NodeClosure( nodeObjects( inputs ), ...params );
  2105. },
  2106. get( node, prop, nodeObj ) {
  2107. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  2108. if ( node.isStackNode !== true && prop === 'assign' ) {
  2109. return ( ...params ) => {
  2110. currentStack.assign( nodeObj, ...params );
  2111. return nodeObj;
  2112. };
  2113. } else if ( NodeElements.has( prop ) ) {
  2114. const nodeElement = NodeElements.get( prop );
  2115. return node.isStackNode ? ( ...params ) => nodeObj.add( nodeElement( ...params ) ) : ( ...params ) => nodeElement( nodeObj, ...params );
  2116. } else if ( prop === 'self' ) {
  2117. return node;
  2118. } else if ( prop.endsWith( 'Assign' ) && NodeElements.has( prop.slice( 0, prop.length - 'Assign'.length ) ) ) {
  2119. const nodeElement = NodeElements.get( prop.slice( 0, prop.length - 'Assign'.length ) );
  2120. return node.isStackNode ? ( ...params ) => nodeObj.assign( params[ 0 ], nodeElement( ...params ) ) : ( ...params ) => nodeObj.assign( nodeElement( nodeObj, ...params ) );
  2121. } else if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true ) {
  2122. // accessing properties ( swizzle )
  2123. prop = parseSwizzle( prop );
  2124. return nodeObject( new SplitNode( nodeObj, prop ) );
  2125. } else if ( /^set[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  2126. // set properties ( swizzle ) and sort to xyzw sequence
  2127. prop = parseSwizzleAndSort( prop.slice( 3 ).toLowerCase() );
  2128. return ( value ) => nodeObject( new SetNode( node, prop, nodeObject( value ) ) );
  2129. } else if ( /^flip[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  2130. // set properties ( swizzle ) and sort to xyzw sequence
  2131. prop = parseSwizzleAndSort( prop.slice( 4 ).toLowerCase() );
  2132. return () => nodeObject( new FlipNode( nodeObject( node ), prop ) );
  2133. } else if ( prop === 'width' || prop === 'height' || prop === 'depth' ) {
  2134. // accessing property
  2135. if ( prop === 'width' ) prop = 'x';
  2136. else if ( prop === 'height' ) prop = 'y';
  2137. else if ( prop === 'depth' ) prop = 'z';
  2138. return nodeObject( new SplitNode( node, prop ) );
  2139. } else if ( /^\d+$/.test( prop ) === true ) {
  2140. // accessing array
  2141. return nodeObject( new ArrayElementNode( nodeObj, new ConstNode( Number( prop ), 'uint' ) ) );
  2142. } else if ( /^get$/.test( prop ) === true ) {
  2143. // accessing properties
  2144. return ( value ) => nodeObject( new MemberNode( nodeObj, value ) );
  2145. }
  2146. }
  2147. return Reflect.get( node, prop, nodeObj );
  2148. },
  2149. set( node, prop, value, nodeObj ) {
  2150. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  2151. // setting properties
  2152. if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true || prop === 'width' || prop === 'height' || prop === 'depth' || /^\d+$/.test( prop ) === true ) {
  2153. nodeObj[ prop ].assign( value );
  2154. return true;
  2155. }
  2156. }
  2157. return Reflect.set( node, prop, value, nodeObj );
  2158. }
  2159. };
  2160. const nodeObjectsCacheMap = new WeakMap();
  2161. const nodeBuilderFunctionsCacheMap = new WeakMap();
  2162. const ShaderNodeObject = function ( obj, altType = null ) {
  2163. const type = getValueType( obj );
  2164. if ( type === 'node' ) {
  2165. let nodeObject = nodeObjectsCacheMap.get( obj );
  2166. if ( nodeObject === undefined ) {
  2167. nodeObject = new Proxy( obj, shaderNodeHandler );
  2168. nodeObjectsCacheMap.set( obj, nodeObject );
  2169. nodeObjectsCacheMap.set( nodeObject, nodeObject );
  2170. }
  2171. return nodeObject;
  2172. } else if ( ( altType === null && ( type === 'float' || type === 'boolean' ) ) || ( type && type !== 'shader' && type !== 'string' ) ) {
  2173. return nodeObject( getConstNode( obj, altType ) );
  2174. } else if ( type === 'shader' ) {
  2175. return Fn( obj );
  2176. }
  2177. return obj;
  2178. };
  2179. const ShaderNodeObjects = function ( objects, altType = null ) {
  2180. for ( const name in objects ) {
  2181. objects[ name ] = nodeObject( objects[ name ], altType );
  2182. }
  2183. return objects;
  2184. };
  2185. const ShaderNodeArray = function ( array, altType = null ) {
  2186. const len = array.length;
  2187. for ( let i = 0; i < len; i ++ ) {
  2188. array[ i ] = nodeObject( array[ i ], altType );
  2189. }
  2190. return array;
  2191. };
  2192. const ShaderNodeProxy = function ( NodeClass, scope = null, factor = null, settings = null ) {
  2193. const assignNode = ( node ) => nodeObject( settings !== null ? Object.assign( node, settings ) : node );
  2194. let fn, name = scope, minParams, maxParams;
  2195. function verifyParamsLimit( params ) {
  2196. let tslName;
  2197. if ( name ) tslName = /[a-z]/i.test( name ) ? name + '()' : name;
  2198. else tslName = NodeClass.type;
  2199. if ( minParams !== undefined && params.length < minParams ) {
  2200. console.error( `THREE.TSL: "${ tslName }" parameter length is less than minimum required.` );
  2201. return params.concat( new Array( minParams - params.length ).fill( 0 ) );
  2202. } else if ( maxParams !== undefined && params.length > maxParams ) {
  2203. console.error( `THREE.TSL: "${ tslName }" parameter length exceeds limit.` );
  2204. return params.slice( 0, maxParams );
  2205. }
  2206. return params;
  2207. }
  2208. if ( scope === null ) {
  2209. fn = ( ...params ) => {
  2210. return assignNode( new NodeClass( ...nodeArray( verifyParamsLimit( params ) ) ) );
  2211. };
  2212. } else if ( factor !== null ) {
  2213. factor = nodeObject( factor );
  2214. fn = ( ...params ) => {
  2215. return assignNode( new NodeClass( scope, ...nodeArray( verifyParamsLimit( params ) ), factor ) );
  2216. };
  2217. } else {
  2218. fn = ( ...params ) => {
  2219. return assignNode( new NodeClass( scope, ...nodeArray( verifyParamsLimit( params ) ) ) );
  2220. };
  2221. }
  2222. fn.setParameterLength = ( ...params ) => {
  2223. if ( params.length === 1 ) minParams = maxParams = params[ 0 ];
  2224. else if ( params.length === 2 ) [ minParams, maxParams ] = params;
  2225. return fn;
  2226. };
  2227. fn.setName = ( value ) => {
  2228. name = value;
  2229. return fn;
  2230. };
  2231. return fn;
  2232. };
  2233. const ShaderNodeImmutable = function ( NodeClass, ...params ) {
  2234. return nodeObject( new NodeClass( ...nodeArray( params ) ) );
  2235. };
  2236. class ShaderCallNodeInternal extends Node {
  2237. constructor( shaderNode, inputNodes ) {
  2238. super();
  2239. this.shaderNode = shaderNode;
  2240. this.inputNodes = inputNodes;
  2241. this.isShaderCallNodeInternal = true;
  2242. }
  2243. getNodeType( builder ) {
  2244. return this.shaderNode.nodeType || this.getOutputNode( builder ).getNodeType( builder );
  2245. }
  2246. getMemberType( builder, name ) {
  2247. return this.getOutputNode( builder ).getMemberType( builder, name );
  2248. }
  2249. call( builder ) {
  2250. const { shaderNode, inputNodes } = this;
  2251. const properties = builder.getNodeProperties( shaderNode );
  2252. const onceNS = shaderNode.namespace && shaderNode.namespace === builder.namespace ? builder.getNamespace( 'once' ) : 'once';
  2253. if ( properties[ onceNS ] ) {
  2254. return properties[ onceNS ];
  2255. }
  2256. //
  2257. let result = null;
  2258. if ( shaderNode.layout ) {
  2259. let functionNodesCacheMap = nodeBuilderFunctionsCacheMap.get( builder.constructor );
  2260. if ( functionNodesCacheMap === undefined ) {
  2261. functionNodesCacheMap = new WeakMap();
  2262. nodeBuilderFunctionsCacheMap.set( builder.constructor, functionNodesCacheMap );
  2263. }
  2264. let functionNode = functionNodesCacheMap.get( shaderNode );
  2265. if ( functionNode === undefined ) {
  2266. functionNode = nodeObject( builder.buildFunctionNode( shaderNode ) );
  2267. functionNodesCacheMap.set( shaderNode, functionNode );
  2268. }
  2269. builder.addInclude( functionNode );
  2270. result = nodeObject( functionNode.call( inputNodes ) );
  2271. } else {
  2272. const jsFunc = shaderNode.jsFunc;
  2273. const outputNode = inputNodes !== null || jsFunc.length > 1 ? jsFunc( inputNodes || [], builder ) : jsFunc( builder );
  2274. result = nodeObject( outputNode );
  2275. }
  2276. if ( shaderNode.once ) {
  2277. properties[ onceNS ] = result;
  2278. }
  2279. return result;
  2280. }
  2281. setupOutput( builder ) {
  2282. builder.addStack();
  2283. builder.stack.outputNode = this.call( builder );
  2284. return builder.removeStack();
  2285. }
  2286. getOutputNode( builder ) {
  2287. const properties = builder.getNodeProperties( this );
  2288. const outputNamespace = builder.getOutputNamespace();
  2289. properties[ outputNamespace ] = properties[ outputNamespace ] || this.setupOutput( builder );
  2290. return properties[ outputNamespace ];
  2291. }
  2292. build( builder, output = null ) {
  2293. let result = null;
  2294. const buildStage = builder.getBuildStage();
  2295. const properties = builder.getNodeProperties( this );
  2296. const outputNamespace = builder.getOutputNamespace();
  2297. const outputNode = this.getOutputNode( builder );
  2298. if ( buildStage === 'setup' ) {
  2299. const initializedNamespace = builder.getNamespace( 'initialized' );
  2300. if ( properties[ initializedNamespace ] !== true ) {
  2301. properties[ initializedNamespace ] = true;
  2302. properties[ outputNamespace ] = this.getOutputNode( builder );
  2303. properties[ outputNamespace ].build( builder );
  2304. }
  2305. result = properties[ outputNamespace ];
  2306. } else if ( buildStage === 'analyze' ) {
  2307. outputNode.build( builder, output );
  2308. } else if ( buildStage === 'generate' ) {
  2309. result = outputNode.build( builder, output ) || '';
  2310. }
  2311. return result;
  2312. }
  2313. }
  2314. class ShaderNodeInternal extends Node {
  2315. constructor( jsFunc, nodeType ) {
  2316. super( nodeType );
  2317. this.jsFunc = jsFunc;
  2318. this.layout = null;
  2319. this.global = true;
  2320. this.once = false;
  2321. this.namespace = null;
  2322. }
  2323. setLayout( layout ) {
  2324. this.layout = layout;
  2325. return this;
  2326. }
  2327. call( inputs = null ) {
  2328. nodeObjects( inputs );
  2329. return nodeObject( new ShaderCallNodeInternal( this, inputs ) );
  2330. }
  2331. setup() {
  2332. return this.call();
  2333. }
  2334. }
  2335. const bools = [ false, true ];
  2336. const uints = [ 0, 1, 2, 3 ];
  2337. const ints = [ -1, -2 ];
  2338. 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 ];
  2339. const boolsCacheMap = new Map();
  2340. for ( const bool of bools ) boolsCacheMap.set( bool, new ConstNode( bool ) );
  2341. const uintsCacheMap = new Map();
  2342. for ( const uint of uints ) uintsCacheMap.set( uint, new ConstNode( uint, 'uint' ) );
  2343. const intsCacheMap = new Map( [ ...uintsCacheMap ].map( el => new ConstNode( el.value, 'int' ) ) );
  2344. for ( const int of ints ) intsCacheMap.set( int, new ConstNode( int, 'int' ) );
  2345. const floatsCacheMap = new Map( [ ...intsCacheMap ].map( el => new ConstNode( el.value ) ) );
  2346. for ( const float of floats ) floatsCacheMap.set( float, new ConstNode( float ) );
  2347. for ( const float of floats ) floatsCacheMap.set( - float, new ConstNode( - float ) );
  2348. const cacheMaps = { bool: boolsCacheMap, uint: uintsCacheMap, ints: intsCacheMap, float: floatsCacheMap };
  2349. const constNodesCacheMap = new Map( [ ...boolsCacheMap, ...floatsCacheMap ] );
  2350. const getConstNode = ( value, type ) => {
  2351. if ( constNodesCacheMap.has( value ) ) {
  2352. return constNodesCacheMap.get( value );
  2353. } else if ( value.isNode === true ) {
  2354. return value;
  2355. } else {
  2356. return new ConstNode( value, type );
  2357. }
  2358. };
  2359. const safeGetNodeType = ( node ) => {
  2360. try {
  2361. return node.getNodeType();
  2362. } catch ( _ ) {
  2363. return undefined;
  2364. }
  2365. };
  2366. const ConvertType = function ( type, cacheMap = null ) {
  2367. return ( ...params ) => {
  2368. if ( params.length === 0 || ( ! [ 'bool', 'float', 'int', 'uint' ].includes( type ) && params.every( param => typeof param !== 'object' ) ) ) {
  2369. params = [ getValueFromType( type, ...params ) ];
  2370. }
  2371. if ( params.length === 1 && cacheMap !== null && cacheMap.has( params[ 0 ] ) ) {
  2372. return nodeObject( cacheMap.get( params[ 0 ] ) );
  2373. }
  2374. if ( params.length === 1 ) {
  2375. const node = getConstNode( params[ 0 ], type );
  2376. if ( safeGetNodeType( node ) === type ) return nodeObject( node );
  2377. return nodeObject( new ConvertNode( node, type ) );
  2378. }
  2379. const nodes = params.map( param => getConstNode( param ) );
  2380. return nodeObject( new JoinNode( nodes, type ) );
  2381. };
  2382. };
  2383. // exports
  2384. const defined = ( v ) => typeof v === 'object' && v !== null ? v.value : v; // TODO: remove boolean conversion and defined function
  2385. // utils
  2386. const getConstNodeType = ( value ) => ( value !== undefined && value !== null ) ? ( value.nodeType || value.convertTo || ( typeof value === 'string' ? value : null ) ) : null;
  2387. // shader node base
  2388. function ShaderNode( jsFunc, nodeType ) {
  2389. return new Proxy( new ShaderNodeInternal( jsFunc, nodeType ), shaderNodeHandler );
  2390. }
  2391. const nodeObject = ( val, altType = null ) => /* new */ ShaderNodeObject( val, altType );
  2392. const nodeObjects = ( val, altType = null ) => new ShaderNodeObjects( val, altType );
  2393. const nodeArray = ( val, altType = null ) => new ShaderNodeArray( val, altType );
  2394. const nodeProxy = ( ...params ) => new ShaderNodeProxy( ...params );
  2395. const nodeImmutable = ( ...params ) => new ShaderNodeImmutable( ...params );
  2396. let fnId = 0;
  2397. const Fn = ( jsFunc, layout = null ) => {
  2398. let nodeType = null;
  2399. if ( layout !== null ) {
  2400. if ( typeof layout === 'object' ) {
  2401. nodeType = layout.return;
  2402. } else {
  2403. if ( typeof layout === 'string' ) {
  2404. nodeType = layout;
  2405. } else {
  2406. console.error( 'THREE.TSL: Invalid layout type.' );
  2407. }
  2408. layout = null;
  2409. }
  2410. }
  2411. const shaderNode = new ShaderNode( jsFunc, nodeType );
  2412. const fn = ( ...params ) => {
  2413. let inputs;
  2414. nodeObjects( params );
  2415. const isArrayAsParameter = params[ 0 ] && ( params[ 0 ].isNode || Object.getPrototypeOf( params[ 0 ] ) !== Object.prototype );
  2416. if ( isArrayAsParameter ) {
  2417. inputs = [ ...params ];
  2418. } else {
  2419. inputs = params[ 0 ];
  2420. }
  2421. const fnCall = shaderNode.call( inputs );
  2422. if ( nodeType === 'void' ) fnCall.toStack();
  2423. return fnCall;
  2424. };
  2425. fn.shaderNode = shaderNode;
  2426. fn.id = shaderNode.id;
  2427. fn.getNodeType = ( ...params ) => shaderNode.getNodeType( ...params );
  2428. fn.getCacheKey = ( ...params ) => shaderNode.getCacheKey( ...params );
  2429. fn.setLayout = ( layout ) => {
  2430. shaderNode.setLayout( layout );
  2431. return fn;
  2432. };
  2433. fn.once = ( namespace = null ) => {
  2434. shaderNode.once = true;
  2435. shaderNode.namespace = namespace;
  2436. return fn;
  2437. };
  2438. if ( layout !== null ) {
  2439. if ( typeof layout.inputs !== 'object' ) {
  2440. const fullLayout = {
  2441. name: 'fn' + fnId ++,
  2442. type: nodeType,
  2443. inputs: []
  2444. };
  2445. for ( const name in layout ) {
  2446. if ( name === 'return' ) continue;
  2447. fullLayout.inputs.push( {
  2448. name: name,
  2449. type: layout[ name ]
  2450. } );
  2451. }
  2452. layout = fullLayout;
  2453. }
  2454. fn.setLayout( layout );
  2455. }
  2456. return fn;
  2457. };
  2458. //
  2459. const setCurrentStack = ( stack ) => {
  2460. currentStack = stack;
  2461. };
  2462. const getCurrentStack = () => currentStack;
  2463. /**
  2464. * Represent a conditional node using if/else statements.
  2465. *
  2466. * ```js
  2467. * If( condition, function )
  2468. * .ElseIf( condition, function )
  2469. * .Else( function )
  2470. * ```
  2471. * @tsl
  2472. * @function
  2473. * @param {...any} params - The parameters for the conditional node.
  2474. * @returns {StackNode} The conditional node.
  2475. */
  2476. const If = ( ...params ) => currentStack.If( ...params );
  2477. /**
  2478. * Represent a conditional node using switch/case statements.
  2479. *
  2480. * ```js
  2481. * Switch( value )
  2482. * .Case( 1, function )
  2483. * .Case( 2, 3, 4, function )
  2484. * .Default( function )
  2485. * ```
  2486. * @tsl
  2487. * @function
  2488. * @param {...any} params - The parameters for the conditional node.
  2489. * @returns {StackNode} The conditional node.
  2490. */
  2491. const Switch = ( ...params ) => currentStack.Switch( ...params );
  2492. /**
  2493. * Add the given node to the current stack.
  2494. *
  2495. * @param {Node} node - The node to add.
  2496. * @returns {Node} The node that was added to the stack.
  2497. */
  2498. function Stack( node ) {
  2499. if ( currentStack ) currentStack.add( node );
  2500. return node;
  2501. }
  2502. addMethodChaining( 'toStack', Stack );
  2503. // types
  2504. const color = new ConvertType( 'color' );
  2505. const float = new ConvertType( 'float', cacheMaps.float );
  2506. const int = new ConvertType( 'int', cacheMaps.ints );
  2507. const uint = new ConvertType( 'uint', cacheMaps.uint );
  2508. const bool = new ConvertType( 'bool', cacheMaps.bool );
  2509. const vec2 = new ConvertType( 'vec2' );
  2510. const ivec2 = new ConvertType( 'ivec2' );
  2511. const uvec2 = new ConvertType( 'uvec2' );
  2512. const bvec2 = new ConvertType( 'bvec2' );
  2513. const vec3 = new ConvertType( 'vec3' );
  2514. const ivec3 = new ConvertType( 'ivec3' );
  2515. const uvec3 = new ConvertType( 'uvec3' );
  2516. const bvec3 = new ConvertType( 'bvec3' );
  2517. const vec4 = new ConvertType( 'vec4' );
  2518. const ivec4 = new ConvertType( 'ivec4' );
  2519. const uvec4 = new ConvertType( 'uvec4' );
  2520. const bvec4 = new ConvertType( 'bvec4' );
  2521. const mat2 = new ConvertType( 'mat2' );
  2522. const mat3 = new ConvertType( 'mat3' );
  2523. const mat4 = new ConvertType( 'mat4' );
  2524. const string = ( value = '' ) => nodeObject( new ConstNode( value, 'string' ) );
  2525. const arrayBuffer = ( value ) => nodeObject( new ConstNode( value, 'ArrayBuffer' ) );
  2526. addMethodChaining( 'toColor', color );
  2527. addMethodChaining( 'toFloat', float );
  2528. addMethodChaining( 'toInt', int );
  2529. addMethodChaining( 'toUint', uint );
  2530. addMethodChaining( 'toBool', bool );
  2531. addMethodChaining( 'toVec2', vec2 );
  2532. addMethodChaining( 'toIVec2', ivec2 );
  2533. addMethodChaining( 'toUVec2', uvec2 );
  2534. addMethodChaining( 'toBVec2', bvec2 );
  2535. addMethodChaining( 'toVec3', vec3 );
  2536. addMethodChaining( 'toIVec3', ivec3 );
  2537. addMethodChaining( 'toUVec3', uvec3 );
  2538. addMethodChaining( 'toBVec3', bvec3 );
  2539. addMethodChaining( 'toVec4', vec4 );
  2540. addMethodChaining( 'toIVec4', ivec4 );
  2541. addMethodChaining( 'toUVec4', uvec4 );
  2542. addMethodChaining( 'toBVec4', bvec4 );
  2543. addMethodChaining( 'toMat2', mat2 );
  2544. addMethodChaining( 'toMat3', mat3 );
  2545. addMethodChaining( 'toMat4', mat4 );
  2546. // basic nodes
  2547. const element = /*@__PURE__*/ nodeProxy( ArrayElementNode ).setParameterLength( 2 );
  2548. const convert = ( node, types ) => nodeObject( new ConvertNode( nodeObject( node ), types ) );
  2549. const split = ( node, channels ) => nodeObject( new SplitNode( nodeObject( node ), channels ) );
  2550. addMethodChaining( 'element', element );
  2551. addMethodChaining( 'convert', convert );
  2552. // deprecated
  2553. /**
  2554. * @tsl
  2555. * @function
  2556. * @deprecated since r176. Use {@link Stack} instead.
  2557. *
  2558. * @param {Node} node - The node to add.
  2559. * @returns {Function}
  2560. */
  2561. const append = ( node ) => { // @deprecated, r176
  2562. console.warn( 'THREE.TSL: append() has been renamed to Stack().' );
  2563. return Stack( node );
  2564. };
  2565. addMethodChaining( 'append', ( node ) => { // @deprecated, r176
  2566. console.warn( 'THREE.TSL: .append() has been renamed to .toStack().' );
  2567. return Stack( node );
  2568. } );
  2569. /**
  2570. * @tsl
  2571. * @function
  2572. * @deprecated since r168. Use {@link Fn} instead.
  2573. *
  2574. * @param {...any} params
  2575. * @returns {Function}
  2576. */
  2577. const tslFn = ( ...params ) => { // @deprecated, r168
  2578. console.warn( 'THREE.TSL: tslFn() has been renamed to Fn().' );
  2579. return Fn( ...params );
  2580. };
  2581. /**
  2582. * This class represents a shader property. It can be used
  2583. * to explicitly define a property and assign a value to it.
  2584. *
  2585. * ```js
  2586. * const threshold = property( 'float', 'threshold' ).assign( THRESHOLD );
  2587. *```
  2588. * `PropertyNode` is used by the engine to predefined common material properties
  2589. * for TSL code.
  2590. *
  2591. * @augments Node
  2592. */
  2593. class PropertyNode extends Node {
  2594. static get type() {
  2595. return 'PropertyNode';
  2596. }
  2597. /**
  2598. * Constructs a new property node.
  2599. *
  2600. * @param {string} nodeType - The type of the node.
  2601. * @param {?string} [name=null] - The name of the property in the shader.
  2602. * @param {boolean} [varying=false] - Whether this property is a varying or not.
  2603. */
  2604. constructor( nodeType, name = null, varying = false ) {
  2605. super( nodeType );
  2606. /**
  2607. * The name of the property in the shader. If no name is defined,
  2608. * the node system auto-generates one.
  2609. *
  2610. * @type {?string}
  2611. * @default null
  2612. */
  2613. this.name = name;
  2614. /**
  2615. * Whether this property is a varying or not.
  2616. *
  2617. * @type {boolean}
  2618. * @default false
  2619. */
  2620. this.varying = varying;
  2621. /**
  2622. * This flag can be used for type testing.
  2623. *
  2624. * @type {boolean}
  2625. * @readonly
  2626. * @default true
  2627. */
  2628. this.isPropertyNode = true;
  2629. /**
  2630. * This flag is used for global cache.
  2631. *
  2632. * @type {boolean}
  2633. * @default true
  2634. */
  2635. this.global = true;
  2636. }
  2637. getHash( builder ) {
  2638. return this.name || super.getHash( builder );
  2639. }
  2640. generate( builder ) {
  2641. let nodeVar;
  2642. if ( this.varying === true ) {
  2643. nodeVar = builder.getVaryingFromNode( this, this.name );
  2644. nodeVar.needsInterpolation = true;
  2645. } else {
  2646. nodeVar = builder.getVarFromNode( this, this.name );
  2647. }
  2648. return builder.getPropertyName( nodeVar );
  2649. }
  2650. }
  2651. /**
  2652. * TSL function for creating a property node.
  2653. *
  2654. * @tsl
  2655. * @function
  2656. * @param {string} type - The type of the node.
  2657. * @param {?string} [name=null] - The name of the property in the shader.
  2658. * @returns {PropertyNode}
  2659. */
  2660. const property = ( type, name ) => nodeObject( new PropertyNode( type, name ) );
  2661. /**
  2662. * TSL function for creating a varying property node.
  2663. *
  2664. * @tsl
  2665. * @function
  2666. * @param {string} type - The type of the node.
  2667. * @param {?string} [name=null] - The name of the varying in the shader.
  2668. * @returns {PropertyNode}
  2669. */
  2670. const varyingProperty = ( type, name ) => nodeObject( new PropertyNode( type, name, true ) );
  2671. /**
  2672. * TSL object that represents the shader variable `DiffuseColor`.
  2673. *
  2674. * @tsl
  2675. * @type {PropertyNode<vec4>}
  2676. */
  2677. const diffuseColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'DiffuseColor' );
  2678. /**
  2679. * TSL object that represents the shader variable `EmissiveColor`.
  2680. *
  2681. * @tsl
  2682. * @type {PropertyNode<vec3>}
  2683. */
  2684. const emissive = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'EmissiveColor' );
  2685. /**
  2686. * TSL object that represents the shader variable `Roughness`.
  2687. *
  2688. * @tsl
  2689. * @type {PropertyNode<float>}
  2690. */
  2691. const roughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Roughness' );
  2692. /**
  2693. * TSL object that represents the shader variable `Metalness`.
  2694. *
  2695. * @tsl
  2696. * @type {PropertyNode<float>}
  2697. */
  2698. const metalness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Metalness' );
  2699. /**
  2700. * TSL object that represents the shader variable `Clearcoat`.
  2701. *
  2702. * @tsl
  2703. * @type {PropertyNode<float>}
  2704. */
  2705. const clearcoat = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Clearcoat' );
  2706. /**
  2707. * TSL object that represents the shader variable `ClearcoatRoughness`.
  2708. *
  2709. * @tsl
  2710. * @type {PropertyNode<float>}
  2711. */
  2712. const clearcoatRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'ClearcoatRoughness' );
  2713. /**
  2714. * TSL object that represents the shader variable `Sheen`.
  2715. *
  2716. * @tsl
  2717. * @type {PropertyNode<vec3>}
  2718. */
  2719. const sheen = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'Sheen' );
  2720. /**
  2721. * TSL object that represents the shader variable `SheenRoughness`.
  2722. *
  2723. * @tsl
  2724. * @type {PropertyNode<float>}
  2725. */
  2726. const sheenRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SheenRoughness' );
  2727. /**
  2728. * TSL object that represents the shader variable `Iridescence`.
  2729. *
  2730. * @tsl
  2731. * @type {PropertyNode<float>}
  2732. */
  2733. const iridescence = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Iridescence' );
  2734. /**
  2735. * TSL object that represents the shader variable `IridescenceIOR`.
  2736. *
  2737. * @tsl
  2738. * @type {PropertyNode<float>}
  2739. */
  2740. const iridescenceIOR = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceIOR' );
  2741. /**
  2742. * TSL object that represents the shader variable `IridescenceThickness`.
  2743. *
  2744. * @tsl
  2745. * @type {PropertyNode<float>}
  2746. */
  2747. const iridescenceThickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceThickness' );
  2748. /**
  2749. * TSL object that represents the shader variable `AlphaT`.
  2750. *
  2751. * @tsl
  2752. * @type {PropertyNode<float>}
  2753. */
  2754. const alphaT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AlphaT' );
  2755. /**
  2756. * TSL object that represents the shader variable `Anisotropy`.
  2757. *
  2758. * @tsl
  2759. * @type {PropertyNode<float>}
  2760. */
  2761. const anisotropy = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Anisotropy' );
  2762. /**
  2763. * TSL object that represents the shader variable `AnisotropyT`.
  2764. *
  2765. * @tsl
  2766. * @type {PropertyNode<vec3>}
  2767. */
  2768. const anisotropyT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyT' );
  2769. /**
  2770. * TSL object that represents the shader variable `AnisotropyB`.
  2771. *
  2772. * @tsl
  2773. * @type {PropertyNode<vec3>}
  2774. */
  2775. const anisotropyB = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyB' );
  2776. /**
  2777. * TSL object that represents the shader variable `SpecularColor`.
  2778. *
  2779. * @tsl
  2780. * @type {PropertyNode<color>}
  2781. */
  2782. const specularColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'SpecularColor' );
  2783. /**
  2784. * TSL object that represents the shader variable `SpecularF90`.
  2785. *
  2786. * @tsl
  2787. * @type {PropertyNode<float>}
  2788. */
  2789. const specularF90 = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SpecularF90' );
  2790. /**
  2791. * TSL object that represents the shader variable `Shininess`.
  2792. *
  2793. * @tsl
  2794. * @type {PropertyNode<float>}
  2795. */
  2796. const shininess = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Shininess' );
  2797. /**
  2798. * TSL object that represents the shader variable `Output`.
  2799. *
  2800. * @tsl
  2801. * @type {PropertyNode<vec4>}
  2802. */
  2803. const output = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'Output' );
  2804. /**
  2805. * TSL object that represents the shader variable `dashSize`.
  2806. *
  2807. * @tsl
  2808. * @type {PropertyNode<float>}
  2809. */
  2810. const dashSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'dashSize' );
  2811. /**
  2812. * TSL object that represents the shader variable `gapSize`.
  2813. *
  2814. * @tsl
  2815. * @type {PropertyNode<float>}
  2816. */
  2817. const gapSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'gapSize' );
  2818. /**
  2819. * TSL object that represents the shader variable `pointWidth`.
  2820. *
  2821. * @tsl
  2822. * @type {PropertyNode<float>}
  2823. */
  2824. const pointWidth = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'pointWidth' );
  2825. /**
  2826. * TSL object that represents the shader variable `IOR`.
  2827. *
  2828. * @tsl
  2829. * @type {PropertyNode<float>}
  2830. */
  2831. const ior = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IOR' );
  2832. /**
  2833. * TSL object that represents the shader variable `Transmission`.
  2834. *
  2835. * @tsl
  2836. * @type {PropertyNode<float>}
  2837. */
  2838. const transmission = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Transmission' );
  2839. /**
  2840. * TSL object that represents the shader variable `Thickness`.
  2841. *
  2842. * @tsl
  2843. * @type {PropertyNode<float>}
  2844. */
  2845. const thickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Thickness' );
  2846. /**
  2847. * TSL object that represents the shader variable `AttenuationDistance`.
  2848. *
  2849. * @tsl
  2850. * @type {PropertyNode<float>}
  2851. */
  2852. const attenuationDistance = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AttenuationDistance' );
  2853. /**
  2854. * TSL object that represents the shader variable `AttenuationColor`.
  2855. *
  2856. * @tsl
  2857. * @type {PropertyNode<color>}
  2858. */
  2859. const attenuationColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'AttenuationColor' );
  2860. /**
  2861. * TSL object that represents the shader variable `Dispersion`.
  2862. *
  2863. * @tsl
  2864. * @type {PropertyNode<float>}
  2865. */
  2866. const dispersion = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Dispersion' );
  2867. /**
  2868. * This node can be used to group single instances of {@link UniformNode}
  2869. * and manage them as a uniform buffer.
  2870. *
  2871. * In most cases, the predefined nodes `objectGroup`, `renderGroup` and `frameGroup`
  2872. * will be used when defining the {@link UniformNode#groupNode} property.
  2873. *
  2874. * - `objectGroup`: Uniform buffer per object.
  2875. * - `renderGroup`: Shared uniform buffer, updated once per render call.
  2876. * - `frameGroup`: Shared uniform buffer, updated once per frame.
  2877. *
  2878. * @augments Node
  2879. */
  2880. class UniformGroupNode extends Node {
  2881. static get type() {
  2882. return 'UniformGroupNode';
  2883. }
  2884. /**
  2885. * Constructs a new uniform group node.
  2886. *
  2887. * @param {string} name - The name of the uniform group node.
  2888. * @param {boolean} [shared=false] - Whether this uniform group node is shared or not.
  2889. * @param {number} [order=1] - Influences the internal sorting.
  2890. */
  2891. constructor( name, shared = false, order = 1 ) {
  2892. super( 'string' );
  2893. /**
  2894. * The name of the uniform group node.
  2895. *
  2896. * @type {string}
  2897. */
  2898. this.name = name;
  2899. /**
  2900. * Whether this uniform group node is shared or not.
  2901. *
  2902. * @type {boolean}
  2903. * @default false
  2904. */
  2905. this.shared = shared;
  2906. /**
  2907. * Influences the internal sorting.
  2908. * TODO: Add details when this property should be changed.
  2909. *
  2910. * @type {number}
  2911. * @default 1
  2912. */
  2913. this.order = order;
  2914. /**
  2915. * This flag can be used for type testing.
  2916. *
  2917. * @type {boolean}
  2918. * @readonly
  2919. * @default true
  2920. */
  2921. this.isUniformGroup = true;
  2922. }
  2923. serialize( data ) {
  2924. super.serialize( data );
  2925. data.name = this.name;
  2926. data.version = this.version;
  2927. data.shared = this.shared;
  2928. }
  2929. deserialize( data ) {
  2930. super.deserialize( data );
  2931. this.name = data.name;
  2932. this.version = data.version;
  2933. this.shared = data.shared;
  2934. }
  2935. }
  2936. /**
  2937. * TSL function for creating a uniform group node with the given name.
  2938. *
  2939. * @tsl
  2940. * @function
  2941. * @param {string} name - The name of the uniform group node.
  2942. * @returns {UniformGroupNode}
  2943. */
  2944. const uniformGroup = ( name ) => new UniformGroupNode( name );
  2945. /**
  2946. * TSL function for creating a shared uniform group node with the given name and order.
  2947. *
  2948. * @tsl
  2949. * @function
  2950. * @param {string} name - The name of the uniform group node.
  2951. * @param {number} [order=0] - Influences the internal sorting.
  2952. * @returns {UniformGroupNode}
  2953. */
  2954. const sharedUniformGroup = ( name, order = 0 ) => new UniformGroupNode( name, true, order );
  2955. /**
  2956. * TSL object that represents a shared uniform group node which is updated once per frame.
  2957. *
  2958. * @tsl
  2959. * @type {UniformGroupNode}
  2960. */
  2961. const frameGroup = /*@__PURE__*/ sharedUniformGroup( 'frame' );
  2962. /**
  2963. * TSL object that represents a shared uniform group node which is updated once per render.
  2964. *
  2965. * @tsl
  2966. * @type {UniformGroupNode}
  2967. */
  2968. const renderGroup = /*@__PURE__*/ sharedUniformGroup( 'render' );
  2969. /**
  2970. * TSL object that represents a uniform group node which is updated once per object.
  2971. *
  2972. * @tsl
  2973. * @type {UniformGroupNode}
  2974. */
  2975. const objectGroup = /*@__PURE__*/ uniformGroup( 'object' );
  2976. /**
  2977. * Class for representing a uniform.
  2978. *
  2979. * @augments InputNode
  2980. */
  2981. class UniformNode extends InputNode {
  2982. static get type() {
  2983. return 'UniformNode';
  2984. }
  2985. /**
  2986. * Constructs a new uniform node.
  2987. *
  2988. * @param {any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  2989. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2990. */
  2991. constructor( value, nodeType = null ) {
  2992. super( value, nodeType );
  2993. /**
  2994. * This flag can be used for type testing.
  2995. *
  2996. * @type {boolean}
  2997. * @readonly
  2998. * @default true
  2999. */
  3000. this.isUniformNode = true;
  3001. /**
  3002. * The name or label of the uniform.
  3003. *
  3004. * @type {string}
  3005. * @default ''
  3006. */
  3007. this.name = '';
  3008. /**
  3009. * The uniform group of this uniform. By default, uniforms are
  3010. * managed per object but they might belong to a shared group
  3011. * which is updated per frame or render call.
  3012. *
  3013. * @type {UniformGroupNode}
  3014. */
  3015. this.groupNode = objectGroup;
  3016. }
  3017. /**
  3018. * Sets the {@link UniformNode#name} property.
  3019. *
  3020. * @param {string} name - The name of the uniform.
  3021. * @return {UniformNode} A reference to this node.
  3022. */
  3023. label( name ) {
  3024. this.name = name;
  3025. return this;
  3026. }
  3027. /**
  3028. * Sets the {@link UniformNode#groupNode} property.
  3029. *
  3030. * @param {UniformGroupNode} group - The uniform group.
  3031. * @return {UniformNode} A reference to this node.
  3032. */
  3033. setGroup( group ) {
  3034. this.groupNode = group;
  3035. return this;
  3036. }
  3037. /**
  3038. * Returns the {@link UniformNode#groupNode}.
  3039. *
  3040. * @return {UniformGroupNode} The uniform group.
  3041. */
  3042. getGroup() {
  3043. return this.groupNode;
  3044. }
  3045. /**
  3046. * By default, this method returns the result of {@link Node#getHash} but derived
  3047. * classes might overwrite this method with a different implementation.
  3048. *
  3049. * @param {NodeBuilder} builder - The current node builder.
  3050. * @return {string} The uniform hash.
  3051. */
  3052. getUniformHash( builder ) {
  3053. return this.getHash( builder );
  3054. }
  3055. onUpdate( callback, updateType ) {
  3056. const self = this.getSelf();
  3057. callback = callback.bind( self );
  3058. return super.onUpdate( ( frame ) => {
  3059. const value = callback( frame, self );
  3060. if ( value !== undefined ) {
  3061. this.value = value;
  3062. }
  3063. }, updateType );
  3064. }
  3065. generate( builder, output ) {
  3066. const type = this.getNodeType( builder );
  3067. const hash = this.getUniformHash( builder );
  3068. let sharedNode = builder.getNodeFromHash( hash );
  3069. if ( sharedNode === undefined ) {
  3070. builder.setHashNode( this, hash );
  3071. sharedNode = this;
  3072. }
  3073. const sharedNodeType = sharedNode.getInputType( builder );
  3074. const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, this.name || builder.context.label );
  3075. const propertyName = builder.getPropertyName( nodeUniform );
  3076. if ( builder.context.label !== undefined ) delete builder.context.label;
  3077. return builder.format( propertyName, type, output );
  3078. }
  3079. }
  3080. /**
  3081. * TSL function for creating a uniform node.
  3082. *
  3083. * @tsl
  3084. * @function
  3085. * @param {any} arg1 - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  3086. * @param {string} [arg2] - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  3087. * @returns {UniformNode}
  3088. */
  3089. const uniform = ( arg1, arg2 ) => {
  3090. const nodeType = getConstNodeType( arg2 || arg1 );
  3091. // @TODO: get ConstNode from .traverse() in the future
  3092. const value = ( arg1 && arg1.isNode === true ) ? ( arg1.node && arg1.node.value ) || arg1.value : arg1;
  3093. return nodeObject( new UniformNode( value, nodeType ) );
  3094. };
  3095. /**
  3096. * ArrayNode represents a collection of nodes, typically created using the {@link array} function.
  3097. * ```js
  3098. * const colors = array( [
  3099. * vec3( 1, 0, 0 ),
  3100. * vec3( 0, 1, 0 ),
  3101. * vec3( 0, 0, 1 )
  3102. * ] );
  3103. *
  3104. * const redColor = tintColors.element( 0 );
  3105. *
  3106. * @augments TempNode
  3107. */
  3108. class ArrayNode extends TempNode {
  3109. static get type() {
  3110. return 'ArrayNode';
  3111. }
  3112. /**
  3113. * Constructs a new array node.
  3114. *
  3115. * @param {?string} nodeType - The data type of the elements.
  3116. * @param {number} count - Size of the array.
  3117. * @param {?Array<Node>} [values=null] - Array default values.
  3118. */
  3119. constructor( nodeType, count, values = null ) {
  3120. super( nodeType );
  3121. /**
  3122. * Array size.
  3123. *
  3124. * @type {number}
  3125. */
  3126. this.count = count;
  3127. /**
  3128. * Array default values.
  3129. *
  3130. * @type {?Array<Node>}
  3131. */
  3132. this.values = values;
  3133. /**
  3134. * This flag can be used for type testing.
  3135. *
  3136. * @type {boolean}
  3137. * @readonly
  3138. * @default true
  3139. */
  3140. this.isArrayNode = true;
  3141. }
  3142. /**
  3143. * Returns the node's type.
  3144. *
  3145. * @param {NodeBuilder} builder - The current node builder.
  3146. * @return {string} The type of the node.
  3147. */
  3148. getNodeType( builder ) {
  3149. if ( this.nodeType === null ) {
  3150. this.nodeType = this.values[ 0 ].getNodeType( builder );
  3151. }
  3152. return this.nodeType;
  3153. }
  3154. /**
  3155. * Returns the node's type.
  3156. *
  3157. * @param {NodeBuilder} builder - The current node builder.
  3158. * @return {string} The type of the node.
  3159. */
  3160. getElementType( builder ) {
  3161. return this.getNodeType( builder );
  3162. }
  3163. /**
  3164. * This method builds the output node and returns the resulting array as a shader string.
  3165. *
  3166. * @param {NodeBuilder} builder - The current node builder.
  3167. * @return {string} The generated shader string.
  3168. */
  3169. generate( builder ) {
  3170. const type = this.getNodeType( builder );
  3171. return builder.generateArray( type, this.count, this.values );
  3172. }
  3173. }
  3174. /**
  3175. * TSL function for creating an array node.
  3176. *
  3177. * @tsl
  3178. * @function
  3179. * @param {string|Array<Node>} nodeTypeOrValues - A string representing the element type (e.g., 'vec3')
  3180. * or an array containing the default values (e.g., [ vec3() ]).
  3181. * @param {?number} [count] - Size of the array.
  3182. * @returns {ArrayNode}
  3183. */
  3184. const array = ( ...params ) => {
  3185. let node;
  3186. if ( params.length === 1 ) {
  3187. const values = params[ 0 ];
  3188. node = new ArrayNode( null, values.length, values );
  3189. } else {
  3190. const nodeType = params[ 0 ];
  3191. const count = params[ 1 ];
  3192. node = new ArrayNode( nodeType, count );
  3193. }
  3194. return nodeObject( node );
  3195. };
  3196. addMethodChaining( 'toArray', ( node, count ) => array( Array( count ).fill( node ) ) );
  3197. /**
  3198. * These node represents an assign operation. Meaning a node is assigned
  3199. * to another node.
  3200. *
  3201. * @augments TempNode
  3202. */
  3203. class AssignNode extends TempNode {
  3204. static get type() {
  3205. return 'AssignNode';
  3206. }
  3207. /**
  3208. * Constructs a new assign node.
  3209. *
  3210. * @param {Node} targetNode - The target node.
  3211. * @param {Node} sourceNode - The source type.
  3212. */
  3213. constructor( targetNode, sourceNode ) {
  3214. super();
  3215. /**
  3216. * The target node.
  3217. *
  3218. * @type {Node}
  3219. */
  3220. this.targetNode = targetNode;
  3221. /**
  3222. * The source node.
  3223. *
  3224. * @type {Node}
  3225. */
  3226. this.sourceNode = sourceNode;
  3227. /**
  3228. * This flag can be used for type testing.
  3229. *
  3230. * @type {boolean}
  3231. * @readonly
  3232. * @default true
  3233. */
  3234. this.isAssignNode = true;
  3235. }
  3236. /**
  3237. * Whether this node is used more than once in context of other nodes. This method
  3238. * is overwritten since it always returns `false` (assigns are unique).
  3239. *
  3240. * @return {boolean} A flag that indicates if there is more than one dependency to other nodes. Always `false`.
  3241. */
  3242. hasDependencies() {
  3243. return false;
  3244. }
  3245. getNodeType( builder, output ) {
  3246. return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void';
  3247. }
  3248. /**
  3249. * Whether a split is required when assigning source to target. This can happen when the component length of
  3250. * target and source data type does not match.
  3251. *
  3252. * @param {NodeBuilder} builder - The current node builder.
  3253. * @return {boolean} Whether a split is required when assigning source to target.
  3254. */
  3255. needsSplitAssign( builder ) {
  3256. const { targetNode } = this;
  3257. if ( builder.isAvailable( 'swizzleAssign' ) === false && targetNode.isSplitNode && targetNode.components.length > 1 ) {
  3258. const targetLength = builder.getTypeLength( targetNode.node.getNodeType( builder ) );
  3259. const assignDifferentVector = vectorComponents.join( '' ).slice( 0, targetLength ) !== targetNode.components;
  3260. return assignDifferentVector;
  3261. }
  3262. return false;
  3263. }
  3264. setup( builder ) {
  3265. const { targetNode, sourceNode } = this;
  3266. const properties = builder.getNodeProperties( this );
  3267. properties.sourceNode = sourceNode;
  3268. properties.targetNode = targetNode.context( { assign: true } );
  3269. }
  3270. generate( builder, output ) {
  3271. const { targetNode, sourceNode } = builder.getNodeProperties( this );
  3272. const needsSplitAssign = this.needsSplitAssign( builder );
  3273. const targetType = targetNode.getNodeType( builder );
  3274. const target = targetNode.build( builder );
  3275. const source = sourceNode.build( builder, targetType );
  3276. const sourceType = sourceNode.getNodeType( builder );
  3277. const nodeData = builder.getDataFromNode( this );
  3278. //
  3279. let snippet;
  3280. if ( nodeData.initialized === true ) {
  3281. if ( output !== 'void' ) {
  3282. snippet = target;
  3283. }
  3284. } else if ( needsSplitAssign ) {
  3285. const sourceVar = builder.getVarFromNode( this, null, targetType );
  3286. const sourceProperty = builder.getPropertyName( sourceVar );
  3287. builder.addLineFlowCode( `${ sourceProperty } = ${ source }`, this );
  3288. const splitNode = targetNode.node;
  3289. const splitTargetNode = splitNode.node.context( { assign: true } );
  3290. const targetRoot = splitTargetNode.build( builder );
  3291. for ( let i = 0; i < splitNode.components.length; i ++ ) {
  3292. const component = splitNode.components[ i ];
  3293. builder.addLineFlowCode( `${ targetRoot }.${ component } = ${ sourceProperty }[ ${ i } ]`, this );
  3294. }
  3295. if ( output !== 'void' ) {
  3296. snippet = target;
  3297. }
  3298. } else {
  3299. snippet = `${ target } = ${ source }`;
  3300. if ( output === 'void' || sourceType === 'void' ) {
  3301. builder.addLineFlowCode( snippet, this );
  3302. if ( output !== 'void' ) {
  3303. snippet = target;
  3304. }
  3305. }
  3306. }
  3307. nodeData.initialized = true;
  3308. return builder.format( snippet, targetType, output );
  3309. }
  3310. }
  3311. /**
  3312. * TSL function for creating an assign node.
  3313. *
  3314. * @tsl
  3315. * @function
  3316. * @param {Node} targetNode - The target node.
  3317. * @param {Node} sourceNode - The source type.
  3318. * @returns {AssignNode}
  3319. */
  3320. const assign = /*@__PURE__*/ nodeProxy( AssignNode ).setParameterLength( 2 );
  3321. addMethodChaining( 'assign', assign );
  3322. /**
  3323. * This module represents the call of a {@link FunctionNode}. Developers are usually not confronted
  3324. * with this module since they use the predefined TSL syntax `wgslFn` and `glslFn` which encapsulate
  3325. * this logic.
  3326. *
  3327. * @augments TempNode
  3328. */
  3329. class FunctionCallNode extends TempNode {
  3330. static get type() {
  3331. return 'FunctionCallNode';
  3332. }
  3333. /**
  3334. * Constructs a new function call node.
  3335. *
  3336. * @param {?FunctionNode} functionNode - The function node.
  3337. * @param {Object<string, Node>} [parameters={}] - The parameters for the function call.
  3338. */
  3339. constructor( functionNode = null, parameters = {} ) {
  3340. super();
  3341. /**
  3342. * The function node.
  3343. *
  3344. * @type {?FunctionNode}
  3345. * @default null
  3346. */
  3347. this.functionNode = functionNode;
  3348. /**
  3349. * The parameters of the function call.
  3350. *
  3351. * @type {Object<string, Node>}
  3352. * @default {}
  3353. */
  3354. this.parameters = parameters;
  3355. }
  3356. /**
  3357. * Sets the parameters of the function call node.
  3358. *
  3359. * @param {Object<string, Node>} parameters - The parameters to set.
  3360. * @return {FunctionCallNode} A reference to this node.
  3361. */
  3362. setParameters( parameters ) {
  3363. this.parameters = parameters;
  3364. return this;
  3365. }
  3366. /**
  3367. * Returns the parameters of the function call node.
  3368. *
  3369. * @return {Object<string, Node>} The parameters of this node.
  3370. */
  3371. getParameters() {
  3372. return this.parameters;
  3373. }
  3374. getNodeType( builder ) {
  3375. return this.functionNode.getNodeType( builder );
  3376. }
  3377. generate( builder ) {
  3378. const params = [];
  3379. const functionNode = this.functionNode;
  3380. const inputs = functionNode.getInputs( builder );
  3381. const parameters = this.parameters;
  3382. const generateInput = ( node, inputNode ) => {
  3383. const type = inputNode.type;
  3384. const pointer = type === 'pointer';
  3385. let output;
  3386. if ( pointer ) output = '&' + node.build( builder );
  3387. else output = node.build( builder, type );
  3388. return output;
  3389. };
  3390. if ( Array.isArray( parameters ) ) {
  3391. if ( parameters.length > inputs.length ) {
  3392. console.error( 'THREE.TSL: The number of provided parameters exceeds the expected number of inputs in \'Fn()\'.' );
  3393. parameters.length = inputs.length;
  3394. } else if ( parameters.length < inputs.length ) {
  3395. console.error( 'THREE.TSL: The number of provided parameters is less than the expected number of inputs in \'Fn()\'.' );
  3396. while ( parameters.length < inputs.length ) {
  3397. parameters.push( float( 0 ) );
  3398. }
  3399. }
  3400. for ( let i = 0; i < parameters.length; i ++ ) {
  3401. params.push( generateInput( parameters[ i ], inputs[ i ] ) );
  3402. }
  3403. } else {
  3404. for ( const inputNode of inputs ) {
  3405. const node = parameters[ inputNode.name ];
  3406. if ( node !== undefined ) {
  3407. params.push( generateInput( node, inputNode ) );
  3408. } else {
  3409. console.error( `THREE.TSL: Input '${ inputNode.name }' not found in \'Fn()\'.` );
  3410. params.push( generateInput( float( 0 ), inputNode ) );
  3411. }
  3412. }
  3413. }
  3414. const functionName = functionNode.build( builder, 'property' );
  3415. return `${ functionName }( ${ params.join( ', ' ) } )`;
  3416. }
  3417. }
  3418. const call = ( func, ...params ) => {
  3419. params = params.length > 1 || ( params[ 0 ] && params[ 0 ].isNode === true ) ? nodeArray( params ) : nodeObjects( params[ 0 ] );
  3420. return nodeObject( new FunctionCallNode( nodeObject( func ), params ) );
  3421. };
  3422. addMethodChaining( 'call', call );
  3423. const _vectorOperators = {
  3424. '==': 'equal',
  3425. '!=': 'notEqual',
  3426. '<': 'lessThan',
  3427. '>': 'greaterThan',
  3428. '<=': 'lessThanEqual',
  3429. '>=': 'greaterThanEqual',
  3430. '%': 'mod'
  3431. };
  3432. /**
  3433. * This node represents basic mathematical and logical operations like addition,
  3434. * subtraction or comparisons (e.g. `equal()`).
  3435. *
  3436. * @augments TempNode
  3437. */
  3438. class OperatorNode extends TempNode {
  3439. static get type() {
  3440. return 'OperatorNode';
  3441. }
  3442. /**
  3443. * Constructs a new operator node.
  3444. *
  3445. * @param {string} op - The operator.
  3446. * @param {Node} aNode - The first input.
  3447. * @param {Node} bNode - The second input.
  3448. * @param {...Node} params - Additional input parameters.
  3449. */
  3450. constructor( op, aNode, bNode, ...params ) {
  3451. super();
  3452. if ( params.length > 0 ) {
  3453. let finalOp = new OperatorNode( op, aNode, bNode );
  3454. for ( let i = 0; i < params.length - 1; i ++ ) {
  3455. finalOp = new OperatorNode( op, finalOp, params[ i ] );
  3456. }
  3457. aNode = finalOp;
  3458. bNode = params[ params.length - 1 ];
  3459. }
  3460. /**
  3461. * The operator.
  3462. *
  3463. * @type {string}
  3464. */
  3465. this.op = op;
  3466. /**
  3467. * The first input.
  3468. *
  3469. * @type {Node}
  3470. */
  3471. this.aNode = aNode;
  3472. /**
  3473. * The second input.
  3474. *
  3475. * @type {Node}
  3476. */
  3477. this.bNode = bNode;
  3478. /**
  3479. * This flag can be used for type testing.
  3480. *
  3481. * @type {boolean}
  3482. * @readonly
  3483. * @default true
  3484. */
  3485. this.isOperatorNode = true;
  3486. }
  3487. /**
  3488. * Returns the operator method name.
  3489. *
  3490. * @param {NodeBuilder} builder - The current node builder.
  3491. * @param {string} output - The output type.
  3492. * @returns {string} The operator method name.
  3493. */
  3494. getOperatorMethod( builder, output ) {
  3495. return builder.getMethod( _vectorOperators[ this.op ], output );
  3496. }
  3497. /**
  3498. * This method is overwritten since the node type is inferred from the operator
  3499. * and the input node types.
  3500. *
  3501. * @param {NodeBuilder} builder - The current node builder.
  3502. * @return {string} The node type.
  3503. */
  3504. getNodeType( builder ) {
  3505. const op = this.op;
  3506. const aNode = this.aNode;
  3507. const bNode = this.bNode;
  3508. const typeA = aNode.getNodeType( builder );
  3509. const typeB = bNode ? bNode.getNodeType( builder ) : null;
  3510. if ( typeA === 'void' || typeB === 'void' ) {
  3511. return 'void';
  3512. } else if ( op === '%' ) {
  3513. return typeA;
  3514. } else if ( op === '~' || op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) {
  3515. return builder.getIntegerType( typeA );
  3516. } else if ( op === '!' || op === '&&' || op === '||' || op === '^^' ) {
  3517. return 'bool';
  3518. } else if ( op === '==' || op === '!=' || op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  3519. const typeLength = Math.max( builder.getTypeLength( typeA ), builder.getTypeLength( typeB ) );
  3520. return typeLength > 1 ? `bvec${ typeLength }` : 'bool';
  3521. } else {
  3522. // Handle matrix operations
  3523. if ( builder.isMatrix( typeA ) ) {
  3524. if ( typeB === 'float' ) {
  3525. return typeA; // matrix * scalar = matrix
  3526. } else if ( builder.isVector( typeB ) ) {
  3527. return builder.getVectorFromMatrix( typeA ); // matrix * vector
  3528. } else if ( builder.isMatrix( typeB ) ) {
  3529. return typeA; // matrix * matrix
  3530. }
  3531. } else if ( builder.isMatrix( typeB ) ) {
  3532. if ( typeA === 'float' ) {
  3533. return typeB; // scalar * matrix = matrix
  3534. } else if ( builder.isVector( typeA ) ) {
  3535. return builder.getVectorFromMatrix( typeB ); // vector * matrix
  3536. }
  3537. }
  3538. // Handle non-matrix cases
  3539. if ( builder.getTypeLength( typeB ) > builder.getTypeLength( typeA ) ) {
  3540. // anytype x anytype: use the greater length vector
  3541. return typeB;
  3542. }
  3543. return typeA;
  3544. }
  3545. }
  3546. generate( builder, output ) {
  3547. const op = this.op;
  3548. const { aNode, bNode } = this;
  3549. const type = this.getNodeType( builder );
  3550. let typeA = null;
  3551. let typeB = null;
  3552. if ( type !== 'void' ) {
  3553. typeA = aNode.getNodeType( builder );
  3554. typeB = bNode ? bNode.getNodeType( builder ) : null;
  3555. if ( op === '<' || op === '>' || op === '<=' || op === '>=' || op === '==' || op === '!=' ) {
  3556. if ( builder.isVector( typeA ) ) {
  3557. typeB = typeA;
  3558. } else if ( builder.isVector( typeB ) ) {
  3559. typeA = typeB;
  3560. } else if ( typeA !== typeB ) {
  3561. typeA = typeB = 'float';
  3562. }
  3563. } else if ( op === '>>' || op === '<<' ) {
  3564. typeA = type;
  3565. typeB = builder.changeComponentType( typeB, 'uint' );
  3566. } else if ( op === '%' ) {
  3567. typeA = type;
  3568. typeB = builder.isInteger( typeA ) && builder.isInteger( typeB ) ? typeB : typeA;
  3569. } else if ( builder.isMatrix( typeA ) ) {
  3570. if ( typeB === 'float' ) {
  3571. // Keep matrix type for typeA, but ensure typeB stays float
  3572. typeB = 'float';
  3573. } else if ( builder.isVector( typeB ) ) {
  3574. // matrix x vector
  3575. typeB = builder.getVectorFromMatrix( typeA );
  3576. } else if ( builder.isMatrix( typeB ) ) ; else {
  3577. typeA = typeB = type;
  3578. }
  3579. } else if ( builder.isMatrix( typeB ) ) {
  3580. if ( typeA === 'float' ) {
  3581. // Keep matrix type for typeB, but ensure typeA stays float
  3582. typeA = 'float';
  3583. } else if ( builder.isVector( typeA ) ) {
  3584. // vector x matrix
  3585. typeA = builder.getVectorFromMatrix( typeB );
  3586. } else {
  3587. typeA = typeB = type;
  3588. }
  3589. } else {
  3590. // anytype x anytype
  3591. typeA = typeB = type;
  3592. }
  3593. } else {
  3594. typeA = typeB = type;
  3595. }
  3596. const a = aNode.build( builder, typeA );
  3597. const b = bNode ? bNode.build( builder, typeB ) : null;
  3598. const fnOpSnippet = builder.getFunctionOperator( op );
  3599. if ( output !== 'void' ) {
  3600. const isGLSL = builder.renderer.coordinateSystem === WebGLCoordinateSystem;
  3601. if ( op === '==' || op === '!=' || op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  3602. if ( isGLSL ) {
  3603. if ( builder.isVector( typeA ) ) {
  3604. return builder.format( `${ this.getOperatorMethod( builder, output ) }( ${ a }, ${ b } )`, type, output );
  3605. } else {
  3606. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  3607. }
  3608. } else {
  3609. // WGSL
  3610. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  3611. }
  3612. } else if ( op === '%' ) {
  3613. if ( builder.isInteger( typeB ) ) {
  3614. return builder.format( `( ${ a } % ${ b } )`, type, output );
  3615. } else {
  3616. return builder.format( `${ this.getOperatorMethod( builder, type ) }( ${ a }, ${ b } )`, type, output );
  3617. }
  3618. } else if ( op === '!' || op === '~' ) {
  3619. return builder.format( `(${op}${a})`, typeA, output );
  3620. } else if ( fnOpSnippet ) {
  3621. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  3622. } else {
  3623. // Handle matrix operations
  3624. if ( builder.isMatrix( typeA ) && typeB === 'float' ) {
  3625. return builder.format( `( ${ b } ${ op } ${ a } )`, type, output );
  3626. } else if ( typeA === 'float' && builder.isMatrix( typeB ) ) {
  3627. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  3628. } else {
  3629. let snippet = `( ${ a } ${ op } ${ b } )`;
  3630. if ( ! isGLSL && type === 'bool' && builder.isVector( typeA ) && builder.isVector( typeB ) ) {
  3631. snippet = `all${ snippet }`;
  3632. }
  3633. return builder.format( snippet, type, output );
  3634. }
  3635. }
  3636. } else if ( typeA !== 'void' ) {
  3637. if ( fnOpSnippet ) {
  3638. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  3639. } else {
  3640. if ( builder.isMatrix( typeA ) && typeB === 'float' ) {
  3641. return builder.format( `${ b } ${ op } ${ a }`, type, output );
  3642. } else {
  3643. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  3644. }
  3645. }
  3646. }
  3647. }
  3648. serialize( data ) {
  3649. super.serialize( data );
  3650. data.op = this.op;
  3651. }
  3652. deserialize( data ) {
  3653. super.deserialize( data );
  3654. this.op = data.op;
  3655. }
  3656. }
  3657. /**
  3658. * Returns the addition of two or more value.
  3659. *
  3660. * @tsl
  3661. * @function
  3662. * @param {Node} a - The first input.
  3663. * @param {Node} b - The second input.
  3664. * @param {...Node} params - Additional input parameters.
  3665. * @returns {OperatorNode}
  3666. */
  3667. const add = /*@__PURE__*/ nodeProxy( OperatorNode, '+' ).setParameterLength( 2, Infinity ).setName( 'add' );
  3668. /**
  3669. * Returns the subtraction of two or more value.
  3670. *
  3671. * @tsl
  3672. * @function
  3673. * @param {Node} a - The first input.
  3674. * @param {Node} b - The second input.
  3675. * @param {...Node} params - Additional input parameters.
  3676. * @returns {OperatorNode}
  3677. */
  3678. const sub = /*@__PURE__*/ nodeProxy( OperatorNode, '-' ).setParameterLength( 2, Infinity ).setName( 'sub' );
  3679. /**
  3680. * Returns the multiplication of two or more value.
  3681. *
  3682. * @tsl
  3683. * @function
  3684. * @param {Node} a - The first input.
  3685. * @param {Node} b - The second input.
  3686. * @param {...Node} params - Additional input parameters.
  3687. * @returns {OperatorNode}
  3688. */
  3689. const mul = /*@__PURE__*/ nodeProxy( OperatorNode, '*' ).setParameterLength( 2, Infinity ).setName( 'mul' );
  3690. /**
  3691. * Returns the division of two or more value.
  3692. *
  3693. * @tsl
  3694. * @function
  3695. * @param {Node} a - The first input.
  3696. * @param {Node} b - The second input.
  3697. * @param {...Node} params - Additional input parameters.
  3698. * @returns {OperatorNode}
  3699. */
  3700. const div = /*@__PURE__*/ nodeProxy( OperatorNode, '/' ).setParameterLength( 2, Infinity ).setName( 'div' );
  3701. /**
  3702. * Computes the remainder of dividing the first node by the second one.
  3703. *
  3704. * @tsl
  3705. * @function
  3706. * @param {Node} a - The first input.
  3707. * @param {Node} b - The second input.
  3708. * @returns {OperatorNode}
  3709. */
  3710. const mod = /*@__PURE__*/ nodeProxy( OperatorNode, '%' ).setParameterLength( 2 ).setName( 'mod' );
  3711. /**
  3712. * Checks if two nodes are equal.
  3713. *
  3714. * @tsl
  3715. * @function
  3716. * @param {Node} a - The first input.
  3717. * @param {Node} b - The second input.
  3718. * @returns {OperatorNode}
  3719. */
  3720. const equal = /*@__PURE__*/ nodeProxy( OperatorNode, '==' ).setParameterLength( 2 ).setName( 'equal' );
  3721. /**
  3722. * Checks if two nodes are not equal.
  3723. *
  3724. * @tsl
  3725. * @function
  3726. * @param {Node} a - The first input.
  3727. * @param {Node} b - The second input.
  3728. * @returns {OperatorNode}
  3729. */
  3730. const notEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '!=' ).setParameterLength( 2 ).setName( 'notEqual' );
  3731. /**
  3732. * Checks if the first node is less than the second.
  3733. *
  3734. * @tsl
  3735. * @function
  3736. * @param {Node} a - The first input.
  3737. * @param {Node} b - The second input.
  3738. * @returns {OperatorNode}
  3739. */
  3740. const lessThan = /*@__PURE__*/ nodeProxy( OperatorNode, '<' ).setParameterLength( 2 ).setName( 'lessThan' );
  3741. /**
  3742. * Checks if the first node is greater than the second.
  3743. *
  3744. * @tsl
  3745. * @function
  3746. * @param {Node} a - The first input.
  3747. * @param {Node} b - The second input.
  3748. * @returns {OperatorNode}
  3749. */
  3750. const greaterThan = /*@__PURE__*/ nodeProxy( OperatorNode, '>' ).setParameterLength( 2 ).setName( 'greaterThan' );
  3751. /**
  3752. * Checks if the first node is less than or equal to the second.
  3753. *
  3754. * @tsl
  3755. * @function
  3756. * @param {Node} a - The first input.
  3757. * @param {Node} b - The second input.
  3758. * @returns {OperatorNode}
  3759. */
  3760. const lessThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '<=' ).setParameterLength( 2 ).setName( 'lessThanEqual' );
  3761. /**
  3762. * Checks if the first node is greater than or equal to the second.
  3763. *
  3764. * @tsl
  3765. * @function
  3766. * @param {Node} a - The first input.
  3767. * @param {Node} b - The second input.
  3768. * @returns {OperatorNode}
  3769. */
  3770. const greaterThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '>=' ).setParameterLength( 2 ).setName( 'greaterThanEqual' );
  3771. /**
  3772. * Performs a logical AND operation on multiple nodes.
  3773. *
  3774. * @tsl
  3775. * @function
  3776. * @param {...Node} nodes - The input nodes to be combined using AND.
  3777. * @returns {OperatorNode}
  3778. */
  3779. const and = /*@__PURE__*/ nodeProxy( OperatorNode, '&&' ).setParameterLength( 2, Infinity ).setName( 'and' );
  3780. /**
  3781. * Performs a logical OR operation on multiple nodes.
  3782. *
  3783. * @tsl
  3784. * @function
  3785. * @param {...Node} nodes - The input nodes to be combined using OR.
  3786. * @returns {OperatorNode}
  3787. */
  3788. const or = /*@__PURE__*/ nodeProxy( OperatorNode, '||' ).setParameterLength( 2, Infinity ).setName( 'or' );
  3789. /**
  3790. * Performs logical NOT on a node.
  3791. *
  3792. * @tsl
  3793. * @function
  3794. * @param {Node} value - The value.
  3795. * @returns {OperatorNode}
  3796. */
  3797. const not = /*@__PURE__*/ nodeProxy( OperatorNode, '!' ).setParameterLength( 1 ).setName( 'not' );
  3798. /**
  3799. * Performs logical XOR on two nodes.
  3800. *
  3801. * @tsl
  3802. * @function
  3803. * @param {Node} a - The first input.
  3804. * @param {Node} b - The second input.
  3805. * @returns {OperatorNode}
  3806. */
  3807. const xor = /*@__PURE__*/ nodeProxy( OperatorNode, '^^' ).setParameterLength( 2 ).setName( 'xor' );
  3808. /**
  3809. * Performs bitwise AND on two nodes.
  3810. *
  3811. * @tsl
  3812. * @function
  3813. * @param {Node} a - The first input.
  3814. * @param {Node} b - The second input.
  3815. * @returns {OperatorNode}
  3816. */
  3817. const bitAnd = /*@__PURE__*/ nodeProxy( OperatorNode, '&' ).setParameterLength( 2 ).setName( 'bitAnd' );
  3818. /**
  3819. * Performs bitwise NOT on a node.
  3820. *
  3821. * @tsl
  3822. * @function
  3823. * @param {Node} a - The first input.
  3824. * @param {Node} b - The second input.
  3825. * @returns {OperatorNode}
  3826. */
  3827. const bitNot = /*@__PURE__*/ nodeProxy( OperatorNode, '~' ).setParameterLength( 2 ).setName( 'bitNot' );
  3828. /**
  3829. * Performs bitwise OR on two nodes.
  3830. *
  3831. * @tsl
  3832. * @function
  3833. * @param {Node} a - The first input.
  3834. * @param {Node} b - The second input.
  3835. * @returns {OperatorNode}
  3836. */
  3837. const bitOr = /*@__PURE__*/ nodeProxy( OperatorNode, '|' ).setParameterLength( 2 ).setName( 'bitOr' );
  3838. /**
  3839. * Performs bitwise XOR on two nodes.
  3840. *
  3841. * @tsl
  3842. * @function
  3843. * @param {Node} a - The first input.
  3844. * @param {Node} b - The second input.
  3845. * @returns {OperatorNode}
  3846. */
  3847. const bitXor = /*@__PURE__*/ nodeProxy( OperatorNode, '^' ).setParameterLength( 2 ).setName( 'bitXor' );
  3848. /**
  3849. * Shifts a node to the left.
  3850. *
  3851. * @tsl
  3852. * @function
  3853. * @param {Node} a - The node to shift.
  3854. * @param {Node} b - The value to shift.
  3855. * @returns {OperatorNode}
  3856. */
  3857. const shiftLeft = /*@__PURE__*/ nodeProxy( OperatorNode, '<<' ).setParameterLength( 2 ).setName( 'shiftLeft' );
  3858. /**
  3859. * Shifts a node to the right.
  3860. *
  3861. * @tsl
  3862. * @function
  3863. * @param {Node} a - The node to shift.
  3864. * @param {Node} b - The value to shift.
  3865. * @returns {OperatorNode}
  3866. */
  3867. const shiftRight = /*@__PURE__*/ nodeProxy( OperatorNode, '>>' ).setParameterLength( 2 ).setName( 'shiftRight' );
  3868. /**
  3869. * Increments a node by 1.
  3870. *
  3871. * @tsl
  3872. * @function
  3873. * @param {Node} a - The node to increment.
  3874. * @returns {OperatorNode}
  3875. */
  3876. const incrementBefore = Fn( ( [ a ] ) => {
  3877. a.addAssign( 1 );
  3878. return a;
  3879. } );
  3880. /**
  3881. * Decrements a node by 1.
  3882. *
  3883. * @tsl
  3884. * @function
  3885. * @param {Node} a - The node to decrement.
  3886. * @returns {OperatorNode}
  3887. */
  3888. const decrementBefore = Fn( ( [ a ] ) => {
  3889. a.subAssign( 1 );
  3890. return a;
  3891. } );
  3892. /**
  3893. * Increments a node by 1 and returns the previous value.
  3894. *
  3895. * @tsl
  3896. * @function
  3897. * @param {Node} a - The node to increment.
  3898. * @returns {OperatorNode}
  3899. */
  3900. const increment = /*@__PURE__*/ Fn( ( [ a ] ) => {
  3901. const temp = int( a ).toConst();
  3902. a.addAssign( 1 );
  3903. return temp;
  3904. } );
  3905. /**
  3906. * Decrements a node by 1 and returns the previous value.
  3907. *
  3908. * @tsl
  3909. * @function
  3910. * @param {Node} a - The node to decrement.
  3911. * @returns {OperatorNode}
  3912. */
  3913. const decrement = /*@__PURE__*/ Fn( ( [ a ] ) => {
  3914. const temp = int( a ).toConst();
  3915. a.subAssign( 1 );
  3916. return temp;
  3917. } );
  3918. addMethodChaining( 'add', add );
  3919. addMethodChaining( 'sub', sub );
  3920. addMethodChaining( 'mul', mul );
  3921. addMethodChaining( 'div', div );
  3922. addMethodChaining( 'mod', mod );
  3923. addMethodChaining( 'equal', equal );
  3924. addMethodChaining( 'notEqual', notEqual );
  3925. addMethodChaining( 'lessThan', lessThan );
  3926. addMethodChaining( 'greaterThan', greaterThan );
  3927. addMethodChaining( 'lessThanEqual', lessThanEqual );
  3928. addMethodChaining( 'greaterThanEqual', greaterThanEqual );
  3929. addMethodChaining( 'and', and );
  3930. addMethodChaining( 'or', or );
  3931. addMethodChaining( 'not', not );
  3932. addMethodChaining( 'xor', xor );
  3933. addMethodChaining( 'bitAnd', bitAnd );
  3934. addMethodChaining( 'bitNot', bitNot );
  3935. addMethodChaining( 'bitOr', bitOr );
  3936. addMethodChaining( 'bitXor', bitXor );
  3937. addMethodChaining( 'shiftLeft', shiftLeft );
  3938. addMethodChaining( 'shiftRight', shiftRight );
  3939. addMethodChaining( 'incrementBefore', incrementBefore );
  3940. addMethodChaining( 'decrementBefore', decrementBefore );
  3941. addMethodChaining( 'increment', increment );
  3942. addMethodChaining( 'decrement', decrement );
  3943. /**
  3944. * @tsl
  3945. * @function
  3946. * @deprecated since r168. Use {@link mod} instead.
  3947. *
  3948. * @param {Node} a - The first input.
  3949. * @param {Node} b - The second input.
  3950. * @returns {OperatorNode}
  3951. */
  3952. const remainder = ( a, b ) => { // @deprecated, r168
  3953. console.warn( 'THREE.TSL: "remainder()" is deprecated. Use "mod( int( ... ) )" instead.' );
  3954. return mod( a, b );
  3955. };
  3956. /**
  3957. * @tsl
  3958. * @function
  3959. * @deprecated since r175. Use {@link mod} instead.
  3960. *
  3961. * @param {Node} a - The first input.
  3962. * @param {Node} b - The second input.
  3963. * @returns {OperatorNode}
  3964. */
  3965. const modInt = ( a, b ) => { // @deprecated, r175
  3966. console.warn( 'THREE.TSL: "modInt()" is deprecated. Use "mod( int( ... ) )" instead.' );
  3967. return mod( int( a ), int( b ) );
  3968. };
  3969. addMethodChaining( 'remainder', remainder );
  3970. addMethodChaining( 'modInt', modInt );
  3971. /**
  3972. * This node represents a variety of mathematical methods available in shaders.
  3973. * They are divided into three categories:
  3974. *
  3975. * - Methods with one input like `sin`, `cos` or `normalize`.
  3976. * - Methods with two inputs like `dot`, `cross` or `pow`.
  3977. * - Methods with three inputs like `mix`, `clamp` or `smoothstep`.
  3978. *
  3979. * @augments TempNode
  3980. */
  3981. class MathNode extends TempNode {
  3982. static get type() {
  3983. return 'MathNode';
  3984. }
  3985. /**
  3986. * Constructs a new math node.
  3987. *
  3988. * @param {string} method - The method name.
  3989. * @param {Node} aNode - The first input.
  3990. * @param {?Node} [bNode=null] - The second input.
  3991. * @param {?Node} [cNode=null] - The third input.
  3992. */
  3993. constructor( method, aNode, bNode = null, cNode = null ) {
  3994. super();
  3995. // Allow the max() and min() functions to take an arbitrary number of arguments.
  3996. if ( ( method === MathNode.MAX || method === MathNode.MIN ) && arguments.length > 3 ) {
  3997. let finalOp = new MathNode( method, aNode, bNode );
  3998. for ( let i = 2; i < arguments.length - 1; i ++ ) {
  3999. finalOp = new MathNode( method, finalOp, arguments[ i ] );
  4000. }
  4001. aNode = finalOp;
  4002. bNode = arguments[ arguments.length - 1 ];
  4003. cNode = null;
  4004. }
  4005. /**
  4006. * The method name.
  4007. *
  4008. * @type {string}
  4009. */
  4010. this.method = method;
  4011. /**
  4012. * The first input.
  4013. *
  4014. * @type {Node}
  4015. */
  4016. this.aNode = aNode;
  4017. /**
  4018. * The second input.
  4019. *
  4020. * @type {?Node}
  4021. * @default null
  4022. */
  4023. this.bNode = bNode;
  4024. /**
  4025. * The third input.
  4026. *
  4027. * @type {?Node}
  4028. * @default null
  4029. */
  4030. this.cNode = cNode;
  4031. /**
  4032. * This flag can be used for type testing.
  4033. *
  4034. * @type {boolean}
  4035. * @readonly
  4036. * @default true
  4037. */
  4038. this.isMathNode = true;
  4039. }
  4040. /**
  4041. * The input type is inferred from the node types of the input nodes.
  4042. *
  4043. * @param {NodeBuilder} builder - The current node builder.
  4044. * @return {string} The input type.
  4045. */
  4046. getInputType( builder ) {
  4047. const aType = this.aNode.getNodeType( builder );
  4048. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  4049. const cType = this.cNode ? this.cNode.getNodeType( builder ) : null;
  4050. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  4051. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  4052. const cLen = builder.isMatrix( cType ) ? 0 : builder.getTypeLength( cType );
  4053. if ( aLen > bLen && aLen > cLen ) {
  4054. return aType;
  4055. } else if ( bLen > cLen ) {
  4056. return bType;
  4057. } else if ( cLen > aLen ) {
  4058. return cType;
  4059. }
  4060. return aType;
  4061. }
  4062. /**
  4063. * The selected method as well as the input type determine the node type of this node.
  4064. *
  4065. * @param {NodeBuilder} builder - The current node builder.
  4066. * @return {string} The node type.
  4067. */
  4068. getNodeType( builder ) {
  4069. const method = this.method;
  4070. if ( method === MathNode.LENGTH || method === MathNode.DISTANCE || method === MathNode.DOT ) {
  4071. return 'float';
  4072. } else if ( method === MathNode.CROSS ) {
  4073. return 'vec3';
  4074. } else if ( method === MathNode.ALL || method === MathNode.ANY ) {
  4075. return 'bool';
  4076. } else if ( method === MathNode.EQUALS ) {
  4077. return builder.changeComponentType( this.aNode.getNodeType( builder ), 'bool' );
  4078. } else {
  4079. return this.getInputType( builder );
  4080. }
  4081. }
  4082. setup( builder ) {
  4083. const { aNode, bNode, method } = this;
  4084. let outputNode = null;
  4085. if ( method === MathNode.ONE_MINUS ) {
  4086. outputNode = sub( 1.0, aNode );
  4087. } else if ( method === MathNode.RECIPROCAL ) {
  4088. outputNode = div( 1.0, aNode );
  4089. } else if ( method === MathNode.DIFFERENCE ) {
  4090. outputNode = abs( sub( aNode, bNode ) );
  4091. } else if ( method === MathNode.TRANSFORM_DIRECTION ) {
  4092. // dir can be either a direction vector or a normal vector
  4093. // upper-left 3x3 of matrix is assumed to be orthogonal
  4094. let tA = aNode;
  4095. let tB = bNode;
  4096. if ( builder.isMatrix( tA.getNodeType( builder ) ) ) {
  4097. tB = vec4( vec3( tB ), 0.0 );
  4098. } else {
  4099. tA = vec4( vec3( tA ), 0.0 );
  4100. }
  4101. const mulNode = mul( tA, tB ).xyz;
  4102. outputNode = normalize( mulNode );
  4103. }
  4104. if ( outputNode !== null ) {
  4105. return outputNode;
  4106. } else {
  4107. return super.setup( builder );
  4108. }
  4109. }
  4110. generate( builder, output ) {
  4111. const properties = builder.getNodeProperties( this );
  4112. if ( properties.outputNode ) {
  4113. return super.generate( builder, output );
  4114. }
  4115. let method = this.method;
  4116. const type = this.getNodeType( builder );
  4117. const inputType = this.getInputType( builder );
  4118. const a = this.aNode;
  4119. const b = this.bNode;
  4120. const c = this.cNode;
  4121. const coordinateSystem = builder.renderer.coordinateSystem;
  4122. if ( method === MathNode.NEGATE ) {
  4123. return builder.format( '( - ' + a.build( builder, inputType ) + ' )', type, output );
  4124. } else {
  4125. const params = [];
  4126. if ( method === MathNode.CROSS ) {
  4127. params.push(
  4128. a.build( builder, type ),
  4129. b.build( builder, type )
  4130. );
  4131. } else if ( coordinateSystem === WebGLCoordinateSystem && method === MathNode.STEP ) {
  4132. params.push(
  4133. a.build( builder, builder.getTypeLength( a.getNodeType( builder ) ) === 1 ? 'float' : inputType ),
  4134. b.build( builder, inputType )
  4135. );
  4136. } else if ( coordinateSystem === WebGLCoordinateSystem && ( method === MathNode.MIN || method === MathNode.MAX ) ) {
  4137. params.push(
  4138. a.build( builder, inputType ),
  4139. b.build( builder, builder.getTypeLength( b.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  4140. );
  4141. } else if ( method === MathNode.REFRACT ) {
  4142. params.push(
  4143. a.build( builder, inputType ),
  4144. b.build( builder, inputType ),
  4145. c.build( builder, 'float' )
  4146. );
  4147. } else if ( method === MathNode.MIX ) {
  4148. params.push(
  4149. a.build( builder, inputType ),
  4150. b.build( builder, inputType ),
  4151. c.build( builder, builder.getTypeLength( c.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  4152. );
  4153. } else {
  4154. if ( coordinateSystem === WebGPUCoordinateSystem && method === MathNode.ATAN && b !== null ) {
  4155. method = 'atan2';
  4156. }
  4157. if ( builder.shaderStage !== 'fragment' && ( method === MathNode.DFDX || method === MathNode.DFDY ) ) {
  4158. console.warn( `THREE.TSL: '${ method }' is not supported in the ${ builder.shaderStage } stage.` );
  4159. method = '/*' + method + '*/';
  4160. }
  4161. params.push( a.build( builder, inputType ) );
  4162. if ( b !== null ) params.push( b.build( builder, inputType ) );
  4163. if ( c !== null ) params.push( c.build( builder, inputType ) );
  4164. }
  4165. return builder.format( `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`, type, output );
  4166. }
  4167. }
  4168. serialize( data ) {
  4169. super.serialize( data );
  4170. data.method = this.method;
  4171. }
  4172. deserialize( data ) {
  4173. super.deserialize( data );
  4174. this.method = data.method;
  4175. }
  4176. }
  4177. // 1 input
  4178. MathNode.ALL = 'all';
  4179. MathNode.ANY = 'any';
  4180. MathNode.RADIANS = 'radians';
  4181. MathNode.DEGREES = 'degrees';
  4182. MathNode.EXP = 'exp';
  4183. MathNode.EXP2 = 'exp2';
  4184. MathNode.LOG = 'log';
  4185. MathNode.LOG2 = 'log2';
  4186. MathNode.SQRT = 'sqrt';
  4187. MathNode.INVERSE_SQRT = 'inversesqrt';
  4188. MathNode.FLOOR = 'floor';
  4189. MathNode.CEIL = 'ceil';
  4190. MathNode.NORMALIZE = 'normalize';
  4191. MathNode.FRACT = 'fract';
  4192. MathNode.SIN = 'sin';
  4193. MathNode.COS = 'cos';
  4194. MathNode.TAN = 'tan';
  4195. MathNode.ASIN = 'asin';
  4196. MathNode.ACOS = 'acos';
  4197. MathNode.ATAN = 'atan';
  4198. MathNode.ABS = 'abs';
  4199. MathNode.SIGN = 'sign';
  4200. MathNode.LENGTH = 'length';
  4201. MathNode.NEGATE = 'negate';
  4202. MathNode.ONE_MINUS = 'oneMinus';
  4203. MathNode.DFDX = 'dFdx';
  4204. MathNode.DFDY = 'dFdy';
  4205. MathNode.ROUND = 'round';
  4206. MathNode.RECIPROCAL = 'reciprocal';
  4207. MathNode.TRUNC = 'trunc';
  4208. MathNode.FWIDTH = 'fwidth';
  4209. MathNode.TRANSPOSE = 'transpose';
  4210. // 2 inputs
  4211. MathNode.BITCAST = 'bitcast';
  4212. MathNode.EQUALS = 'equals';
  4213. MathNode.MIN = 'min';
  4214. MathNode.MAX = 'max';
  4215. MathNode.STEP = 'step';
  4216. MathNode.REFLECT = 'reflect';
  4217. MathNode.DISTANCE = 'distance';
  4218. MathNode.DIFFERENCE = 'difference';
  4219. MathNode.DOT = 'dot';
  4220. MathNode.CROSS = 'cross';
  4221. MathNode.POW = 'pow';
  4222. MathNode.TRANSFORM_DIRECTION = 'transformDirection';
  4223. // 3 inputs
  4224. MathNode.MIX = 'mix';
  4225. MathNode.CLAMP = 'clamp';
  4226. MathNode.REFRACT = 'refract';
  4227. MathNode.SMOOTHSTEP = 'smoothstep';
  4228. MathNode.FACEFORWARD = 'faceforward';
  4229. // 1 inputs
  4230. /**
  4231. * A small value used to handle floating-point precision errors.
  4232. *
  4233. * @tsl
  4234. * @type {Node<float>}
  4235. */
  4236. const EPSILON = /*@__PURE__*/ float( 1e-6 );
  4237. /**
  4238. * Represents infinity.
  4239. *
  4240. * @tsl
  4241. * @type {Node<float>}
  4242. */
  4243. const INFINITY = /*@__PURE__*/ float( 1e6 );
  4244. /**
  4245. * Represents PI.
  4246. *
  4247. * @tsl
  4248. * @type {Node<float>}
  4249. */
  4250. const PI = /*@__PURE__*/ float( Math.PI );
  4251. /**
  4252. * Represents PI * 2.
  4253. *
  4254. * @tsl
  4255. * @type {Node<float>}
  4256. */
  4257. const PI2 = /*@__PURE__*/ float( Math.PI * 2 );
  4258. /**
  4259. * Returns `true` if all components of `x` are `true`.
  4260. *
  4261. * @tsl
  4262. * @function
  4263. * @param {Node | number} x - The parameter.
  4264. * @returns {Node<bool>}
  4265. */
  4266. const all = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ALL ).setParameterLength( 1 );
  4267. /**
  4268. * Returns `true` if any components of `x` are `true`.
  4269. *
  4270. * @tsl
  4271. * @function
  4272. * @param {Node | number} x - The parameter.
  4273. * @returns {Node<bool>}
  4274. */
  4275. const any = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ANY ).setParameterLength( 1 );
  4276. /**
  4277. * Converts a quantity in degrees to radians.
  4278. *
  4279. * @tsl
  4280. * @function
  4281. * @param {Node | number} x - The input in degrees.
  4282. * @returns {Node}
  4283. */
  4284. const radians = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RADIANS ).setParameterLength( 1 );
  4285. /**
  4286. * Convert a quantity in radians to degrees.
  4287. *
  4288. * @tsl
  4289. * @function
  4290. * @param {Node | number} x - The input in radians.
  4291. * @returns {Node}
  4292. */
  4293. const degrees = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DEGREES ).setParameterLength( 1 );
  4294. /**
  4295. * Returns the natural exponentiation of the parameter.
  4296. *
  4297. * @tsl
  4298. * @function
  4299. * @param {Node | number} x - The parameter.
  4300. * @returns {Node}
  4301. */
  4302. const exp = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP ).setParameterLength( 1 );
  4303. /**
  4304. * Returns 2 raised to the power of the parameter.
  4305. *
  4306. * @tsl
  4307. * @function
  4308. * @param {Node | number} x - The parameter.
  4309. * @returns {Node}
  4310. */
  4311. const exp2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP2 ).setParameterLength( 1 );
  4312. /**
  4313. * Returns the natural logarithm of the parameter.
  4314. *
  4315. * @tsl
  4316. * @function
  4317. * @param {Node | number} x - The parameter.
  4318. * @returns {Node}
  4319. */
  4320. const log = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG ).setParameterLength( 1 );
  4321. /**
  4322. * Returns the base 2 logarithm of the parameter.
  4323. *
  4324. * @tsl
  4325. * @function
  4326. * @param {Node | number} x - The parameter.
  4327. * @returns {Node}
  4328. */
  4329. const log2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG2 ).setParameterLength( 1 );
  4330. /**
  4331. * Returns the square root of the parameter.
  4332. *
  4333. * @tsl
  4334. * @function
  4335. * @param {Node | number} x - The parameter.
  4336. * @returns {Node}
  4337. */
  4338. const sqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SQRT ).setParameterLength( 1 );
  4339. /**
  4340. * Returns the inverse of the square root of the parameter.
  4341. *
  4342. * @tsl
  4343. * @function
  4344. * @param {Node | number} x - The parameter.
  4345. * @returns {Node}
  4346. */
  4347. const inverseSqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.INVERSE_SQRT ).setParameterLength( 1 );
  4348. /**
  4349. * Finds the nearest integer less than or equal to the parameter.
  4350. *
  4351. * @tsl
  4352. * @function
  4353. * @param {Node | number} x - The parameter.
  4354. * @returns {Node}
  4355. */
  4356. const floor = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FLOOR ).setParameterLength( 1 );
  4357. /**
  4358. * Finds the nearest integer that is greater than or equal to the parameter.
  4359. *
  4360. * @tsl
  4361. * @function
  4362. * @param {Node | number} x - The parameter.
  4363. * @returns {Node}
  4364. */
  4365. const ceil = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CEIL ).setParameterLength( 1 );
  4366. /**
  4367. * Calculates the unit vector in the same direction as the original vector.
  4368. *
  4369. * @tsl
  4370. * @function
  4371. * @param {Node} x - The input vector.
  4372. * @returns {Node}
  4373. */
  4374. const normalize = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NORMALIZE ).setParameterLength( 1 );
  4375. /**
  4376. * Computes the fractional part of the parameter.
  4377. *
  4378. * @tsl
  4379. * @function
  4380. * @param {Node | number} x - The parameter.
  4381. * @returns {Node}
  4382. */
  4383. const fract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FRACT ).setParameterLength( 1 );
  4384. /**
  4385. * Returns the sine of the parameter.
  4386. *
  4387. * @tsl
  4388. * @function
  4389. * @param {Node | number} x - The parameter.
  4390. * @returns {Node}
  4391. */
  4392. const sin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIN ).setParameterLength( 1 );
  4393. /**
  4394. * Returns the cosine of the parameter.
  4395. *
  4396. * @tsl
  4397. * @function
  4398. * @param {Node | number} x - The parameter.
  4399. * @returns {Node}
  4400. */
  4401. const cos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.COS ).setParameterLength( 1 );
  4402. /**
  4403. * Returns the tangent of the parameter.
  4404. *
  4405. * @tsl
  4406. * @function
  4407. * @param {Node | number} x - The parameter.
  4408. * @returns {Node}
  4409. */
  4410. const tan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TAN ).setParameterLength( 1 );
  4411. /**
  4412. * Returns the arcsine of the parameter.
  4413. *
  4414. * @tsl
  4415. * @function
  4416. * @param {Node | number} x - The parameter.
  4417. * @returns {Node}
  4418. */
  4419. const asin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ASIN ).setParameterLength( 1 );
  4420. /**
  4421. * Returns the arccosine of the parameter.
  4422. *
  4423. * @tsl
  4424. * @function
  4425. * @param {Node | number} x - The parameter.
  4426. * @returns {Node}
  4427. */
  4428. const acos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ACOS ).setParameterLength( 1 );
  4429. /**
  4430. * Returns the arc-tangent of the parameter.
  4431. * If two parameters are provided, the result is `atan2(y/x)`.
  4432. *
  4433. * @tsl
  4434. * @function
  4435. * @param {Node | number} y - The y parameter.
  4436. * @param {?(Node | number)} x - The x parameter.
  4437. * @returns {Node}
  4438. */
  4439. const atan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ATAN ).setParameterLength( 1, 2 );
  4440. /**
  4441. * Returns the absolute value of the parameter.
  4442. *
  4443. * @tsl
  4444. * @function
  4445. * @param {Node | number} x - The parameter.
  4446. * @returns {Node}
  4447. */
  4448. const abs = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ABS ).setParameterLength( 1 );
  4449. /**
  4450. * Extracts the sign of the parameter.
  4451. *
  4452. * @tsl
  4453. * @function
  4454. * @param {Node | number} x - The parameter.
  4455. * @returns {Node}
  4456. */
  4457. const sign = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIGN ).setParameterLength( 1 );
  4458. /**
  4459. * Calculates the length of a vector.
  4460. *
  4461. * @tsl
  4462. * @function
  4463. * @param {Node} x - The parameter.
  4464. * @returns {Node<float>}
  4465. */
  4466. const length = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LENGTH ).setParameterLength( 1 );
  4467. /**
  4468. * Negates the value of the parameter (-x).
  4469. *
  4470. * @tsl
  4471. * @function
  4472. * @param {Node | number} x - The parameter.
  4473. * @returns {Node}
  4474. */
  4475. const negate = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NEGATE ).setParameterLength( 1 );
  4476. /**
  4477. * Return `1` minus the parameter.
  4478. *
  4479. * @tsl
  4480. * @function
  4481. * @param {Node | number} x - The parameter.
  4482. * @returns {Node}
  4483. */
  4484. const oneMinus = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ONE_MINUS ).setParameterLength( 1 );
  4485. /**
  4486. * Returns the partial derivative of the parameter with respect to x.
  4487. *
  4488. * @tsl
  4489. * @function
  4490. * @param {Node | number} x - The parameter.
  4491. * @returns {Node}
  4492. */
  4493. const dFdx = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDX ).setParameterLength( 1 );
  4494. /**
  4495. * Returns the partial derivative of the parameter with respect to y.
  4496. *
  4497. * @tsl
  4498. * @function
  4499. * @param {Node | number} x - The parameter.
  4500. * @returns {Node}
  4501. */
  4502. const dFdy = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDY ).setParameterLength( 1 );
  4503. /**
  4504. * Rounds the parameter to the nearest integer.
  4505. *
  4506. * @tsl
  4507. * @function
  4508. * @param {Node | number} x - The parameter.
  4509. * @returns {Node}
  4510. */
  4511. const round = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ROUND ).setParameterLength( 1 );
  4512. /**
  4513. * Returns the reciprocal of the parameter `(1/x)`.
  4514. *
  4515. * @tsl
  4516. * @function
  4517. * @param {Node | number} x - The parameter.
  4518. * @returns {Node}
  4519. */
  4520. const reciprocal = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RECIPROCAL ).setParameterLength( 1 );
  4521. /**
  4522. * Truncates the parameter, removing the fractional part.
  4523. *
  4524. * @tsl
  4525. * @function
  4526. * @param {Node | number} x - The parameter.
  4527. * @returns {Node}
  4528. */
  4529. const trunc = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRUNC ).setParameterLength( 1 );
  4530. /**
  4531. * Returns the sum of the absolute derivatives in x and y.
  4532. *
  4533. * @tsl
  4534. * @function
  4535. * @param {Node | number} x - The parameter.
  4536. * @returns {Node}
  4537. */
  4538. const fwidth = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FWIDTH ).setParameterLength( 1 );
  4539. /**
  4540. * Returns the transpose of a matrix.
  4541. *
  4542. * @tsl
  4543. * @function
  4544. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  4545. * @returns {Node}
  4546. */
  4547. const transpose = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSPOSE ).setParameterLength( 1 );
  4548. // 2 inputs
  4549. /**
  4550. * Reinterpret the bit representation of a value in one type as a value in another type.
  4551. *
  4552. * @tsl
  4553. * @function
  4554. * @param {Node | number} x - The parameter.
  4555. * @param {string} y - The new type.
  4556. * @returns {Node}
  4557. */
  4558. const bitcast = /*@__PURE__*/ nodeProxy( MathNode, MathNode.BITCAST ).setParameterLength( 2 );
  4559. /**
  4560. * Returns `true` if `x` equals `y`.
  4561. *
  4562. * @tsl
  4563. * @function
  4564. * @param {Node | number} x - The first parameter.
  4565. * @param {Node | number} y - The second parameter.
  4566. * @deprecated since r175. Use {@link equal} instead.
  4567. * @returns {Node<bool>}
  4568. */
  4569. const equals = ( x, y ) => { // @deprecated, r172
  4570. console.warn( 'THREE.TSL: "equals" is deprecated. Use "equal" inside a vector instead, like: "bvec*( equal( ... ) )"' );
  4571. return equal( x, y );
  4572. };
  4573. /**
  4574. * Returns the least of the given values.
  4575. *
  4576. * @tsl
  4577. * @function
  4578. * @param {...(Node | number)} values - The values to compare.
  4579. * @returns {Node}
  4580. */
  4581. const min$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIN ).setParameterLength( 2, Infinity );
  4582. /**
  4583. * Returns the greatest of the given values.
  4584. *
  4585. * @tsl
  4586. * @function
  4587. * @param {...(Node | number)} values - The values to compare.
  4588. * @returns {Node}
  4589. */
  4590. const max$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MAX ).setParameterLength( 2, Infinity );
  4591. /**
  4592. * Generate a step function by comparing two values.
  4593. *
  4594. * @tsl
  4595. * @function
  4596. * @param {Node | number} x - The y parameter.
  4597. * @param {Node | number} y - The x parameter.
  4598. * @returns {Node}
  4599. */
  4600. const step = /*@__PURE__*/ nodeProxy( MathNode, MathNode.STEP ).setParameterLength( 2 );
  4601. /**
  4602. * Calculates the reflection direction for an incident vector.
  4603. *
  4604. * @tsl
  4605. * @function
  4606. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  4607. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  4608. * @returns {Node<vec2|vec3|vec4>}
  4609. */
  4610. const reflect = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFLECT ).setParameterLength( 2 );
  4611. /**
  4612. * Calculates the distance between two points.
  4613. *
  4614. * @tsl
  4615. * @function
  4616. * @param {Node<vec2|vec3|vec4>} x - The first point.
  4617. * @param {Node<vec2|vec3|vec4>} y - The second point.
  4618. * @returns {Node<float>}
  4619. */
  4620. const distance = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DISTANCE ).setParameterLength( 2 );
  4621. /**
  4622. * Calculates the absolute difference between two values.
  4623. *
  4624. * @tsl
  4625. * @function
  4626. * @param {Node | number} x - The first parameter.
  4627. * @param {Node | number} y - The second parameter.
  4628. * @returns {Node}
  4629. */
  4630. const difference = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DIFFERENCE ).setParameterLength( 2 );
  4631. /**
  4632. * Calculates the dot product of two vectors.
  4633. *
  4634. * @tsl
  4635. * @function
  4636. * @param {Node<vec2|vec3|vec4>} x - The first vector.
  4637. * @param {Node<vec2|vec3|vec4>} y - The second vector.
  4638. * @returns {Node<float>}
  4639. */
  4640. const dot = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DOT ).setParameterLength( 2 );
  4641. /**
  4642. * Calculates the cross product of two vectors.
  4643. *
  4644. * @tsl
  4645. * @function
  4646. * @param {Node<vec2|vec3|vec4>} x - The first vector.
  4647. * @param {Node<vec2|vec3|vec4>} y - The second vector.
  4648. * @returns {Node<vec2|vec3|vec4>}
  4649. */
  4650. const cross = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CROSS ).setParameterLength( 2 );
  4651. /**
  4652. * Return the value of the first parameter raised to the power of the second one.
  4653. *
  4654. * @tsl
  4655. * @function
  4656. * @param {Node | number} x - The first parameter.
  4657. * @param {Node | number} y - The second parameter.
  4658. * @returns {Node}
  4659. */
  4660. const pow = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW ).setParameterLength( 2 );
  4661. /**
  4662. * Returns the square of the parameter.
  4663. *
  4664. * @tsl
  4665. * @function
  4666. * @param {Node | number} x - The first parameter.
  4667. * @returns {Node}
  4668. */
  4669. const pow2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 2 ).setParameterLength( 1 );
  4670. /**
  4671. * Returns the cube of the parameter.
  4672. *
  4673. * @tsl
  4674. * @function
  4675. * @param {Node | number} x - The first parameter.
  4676. * @returns {Node}
  4677. */
  4678. const pow3 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 3 ).setParameterLength( 1 );
  4679. /**
  4680. * Returns the fourth power of the parameter.
  4681. *
  4682. * @tsl
  4683. * @function
  4684. * @param {Node | number} x - The first parameter.
  4685. * @returns {Node}
  4686. */
  4687. const pow4 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 4 ).setParameterLength( 1 );
  4688. /**
  4689. * Transforms the direction of a vector by a matrix and then normalizes the result.
  4690. *
  4691. * @tsl
  4692. * @function
  4693. * @param {Node<vec2|vec3|vec4>} direction - The direction vector.
  4694. * @param {Node<mat2|mat3|mat4>} matrix - The transformation matrix.
  4695. * @returns {Node}
  4696. */
  4697. const transformDirection = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSFORM_DIRECTION ).setParameterLength( 2 );
  4698. /**
  4699. * Returns the cube root of a number.
  4700. *
  4701. * @tsl
  4702. * @function
  4703. * @param {Node | number} a - The first parameter.
  4704. * @returns {Node}
  4705. */
  4706. const cbrt = ( a ) => mul( sign( a ), pow( abs( a ), 1.0 / 3.0 ) );
  4707. /**
  4708. * Calculate the squared length of a vector.
  4709. *
  4710. * @tsl
  4711. * @function
  4712. * @param {Node<vec2|vec3|vec4>} a - The vector.
  4713. * @returns {Node<float>}
  4714. */
  4715. const lengthSq = ( a ) => dot( a, a );
  4716. /**
  4717. * Linearly interpolates between two values.
  4718. *
  4719. * @tsl
  4720. * @function
  4721. * @param {Node | number} a - The first parameter.
  4722. * @param {Node | number} b - The second parameter.
  4723. * @param {Node | number} t - The interpolation value.
  4724. * @returns {Node}
  4725. */
  4726. const mix = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIX ).setParameterLength( 3 );
  4727. /**
  4728. * Constrains a value to lie between two further values.
  4729. *
  4730. * @tsl
  4731. * @function
  4732. * @param {Node | number} value - The value to constrain.
  4733. * @param {Node | number} [low=0] - The lower bound.
  4734. * @param {Node | number} [high=1] - The upper bound.
  4735. * @returns {Node}
  4736. */
  4737. const clamp = ( value, low = 0, high = 1 ) => nodeObject( new MathNode( MathNode.CLAMP, nodeObject( value ), nodeObject( low ), nodeObject( high ) ) );
  4738. /**
  4739. * Constrains a value between `0` and `1`.
  4740. *
  4741. * @tsl
  4742. * @function
  4743. * @param {Node | number} value - The value to constrain.
  4744. * @returns {Node}
  4745. */
  4746. const saturate = ( value ) => clamp( value );
  4747. /**
  4748. * Calculates the refraction direction for an incident vector.
  4749. *
  4750. * @tsl
  4751. * @function
  4752. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  4753. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  4754. * @param {Node<float>} eta - The ratio of indices of refraction.
  4755. * @returns {Node<vec2|vec3|vec4>}
  4756. */
  4757. const refract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFRACT ).setParameterLength( 3 );
  4758. /**
  4759. * Performs a Hermite interpolation between two values.
  4760. *
  4761. * @tsl
  4762. * @function
  4763. * @param {Node | number} low - The value of the lower edge of the Hermite function.
  4764. * @param {Node | number} high - The value of the upper edge of the Hermite function.
  4765. * @param {Node | number} x - The source value for interpolation.
  4766. * @returns {Node}
  4767. */
  4768. const smoothstep = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SMOOTHSTEP ).setParameterLength( 3 );
  4769. /**
  4770. * Returns a vector pointing in the same direction as another.
  4771. *
  4772. * @tsl
  4773. * @function
  4774. * @param {Node<vec2|vec3|vec4>} N - The vector to orient.
  4775. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  4776. * @param {Node<vec2|vec3|vec4>} Nref - The reference vector.
  4777. * @returns {Node<vec2|vec3|vec4>}
  4778. */
  4779. const faceForward = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FACEFORWARD ).setParameterLength( 3 );
  4780. /**
  4781. * Returns a random value for the given uv.
  4782. *
  4783. * @tsl
  4784. * @function
  4785. * @param {Node<vec2>} uv - The uv node.
  4786. * @returns {Node<float>}
  4787. */
  4788. const rand = /*@__PURE__*/ Fn( ( [ uv ] ) => {
  4789. const a = 12.9898, b = 78.233, c = 43758.5453;
  4790. const dt = dot( uv.xy, vec2( a, b ) ), sn = mod( dt, PI );
  4791. return fract( sin( sn ).mul( c ) );
  4792. } );
  4793. /**
  4794. * Alias for `mix()` with a different parameter order.
  4795. *
  4796. * @tsl
  4797. * @function
  4798. * @param {Node | number} t - The interpolation value.
  4799. * @param {Node | number} e1 - The first parameter.
  4800. * @param {Node | number} e2 - The second parameter.
  4801. * @returns {Node}
  4802. */
  4803. const mixElement = ( t, e1, e2 ) => mix( e1, e2, t );
  4804. /**
  4805. * Alias for `smoothstep()` with a different parameter order.
  4806. *
  4807. * @tsl
  4808. * @function
  4809. * @param {Node | number} x - The source value for interpolation.
  4810. * @param {Node | number} low - The value of the lower edge of the Hermite function.
  4811. * @param {Node | number} high - The value of the upper edge of the Hermite function.
  4812. * @returns {Node}
  4813. */
  4814. const smoothstepElement = ( x, low, high ) => smoothstep( low, high, x );
  4815. /**
  4816. * Returns the arc-tangent of the quotient of its parameters.
  4817. *
  4818. * @tsl
  4819. * @function
  4820. * @deprecated since r172. Use {@link atan} instead.
  4821. *
  4822. * @param {Node | number} y - The y parameter.
  4823. * @param {Node | number} x - The x parameter.
  4824. * @returns {Node}
  4825. */
  4826. const atan2 = ( y, x ) => { // @deprecated, r172
  4827. console.warn( 'THREE.TSL: "atan2" is overloaded. Use "atan" instead.' );
  4828. return atan( y, x );
  4829. };
  4830. // GLSL alias function
  4831. const faceforward = faceForward;
  4832. const inversesqrt = inverseSqrt;
  4833. // Method chaining
  4834. addMethodChaining( 'all', all );
  4835. addMethodChaining( 'any', any );
  4836. addMethodChaining( 'equals', equals );
  4837. addMethodChaining( 'radians', radians );
  4838. addMethodChaining( 'degrees', degrees );
  4839. addMethodChaining( 'exp', exp );
  4840. addMethodChaining( 'exp2', exp2 );
  4841. addMethodChaining( 'log', log );
  4842. addMethodChaining( 'log2', log2 );
  4843. addMethodChaining( 'sqrt', sqrt );
  4844. addMethodChaining( 'inverseSqrt', inverseSqrt );
  4845. addMethodChaining( 'floor', floor );
  4846. addMethodChaining( 'ceil', ceil );
  4847. addMethodChaining( 'normalize', normalize );
  4848. addMethodChaining( 'fract', fract );
  4849. addMethodChaining( 'sin', sin );
  4850. addMethodChaining( 'cos', cos );
  4851. addMethodChaining( 'tan', tan );
  4852. addMethodChaining( 'asin', asin );
  4853. addMethodChaining( 'acos', acos );
  4854. addMethodChaining( 'atan', atan );
  4855. addMethodChaining( 'abs', abs );
  4856. addMethodChaining( 'sign', sign );
  4857. addMethodChaining( 'length', length );
  4858. addMethodChaining( 'lengthSq', lengthSq );
  4859. addMethodChaining( 'negate', negate );
  4860. addMethodChaining( 'oneMinus', oneMinus );
  4861. addMethodChaining( 'dFdx', dFdx );
  4862. addMethodChaining( 'dFdy', dFdy );
  4863. addMethodChaining( 'round', round );
  4864. addMethodChaining( 'reciprocal', reciprocal );
  4865. addMethodChaining( 'trunc', trunc );
  4866. addMethodChaining( 'fwidth', fwidth );
  4867. addMethodChaining( 'atan2', atan2 );
  4868. addMethodChaining( 'min', min$1 );
  4869. addMethodChaining( 'max', max$1 );
  4870. addMethodChaining( 'step', step );
  4871. addMethodChaining( 'reflect', reflect );
  4872. addMethodChaining( 'distance', distance );
  4873. addMethodChaining( 'dot', dot );
  4874. addMethodChaining( 'cross', cross );
  4875. addMethodChaining( 'pow', pow );
  4876. addMethodChaining( 'pow2', pow2 );
  4877. addMethodChaining( 'pow3', pow3 );
  4878. addMethodChaining( 'pow4', pow4 );
  4879. addMethodChaining( 'transformDirection', transformDirection );
  4880. addMethodChaining( 'mix', mixElement );
  4881. addMethodChaining( 'clamp', clamp );
  4882. addMethodChaining( 'refract', refract );
  4883. addMethodChaining( 'smoothstep', smoothstepElement );
  4884. addMethodChaining( 'faceForward', faceForward );
  4885. addMethodChaining( 'difference', difference );
  4886. addMethodChaining( 'saturate', saturate );
  4887. addMethodChaining( 'cbrt', cbrt );
  4888. addMethodChaining( 'transpose', transpose );
  4889. addMethodChaining( 'rand', rand );
  4890. /**
  4891. * Represents a logical `if/else` statement. Can be used as an alternative
  4892. * to the `If()`/`Else()` syntax.
  4893. *
  4894. * The corresponding TSL `select()` looks like so:
  4895. * ```js
  4896. * velocity = position.greaterThanEqual( limit ).select( velocity.negate(), velocity );
  4897. * ```
  4898. * The `select()` method is called in a chaining fashion on a condition. The parameter nodes of `select()`
  4899. * determine the outcome of the entire statement.
  4900. *
  4901. * @augments Node
  4902. */
  4903. class ConditionalNode extends Node {
  4904. static get type() {
  4905. return 'ConditionalNode';
  4906. }
  4907. /**
  4908. * Constructs a new conditional node.
  4909. *
  4910. * @param {Node} condNode - The node that defines the condition.
  4911. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  4912. * @param {?Node} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  4913. */
  4914. constructor( condNode, ifNode, elseNode = null ) {
  4915. super();
  4916. /**
  4917. * The node that defines the condition.
  4918. *
  4919. * @type {Node}
  4920. */
  4921. this.condNode = condNode;
  4922. /**
  4923. * The node that is evaluate when the condition ends up `true`.
  4924. *
  4925. * @type {Node}
  4926. */
  4927. this.ifNode = ifNode;
  4928. /**
  4929. * The node that is evaluate when the condition ends up `false`.
  4930. *
  4931. * @type {?Node}
  4932. * @default null
  4933. */
  4934. this.elseNode = elseNode;
  4935. }
  4936. /**
  4937. * This method is overwritten since the node type is inferred from the if/else
  4938. * nodes.
  4939. *
  4940. * @param {NodeBuilder} builder - The current node builder.
  4941. * @return {string} The node type.
  4942. */
  4943. getNodeType( builder ) {
  4944. const { ifNode, elseNode } = builder.getNodeProperties( this );
  4945. if ( ifNode === undefined ) {
  4946. // fallback setup
  4947. this.setup( builder );
  4948. return this.getNodeType( builder );
  4949. }
  4950. const ifType = ifNode.getNodeType( builder );
  4951. if ( elseNode !== null ) {
  4952. const elseType = elseNode.getNodeType( builder );
  4953. if ( builder.getTypeLength( elseType ) > builder.getTypeLength( ifType ) ) {
  4954. return elseType;
  4955. }
  4956. }
  4957. return ifType;
  4958. }
  4959. setup( builder ) {
  4960. const condNode = this.condNode.cache();
  4961. const ifNode = this.ifNode.cache();
  4962. const elseNode = this.elseNode ? this.elseNode.cache() : null;
  4963. //
  4964. const currentNodeBlock = builder.context.nodeBlock;
  4965. builder.getDataFromNode( ifNode ).parentNodeBlock = currentNodeBlock;
  4966. if ( elseNode !== null ) builder.getDataFromNode( elseNode ).parentNodeBlock = currentNodeBlock;
  4967. //
  4968. const properties = builder.getNodeProperties( this );
  4969. properties.condNode = condNode;
  4970. properties.ifNode = ifNode.context( { nodeBlock: ifNode } );
  4971. properties.elseNode = elseNode ? elseNode.context( { nodeBlock: elseNode } ) : null;
  4972. }
  4973. generate( builder, output ) {
  4974. const type = this.getNodeType( builder );
  4975. const nodeData = builder.getDataFromNode( this );
  4976. if ( nodeData.nodeProperty !== undefined ) {
  4977. return nodeData.nodeProperty;
  4978. }
  4979. const { condNode, ifNode, elseNode } = builder.getNodeProperties( this );
  4980. const functionNode = builder.currentFunctionNode;
  4981. const needsOutput = output !== 'void';
  4982. const nodeProperty = needsOutput ? property( type ).build( builder ) : '';
  4983. nodeData.nodeProperty = nodeProperty;
  4984. const nodeSnippet = condNode.build( builder, 'bool' );
  4985. builder.addFlowCode( `\n${ builder.tab }if ( ${ nodeSnippet } ) {\n\n` ).addFlowTab();
  4986. let ifSnippet = ifNode.build( builder, type );
  4987. if ( ifSnippet ) {
  4988. if ( needsOutput ) {
  4989. ifSnippet = nodeProperty + ' = ' + ifSnippet + ';';
  4990. } else {
  4991. ifSnippet = 'return ' + ifSnippet + ';';
  4992. if ( functionNode === null ) {
  4993. console.warn( 'THREE.TSL: Return statement used in an inline \'Fn()\'. Define a layout struct to allow return values.' );
  4994. ifSnippet = '// ' + ifSnippet;
  4995. }
  4996. }
  4997. }
  4998. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + ifSnippet + '\n\n' + builder.tab + '}' );
  4999. if ( elseNode !== null ) {
  5000. builder.addFlowCode( ' else {\n\n' ).addFlowTab();
  5001. let elseSnippet = elseNode.build( builder, type );
  5002. if ( elseSnippet ) {
  5003. if ( needsOutput ) {
  5004. elseSnippet = nodeProperty + ' = ' + elseSnippet + ';';
  5005. } else {
  5006. elseSnippet = 'return ' + elseSnippet + ';';
  5007. if ( functionNode === null ) {
  5008. console.warn( 'THREE.TSL: Return statement used in an inline \'Fn()\'. Define a layout struct to allow return values.' );
  5009. elseSnippet = '// ' + elseSnippet;
  5010. }
  5011. }
  5012. }
  5013. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + elseSnippet + '\n\n' + builder.tab + '}\n\n' );
  5014. } else {
  5015. builder.addFlowCode( '\n\n' );
  5016. }
  5017. return builder.format( nodeProperty, type, output );
  5018. }
  5019. }
  5020. /**
  5021. * TSL function for creating a conditional node.
  5022. *
  5023. * @tsl
  5024. * @function
  5025. * @param {Node} condNode - The node that defines the condition.
  5026. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  5027. * @param {?Node} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  5028. * @returns {ConditionalNode}
  5029. */
  5030. const select = /*@__PURE__*/ nodeProxy( ConditionalNode ).setParameterLength( 2, 3 );
  5031. addMethodChaining( 'select', select );
  5032. // Deprecated
  5033. /**
  5034. * @tsl
  5035. * @function
  5036. * @deprecated since r168. Use {@link select} instead.
  5037. *
  5038. * @param {...any} params
  5039. * @returns {ConditionalNode}
  5040. */
  5041. const cond = ( ...params ) => { // @deprecated, r168
  5042. console.warn( 'THREE.TSL: cond() has been renamed to select().' );
  5043. return select( ...params );
  5044. };
  5045. addMethodChaining( 'cond', cond );
  5046. /**
  5047. * This node can be used as a context management component for another node.
  5048. * {@link NodeBuilder} performs its node building process in a specific context and
  5049. * this node allows the modify the context. A typical use case is to overwrite `getUV()` e.g.:
  5050. *
  5051. * ```js
  5052. *node.context( { getUV: () => customCoord } );
  5053. *```
  5054. * @augments Node
  5055. */
  5056. class ContextNode extends Node {
  5057. static get type() {
  5058. return 'ContextNode';
  5059. }
  5060. /**
  5061. * Constructs a new context node.
  5062. *
  5063. * @param {Node} node - The node whose context should be modified.
  5064. * @param {Object} [value={}] - The modified context data.
  5065. */
  5066. constructor( node, value = {} ) {
  5067. super();
  5068. /**
  5069. * This flag can be used for type testing.
  5070. *
  5071. * @type {boolean}
  5072. * @readonly
  5073. * @default true
  5074. */
  5075. this.isContextNode = true;
  5076. /**
  5077. * The node whose context should be modified.
  5078. *
  5079. * @type {Node}
  5080. */
  5081. this.node = node;
  5082. /**
  5083. * The modified context data.
  5084. *
  5085. * @type {Object}
  5086. * @default {}
  5087. */
  5088. this.value = value;
  5089. }
  5090. /**
  5091. * This method is overwritten to ensure it returns the reference to {@link ContextNode#node}.
  5092. *
  5093. * @return {Node} A reference to {@link ContextNode#node}.
  5094. */
  5095. getScope() {
  5096. return this.node.getScope();
  5097. }
  5098. /**
  5099. * This method is overwritten to ensure it returns the type of {@link ContextNode#node}.
  5100. *
  5101. * @param {NodeBuilder} builder - The current node builder.
  5102. * @return {string} The node type.
  5103. */
  5104. getNodeType( builder ) {
  5105. return this.node.getNodeType( builder );
  5106. }
  5107. analyze( builder ) {
  5108. const previousContext = builder.getContext();
  5109. builder.setContext( { ...builder.context, ...this.value } );
  5110. this.node.build( builder );
  5111. builder.setContext( previousContext );
  5112. }
  5113. setup( builder ) {
  5114. const previousContext = builder.getContext();
  5115. builder.setContext( { ...builder.context, ...this.value } );
  5116. this.node.build( builder );
  5117. builder.setContext( previousContext );
  5118. }
  5119. generate( builder, output ) {
  5120. const previousContext = builder.getContext();
  5121. builder.setContext( { ...builder.context, ...this.value } );
  5122. const snippet = this.node.build( builder, output );
  5123. builder.setContext( previousContext );
  5124. return snippet;
  5125. }
  5126. }
  5127. /**
  5128. * TSL function for creating a context node.
  5129. *
  5130. * @tsl
  5131. * @function
  5132. * @param {Node} node - The node whose context should be modified.
  5133. * @param {Object} [value={}] - The modified context data.
  5134. * @returns {ContextNode}
  5135. */
  5136. const context = /*@__PURE__*/ nodeProxy( ContextNode ).setParameterLength( 1, 2 );
  5137. /**
  5138. * TSL function for defining a label context value for a given node.
  5139. *
  5140. * @tsl
  5141. * @function
  5142. * @param {Node} node - The node whose context should be modified.
  5143. * @param {string} name - The name/label to set.
  5144. * @returns {ContextNode}
  5145. */
  5146. const label = ( node, name ) => context( node, { label: name } );
  5147. addMethodChaining( 'context', context );
  5148. addMethodChaining( 'label', label );
  5149. /**
  5150. * Class for representing shader variables as nodes. Variables are created from
  5151. * existing nodes like the following:
  5152. *
  5153. * ```js
  5154. * const depth = sampleDepth( uvNode ).toVar( 'depth' );
  5155. * ```
  5156. *
  5157. * @augments Node
  5158. */
  5159. class VarNode extends Node {
  5160. static get type() {
  5161. return 'VarNode';
  5162. }
  5163. /**
  5164. * Constructs a new variable node.
  5165. *
  5166. * @param {Node} node - The node for which a variable should be created.
  5167. * @param {?string} [name=null] - The name of the variable in the shader.
  5168. * @param {boolean} [readOnly=false] - The read-only flag.
  5169. */
  5170. constructor( node, name = null, readOnly = false ) {
  5171. super();
  5172. /**
  5173. * The node for which a variable should be created.
  5174. *
  5175. * @type {Node}
  5176. */
  5177. this.node = node;
  5178. /**
  5179. * The name of the variable in the shader. If no name is defined,
  5180. * the node system auto-generates one.
  5181. *
  5182. * @type {?string}
  5183. * @default null
  5184. */
  5185. this.name = name;
  5186. /**
  5187. * `VarNode` sets this property to `true` by default.
  5188. *
  5189. * @type {boolean}
  5190. * @default true
  5191. */
  5192. this.global = true;
  5193. /**
  5194. * This flag can be used for type testing.
  5195. *
  5196. * @type {boolean}
  5197. * @readonly
  5198. * @default true
  5199. */
  5200. this.isVarNode = true;
  5201. /**
  5202. *
  5203. * The read-only flag.
  5204. *
  5205. * @type {boolean}
  5206. * @default false
  5207. */
  5208. this.readOnly = readOnly;
  5209. /**
  5210. *
  5211. * Add this flag to the node system to indicate that this node require parents.
  5212. *
  5213. * @type {boolean}
  5214. * @default true
  5215. */
  5216. this.parents = true;
  5217. }
  5218. getMemberType( builder, name ) {
  5219. return this.node.getMemberType( builder, name );
  5220. }
  5221. getElementType( builder ) {
  5222. return this.node.getElementType( builder );
  5223. }
  5224. getNodeType( builder ) {
  5225. return this.node.getNodeType( builder );
  5226. }
  5227. generate( builder ) {
  5228. const { node, name, readOnly } = this;
  5229. const { renderer } = builder;
  5230. const isWebGPUBackend = renderer.backend.isWebGPUBackend === true;
  5231. let isDeterministic = false;
  5232. let shouldTreatAsReadOnly = false;
  5233. if ( readOnly ) {
  5234. isDeterministic = builder.isDeterministic( node );
  5235. shouldTreatAsReadOnly = isWebGPUBackend ? readOnly : isDeterministic;
  5236. }
  5237. const vectorType = builder.getVectorType( this.getNodeType( builder ) );
  5238. const snippet = node.build( builder, vectorType );
  5239. const nodeVar = builder.getVarFromNode( this, name, vectorType, undefined, shouldTreatAsReadOnly );
  5240. const propertyName = builder.getPropertyName( nodeVar );
  5241. let declarationPrefix = propertyName;
  5242. if ( shouldTreatAsReadOnly ) {
  5243. if ( isWebGPUBackend ) {
  5244. declarationPrefix = isDeterministic
  5245. ? `const ${ propertyName }`
  5246. : `let ${ propertyName }`;
  5247. } else {
  5248. const count = builder.getArrayCount( node );
  5249. declarationPrefix = `const ${ builder.getVar( nodeVar.type, propertyName, count ) }`;
  5250. }
  5251. }
  5252. builder.addLineFlowCode( `${ declarationPrefix } = ${ snippet }`, this );
  5253. return propertyName;
  5254. }
  5255. }
  5256. /**
  5257. * TSL function for creating a var node.
  5258. *
  5259. * @tsl
  5260. * @function
  5261. * @param {Node} node - The node for which a variable should be created.
  5262. * @param {?string} name - The name of the variable in the shader.
  5263. * @returns {VarNode}
  5264. */
  5265. const createVar = /*@__PURE__*/ nodeProxy( VarNode );
  5266. /**
  5267. * TSL function for creating a var node.
  5268. *
  5269. * @tsl
  5270. * @function
  5271. * @param {Node} node - The node for which a variable should be created.
  5272. * @param {?string} name - The name of the variable in the shader.
  5273. * @returns {VarNode}
  5274. */
  5275. const Var = ( node, name = null ) => createVar( node, name ).toStack();
  5276. /**
  5277. * TSL function for creating a const node.
  5278. *
  5279. * @tsl
  5280. * @function
  5281. * @param {Node} node - The node for which a constant should be created.
  5282. * @param {?string} name - The name of the constant in the shader.
  5283. * @returns {VarNode}
  5284. */
  5285. const Const = ( node, name = null ) => createVar( node, name, true ).toStack();
  5286. // Method chaining
  5287. addMethodChaining( 'toVar', Var );
  5288. addMethodChaining( 'toConst', Const );
  5289. // Deprecated
  5290. /**
  5291. * @tsl
  5292. * @function
  5293. * @deprecated since r170. Use `Var( node )` or `node.toVar()` instead.
  5294. *
  5295. * @param {any} node
  5296. * @returns {VarNode}
  5297. */
  5298. const temp = ( node ) => { // @deprecated, r170
  5299. console.warn( 'TSL: "temp( node )" is deprecated. Use "Var( node )" or "node.toVar()" instead.' );
  5300. return createVar( node );
  5301. };
  5302. addMethodChaining( 'temp', temp );
  5303. /**
  5304. * Class for representing shader varyings as nodes. Varyings are create from
  5305. * existing nodes like the following:
  5306. *
  5307. * ```js
  5308. * const positionLocal = positionGeometry.toVarying( 'vPositionLocal' );
  5309. * ```
  5310. *
  5311. * @augments Node
  5312. */
  5313. class VaryingNode extends Node {
  5314. static get type() {
  5315. return 'VaryingNode';
  5316. }
  5317. /**
  5318. * Constructs a new varying node.
  5319. *
  5320. * @param {Node} node - The node for which a varying should be created.
  5321. * @param {?string} name - The name of the varying in the shader.
  5322. */
  5323. constructor( node, name = null ) {
  5324. super();
  5325. /**
  5326. * The node for which a varying should be created.
  5327. *
  5328. * @type {Node}
  5329. */
  5330. this.node = node;
  5331. /**
  5332. * The name of the varying in the shader. If no name is defined,
  5333. * the node system auto-generates one.
  5334. *
  5335. * @type {?string}
  5336. * @default null
  5337. */
  5338. this.name = name;
  5339. /**
  5340. * This flag can be used for type testing.
  5341. *
  5342. * @type {boolean}
  5343. * @readonly
  5344. * @default true
  5345. */
  5346. this.isVaryingNode = true;
  5347. /**
  5348. * The interpolation type of the varying data.
  5349. *
  5350. * @type {?string}
  5351. * @default null
  5352. */
  5353. this.interpolationType = null;
  5354. /**
  5355. * The interpolation sampling type of varying data.
  5356. *
  5357. * @type {?string}
  5358. * @default null
  5359. */
  5360. this.interpolationSampling = null;
  5361. /**
  5362. * This flag is used for global cache.
  5363. *
  5364. * @type {boolean}
  5365. * @default true
  5366. */
  5367. this.global = true;
  5368. }
  5369. /**
  5370. * Defines the interpolation type of the varying.
  5371. *
  5372. * @param {string} type - The interpolation type.
  5373. * @param {?string} sampling - The interpolation sampling type
  5374. * @return {VaryingNode} A reference to this node.
  5375. */
  5376. setInterpolation( type, sampling = null ) {
  5377. this.interpolationType = type;
  5378. this.interpolationSampling = sampling;
  5379. return this;
  5380. }
  5381. getHash( builder ) {
  5382. return this.name || super.getHash( builder );
  5383. }
  5384. getNodeType( builder ) {
  5385. // VaryingNode is auto type
  5386. return this.node.getNodeType( builder );
  5387. }
  5388. /**
  5389. * This method performs the setup of a varying node with the current node builder.
  5390. *
  5391. * @param {NodeBuilder} builder - The current node builder.
  5392. * @return {NodeVarying} The node varying from the node builder.
  5393. */
  5394. setupVarying( builder ) {
  5395. const properties = builder.getNodeProperties( this );
  5396. let varying = properties.varying;
  5397. if ( varying === undefined ) {
  5398. const name = this.name;
  5399. const type = this.getNodeType( builder );
  5400. const interpolationType = this.interpolationType;
  5401. const interpolationSampling = this.interpolationSampling;
  5402. properties.varying = varying = builder.getVaryingFromNode( this, name, type, interpolationType, interpolationSampling );
  5403. properties.node = this.node;
  5404. }
  5405. // this property can be used to check if the varying can be optimized for a variable
  5406. varying.needsInterpolation || ( varying.needsInterpolation = ( builder.shaderStage === 'fragment' ) );
  5407. return varying;
  5408. }
  5409. setup( builder ) {
  5410. this.setupVarying( builder );
  5411. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node );
  5412. }
  5413. analyze( builder ) {
  5414. this.setupVarying( builder );
  5415. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node );
  5416. }
  5417. generate( builder ) {
  5418. const properties = builder.getNodeProperties( this );
  5419. const varying = this.setupVarying( builder );
  5420. if ( properties.propertyName === undefined ) {
  5421. const type = this.getNodeType( builder );
  5422. const propertyName = builder.getPropertyName( varying, NodeShaderStage.VERTEX );
  5423. // force node run in vertex stage
  5424. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node, type, propertyName );
  5425. properties.propertyName = propertyName;
  5426. }
  5427. return builder.getPropertyName( varying );
  5428. }
  5429. }
  5430. /**
  5431. * TSL function for creating a varying node.
  5432. *
  5433. * @tsl
  5434. * @function
  5435. * @param {Node} node - The node for which a varying should be created.
  5436. * @param {?string} name - The name of the varying in the shader.
  5437. * @returns {VaryingNode}
  5438. */
  5439. const varying = /*@__PURE__*/ nodeProxy( VaryingNode ).setParameterLength( 1, 2 );
  5440. /**
  5441. * Computes a node in the vertex stage.
  5442. *
  5443. * @tsl
  5444. * @function
  5445. * @param {Node} node - The node which should be executed in the vertex stage.
  5446. * @returns {VaryingNode}
  5447. */
  5448. const vertexStage = ( node ) => varying( node );
  5449. addMethodChaining( 'toVarying', varying );
  5450. addMethodChaining( 'toVertexStage', vertexStage );
  5451. // Deprecated
  5452. addMethodChaining( 'varying', ( ...params ) => { // @deprecated, r173
  5453. console.warn( 'THREE.TSL: .varying() has been renamed to .toVarying().' );
  5454. return varying( ...params );
  5455. } );
  5456. addMethodChaining( 'vertexStage', ( ...params ) => { // @deprecated, r173
  5457. console.warn( 'THREE.TSL: .vertexStage() has been renamed to .toVertexStage().' );
  5458. return varying( ...params );
  5459. } );
  5460. /**
  5461. * Converts the given color value from sRGB to linear-sRGB color space.
  5462. *
  5463. * @tsl
  5464. * @function
  5465. * @param {Node<vec3>} color - The sRGB color.
  5466. * @return {Node<vec3>} The linear-sRGB color.
  5467. */
  5468. const sRGBTransferEOTF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  5469. const a = color.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 );
  5470. const b = color.mul( 0.0773993808 );
  5471. const factor = color.lessThanEqual( 0.04045 );
  5472. const rgbResult = mix( a, b, factor );
  5473. return rgbResult;
  5474. } ).setLayout( {
  5475. name: 'sRGBTransferEOTF',
  5476. type: 'vec3',
  5477. inputs: [
  5478. { name: 'color', type: 'vec3' }
  5479. ]
  5480. } );
  5481. /**
  5482. * Converts the given color value from linear-sRGB to sRGB color space.
  5483. *
  5484. * @tsl
  5485. * @function
  5486. * @param {Node<vec3>} color - The linear-sRGB color.
  5487. * @return {Node<vec3>} The sRGB color.
  5488. */
  5489. const sRGBTransferOETF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  5490. const a = color.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 );
  5491. const b = color.mul( 12.92 );
  5492. const factor = color.lessThanEqual( 0.0031308 );
  5493. const rgbResult = mix( a, b, factor );
  5494. return rgbResult;
  5495. } ).setLayout( {
  5496. name: 'sRGBTransferOETF',
  5497. type: 'vec3',
  5498. inputs: [
  5499. { name: 'color', type: 'vec3' }
  5500. ]
  5501. } );
  5502. const WORKING_COLOR_SPACE = 'WorkingColorSpace';
  5503. const OUTPUT_COLOR_SPACE = 'OutputColorSpace';
  5504. /**
  5505. * This node represents a color space conversion. Meaning it converts
  5506. * a color value from a source to a target color space.
  5507. *
  5508. * @augments TempNode
  5509. */
  5510. class ColorSpaceNode extends TempNode {
  5511. static get type() {
  5512. return 'ColorSpaceNode';
  5513. }
  5514. /**
  5515. * Constructs a new color space node.
  5516. *
  5517. * @param {Node} colorNode - Represents the color to convert.
  5518. * @param {string} source - The source color space.
  5519. * @param {string} target - The target color space.
  5520. */
  5521. constructor( colorNode, source, target ) {
  5522. super( 'vec4' );
  5523. /**
  5524. * Represents the color to convert.
  5525. *
  5526. * @type {Node}
  5527. */
  5528. this.colorNode = colorNode;
  5529. /**
  5530. * The source color space.
  5531. *
  5532. * @type {string}
  5533. */
  5534. this.source = source;
  5535. /**
  5536. * The target color space.
  5537. *
  5538. * @type {string}
  5539. */
  5540. this.target = target;
  5541. }
  5542. /**
  5543. * This method resolves the constants `WORKING_COLOR_SPACE` and
  5544. * `OUTPUT_COLOR_SPACE` based on the current configuration of the
  5545. * color management and renderer.
  5546. *
  5547. * @param {NodeBuilder} builder - The current node builder.
  5548. * @param {string} colorSpace - The color space to resolve.
  5549. * @return {string} The resolved color space.
  5550. */
  5551. resolveColorSpace( builder, colorSpace ) {
  5552. if ( colorSpace === WORKING_COLOR_SPACE ) {
  5553. return ColorManagement.workingColorSpace;
  5554. } else if ( colorSpace === OUTPUT_COLOR_SPACE ) {
  5555. return builder.context.outputColorSpace || builder.renderer.outputColorSpace;
  5556. }
  5557. return colorSpace;
  5558. }
  5559. setup( builder ) {
  5560. const { colorNode } = this;
  5561. const source = this.resolveColorSpace( builder, this.source );
  5562. const target = this.resolveColorSpace( builder, this.target );
  5563. let outputNode = colorNode;
  5564. if ( ColorManagement.enabled === false || source === target || ! source || ! target ) {
  5565. return outputNode;
  5566. }
  5567. if ( ColorManagement.getTransfer( source ) === SRGBTransfer ) {
  5568. outputNode = vec4( sRGBTransferEOTF( outputNode.rgb ), outputNode.a );
  5569. }
  5570. if ( ColorManagement.getPrimaries( source ) !== ColorManagement.getPrimaries( target ) ) {
  5571. outputNode = vec4(
  5572. mat3( ColorManagement._getMatrix( new Matrix3(), source, target ) ).mul( outputNode.rgb ),
  5573. outputNode.a
  5574. );
  5575. }
  5576. if ( ColorManagement.getTransfer( target ) === SRGBTransfer ) {
  5577. outputNode = vec4( sRGBTransferOETF( outputNode.rgb ), outputNode.a );
  5578. }
  5579. return outputNode;
  5580. }
  5581. }
  5582. /**
  5583. * TSL function for converting a given color node from the current working color space to the given color space.
  5584. *
  5585. * @tsl
  5586. * @function
  5587. * @param {Node} node - Represents the node to convert.
  5588. * @param {string} targetColorSpace - The target color space.
  5589. * @returns {ColorSpaceNode}
  5590. */
  5591. const workingToColorSpace = ( node, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, targetColorSpace ) );
  5592. /**
  5593. * TSL function for converting a given color node from the given color space to the current working color space.
  5594. *
  5595. * @tsl
  5596. * @function
  5597. * @param {Node} node - Represents the node to convert.
  5598. * @param {string} sourceColorSpace - The source color space.
  5599. * @returns {ColorSpaceNode}
  5600. */
  5601. const colorSpaceToWorking = ( node, sourceColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, WORKING_COLOR_SPACE ) );
  5602. /**
  5603. * TSL function for converting a given color node from one color space to another one.
  5604. *
  5605. * @tsl
  5606. * @function
  5607. * @param {Node} node - Represents the node to convert.
  5608. * @param {string} sourceColorSpace - The source color space.
  5609. * @param {string} targetColorSpace - The target color space.
  5610. * @returns {ColorSpaceNode}
  5611. */
  5612. const convertColorSpace = ( node, sourceColorSpace, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, targetColorSpace ) );
  5613. addMethodChaining( 'workingToColorSpace', workingToColorSpace );
  5614. addMethodChaining( 'colorSpaceToWorking', colorSpaceToWorking );
  5615. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  5616. /**
  5617. * This class is only relevant if the referenced property is array-like.
  5618. * In this case, `ReferenceElementNode` allows to refer to a specific
  5619. * element inside the data structure via an index.
  5620. *
  5621. * @augments ArrayElementNode
  5622. */
  5623. let ReferenceElementNode$1 = class ReferenceElementNode extends ArrayElementNode {
  5624. static get type() {
  5625. return 'ReferenceElementNode';
  5626. }
  5627. /**
  5628. * Constructs a new reference element node.
  5629. *
  5630. * @param {ReferenceBaseNode} referenceNode - The reference node.
  5631. * @param {Node} indexNode - The index node that defines the element access.
  5632. */
  5633. constructor( referenceNode, indexNode ) {
  5634. super( referenceNode, indexNode );
  5635. /**
  5636. * Similar to {@link ReferenceBaseNode#reference}, an additional
  5637. * property references to the current node.
  5638. *
  5639. * @type {?ReferenceBaseNode}
  5640. * @default null
  5641. */
  5642. this.referenceNode = referenceNode;
  5643. /**
  5644. * This flag can be used for type testing.
  5645. *
  5646. * @type {boolean}
  5647. * @readonly
  5648. * @default true
  5649. */
  5650. this.isReferenceElementNode = true;
  5651. }
  5652. /**
  5653. * This method is overwritten since the node type is inferred from
  5654. * the uniform type of the reference node.
  5655. *
  5656. * @return {string} The node type.
  5657. */
  5658. getNodeType() {
  5659. return this.referenceNode.uniformType;
  5660. }
  5661. generate( builder ) {
  5662. const snippet = super.generate( builder );
  5663. const arrayType = this.referenceNode.getNodeType();
  5664. const elementType = this.getNodeType();
  5665. return builder.format( snippet, arrayType, elementType );
  5666. }
  5667. };
  5668. /**
  5669. * Base class for nodes which establishes a reference to a property of another object.
  5670. * In this way, the value of the node is automatically linked to the value of
  5671. * referenced object. Reference nodes internally represent the linked value
  5672. * as a uniform.
  5673. *
  5674. * @augments Node
  5675. */
  5676. class ReferenceBaseNode extends Node {
  5677. static get type() {
  5678. return 'ReferenceBaseNode';
  5679. }
  5680. /**
  5681. * Constructs a new reference base node.
  5682. *
  5683. * @param {string} property - The name of the property the node refers to.
  5684. * @param {string} uniformType - The uniform type that should be used to represent the property value.
  5685. * @param {?Object} [object=null] - The object the property belongs to.
  5686. * @param {?number} [count=null] - When the linked property is an array-like, this parameter defines its length.
  5687. */
  5688. constructor( property, uniformType, object = null, count = null ) {
  5689. super();
  5690. /**
  5691. * The name of the property the node refers to.
  5692. *
  5693. * @type {string}
  5694. */
  5695. this.property = property;
  5696. /**
  5697. * The uniform type that should be used to represent the property value.
  5698. *
  5699. * @type {string}
  5700. */
  5701. this.uniformType = uniformType;
  5702. /**
  5703. * The object the property belongs to.
  5704. *
  5705. * @type {?Object}
  5706. * @default null
  5707. */
  5708. this.object = object;
  5709. /**
  5710. * When the linked property is an array, this parameter defines its length.
  5711. *
  5712. * @type {?number}
  5713. * @default null
  5714. */
  5715. this.count = count;
  5716. /**
  5717. * The property name might have dots so nested properties can be referred.
  5718. * The hierarchy of the names is stored inside this array.
  5719. *
  5720. * @type {Array<string>}
  5721. */
  5722. this.properties = property.split( '.' );
  5723. /**
  5724. * Points to the current referred object. This property exists next to {@link ReferenceNode#object}
  5725. * since the final reference might be updated from calling code.
  5726. *
  5727. * @type {?Object}
  5728. * @default null
  5729. */
  5730. this.reference = object;
  5731. /**
  5732. * The uniform node that holds the value of the reference node.
  5733. *
  5734. * @type {UniformNode}
  5735. * @default null
  5736. */
  5737. this.node = null;
  5738. /**
  5739. * The uniform group of the internal uniform.
  5740. *
  5741. * @type {UniformGroupNode}
  5742. * @default null
  5743. */
  5744. this.group = null;
  5745. /**
  5746. * Overwritten since reference nodes are updated per object.
  5747. *
  5748. * @type {string}
  5749. * @default 'object'
  5750. */
  5751. this.updateType = NodeUpdateType.OBJECT;
  5752. }
  5753. /**
  5754. * Sets the uniform group for this reference node.
  5755. *
  5756. * @param {UniformGroupNode} group - The uniform group to set.
  5757. * @return {ReferenceBaseNode} A reference to this node.
  5758. */
  5759. setGroup( group ) {
  5760. this.group = group;
  5761. return this;
  5762. }
  5763. /**
  5764. * When the referred property is array-like, this method can be used
  5765. * to access elements via an index node.
  5766. *
  5767. * @param {IndexNode} indexNode - indexNode.
  5768. * @return {ReferenceElementNode} A reference to an element.
  5769. */
  5770. element( indexNode ) {
  5771. return nodeObject( new ReferenceElementNode$1( this, nodeObject( indexNode ) ) );
  5772. }
  5773. /**
  5774. * Sets the node type which automatically defines the internal
  5775. * uniform type.
  5776. *
  5777. * @param {string} uniformType - The type to set.
  5778. */
  5779. setNodeType( uniformType ) {
  5780. const node = uniform( null, uniformType ).getSelf();
  5781. if ( this.group !== null ) {
  5782. node.setGroup( this.group );
  5783. }
  5784. this.node = node;
  5785. }
  5786. /**
  5787. * This method is overwritten since the node type is inferred from
  5788. * the type of the reference node.
  5789. *
  5790. * @param {NodeBuilder} builder - The current node builder.
  5791. * @return {string} The node type.
  5792. */
  5793. getNodeType( builder ) {
  5794. if ( this.node === null ) {
  5795. this.updateReference( builder );
  5796. this.updateValue();
  5797. }
  5798. return this.node.getNodeType( builder );
  5799. }
  5800. /**
  5801. * Returns the property value from the given referred object.
  5802. *
  5803. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  5804. * @return {any} The value.
  5805. */
  5806. getValueFromReference( object = this.reference ) {
  5807. const { properties } = this;
  5808. let value = object[ properties[ 0 ] ];
  5809. for ( let i = 1; i < properties.length; i ++ ) {
  5810. value = value[ properties[ i ] ];
  5811. }
  5812. return value;
  5813. }
  5814. /**
  5815. * Allows to update the reference based on the given state. The state is only
  5816. * evaluated {@link ReferenceBaseNode#object} is not set.
  5817. *
  5818. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  5819. * @return {Object} The updated reference.
  5820. */
  5821. updateReference( state ) {
  5822. this.reference = this.object !== null ? this.object : state.object;
  5823. return this.reference;
  5824. }
  5825. /**
  5826. * The output of the reference node is the internal uniform node.
  5827. *
  5828. * @return {UniformNode} The output node.
  5829. */
  5830. setup() {
  5831. this.updateValue();
  5832. return this.node;
  5833. }
  5834. /**
  5835. * Overwritten to update the internal uniform value.
  5836. *
  5837. * @param {NodeFrame} frame - A reference to the current node frame.
  5838. */
  5839. update( /*frame*/ ) {
  5840. this.updateValue();
  5841. }
  5842. /**
  5843. * Retrieves the value from the referred object property and uses it
  5844. * to updated the internal uniform.
  5845. */
  5846. updateValue() {
  5847. if ( this.node === null ) this.setNodeType( this.uniformType );
  5848. const value = this.getValueFromReference();
  5849. if ( Array.isArray( value ) ) {
  5850. this.node.array = value;
  5851. } else {
  5852. this.node.value = value;
  5853. }
  5854. }
  5855. }
  5856. /**
  5857. * TSL function for creating a reference base node.
  5858. *
  5859. * @tsl
  5860. * @function
  5861. * @param {string} name - The name of the property the node refers to.
  5862. * @param {string} type - The uniform type that should be used to represent the property value.
  5863. * @param {Object} object - The object the property belongs to.
  5864. * @returns {ReferenceBaseNode}
  5865. */
  5866. const reference$1 = ( name, type, object ) => nodeObject( new ReferenceBaseNode( name, type, object ) );
  5867. /**
  5868. * This node is a special type of reference node which is intended
  5869. * for linking renderer properties with node values.
  5870. * ```js
  5871. * const exposureNode = rendererReference( 'toneMappingExposure', 'float', renderer );
  5872. * ```
  5873. * When changing `renderer.toneMappingExposure`, the node value of `exposureNode` will
  5874. * automatically be updated.
  5875. *
  5876. * @augments ReferenceBaseNode
  5877. */
  5878. class RendererReferenceNode extends ReferenceBaseNode {
  5879. static get type() {
  5880. return 'RendererReferenceNode';
  5881. }
  5882. /**
  5883. * Constructs a new renderer reference node.
  5884. *
  5885. * @param {string} property - The name of the property the node refers to.
  5886. * @param {string} inputType - The uniform type that should be used to represent the property value.
  5887. * @param {?Renderer} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  5888. * the node refers to the renderer of the current state.
  5889. */
  5890. constructor( property, inputType, renderer = null ) {
  5891. super( property, inputType, renderer );
  5892. /**
  5893. * The renderer the property belongs to. When no renderer is set,
  5894. * the node refers to the renderer of the current state.
  5895. *
  5896. * @type {?Renderer}
  5897. * @default null
  5898. */
  5899. this.renderer = renderer;
  5900. this.setGroup( renderGroup );
  5901. }
  5902. /**
  5903. * Updates the reference based on the given state. The state is only evaluated
  5904. * {@link RendererReferenceNode#renderer} is not set.
  5905. *
  5906. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  5907. * @return {Object} The updated reference.
  5908. */
  5909. updateReference( state ) {
  5910. this.reference = this.renderer !== null ? this.renderer : state.renderer;
  5911. return this.reference;
  5912. }
  5913. }
  5914. /**
  5915. * TSL function for creating a renderer reference node.
  5916. *
  5917. * @tsl
  5918. * @function
  5919. * @param {string} name - The name of the property the node refers to.
  5920. * @param {string} type - The uniform type that should be used to represent the property value.
  5921. * @param {?Renderer} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  5922. * the node refers to the renderer of the current state.
  5923. * @returns {RendererReferenceNode}
  5924. */
  5925. const rendererReference = ( name, type, renderer = null ) => nodeObject( new RendererReferenceNode( name, type, renderer ) );
  5926. /**
  5927. * This node represents a tone mapping operation.
  5928. *
  5929. * @augments TempNode
  5930. */
  5931. class ToneMappingNode extends TempNode {
  5932. static get type() {
  5933. return 'ToneMappingNode';
  5934. }
  5935. /**
  5936. * Constructs a new tone mapping node.
  5937. *
  5938. * @param {number} toneMapping - The tone mapping type.
  5939. * @param {Node} exposureNode - The tone mapping exposure.
  5940. * @param {Node} [colorNode=null] - The color node to process.
  5941. */
  5942. constructor( toneMapping, exposureNode = toneMappingExposure, colorNode = null ) {
  5943. super( 'vec3' );
  5944. /**
  5945. * The tone mapping type.
  5946. *
  5947. * @type {number}
  5948. */
  5949. this.toneMapping = toneMapping;
  5950. /**
  5951. * The tone mapping exposure.
  5952. *
  5953. * @type {Node}
  5954. * @default null
  5955. */
  5956. this.exposureNode = exposureNode;
  5957. /**
  5958. * Represents the color to process.
  5959. *
  5960. * @type {?Node}
  5961. * @default null
  5962. */
  5963. this.colorNode = colorNode;
  5964. }
  5965. /**
  5966. * Overwrites the default `customCacheKey()` implementation by including the tone
  5967. * mapping type into the cache key.
  5968. *
  5969. * @return {number} The hash.
  5970. */
  5971. customCacheKey() {
  5972. return hash$1( this.toneMapping );
  5973. }
  5974. setup( builder ) {
  5975. const colorNode = this.colorNode || builder.context.color;
  5976. const toneMapping = this.toneMapping;
  5977. if ( toneMapping === NoToneMapping ) return colorNode;
  5978. let outputNode = null;
  5979. const toneMappingFn = builder.renderer.library.getToneMappingFunction( toneMapping );
  5980. if ( toneMappingFn !== null ) {
  5981. outputNode = vec4( toneMappingFn( colorNode.rgb, this.exposureNode ), colorNode.a );
  5982. } else {
  5983. console.error( 'ToneMappingNode: Unsupported Tone Mapping configuration.', toneMapping );
  5984. outputNode = colorNode;
  5985. }
  5986. return outputNode;
  5987. }
  5988. }
  5989. /**
  5990. * TSL function for creating a tone mapping node.
  5991. *
  5992. * @tsl
  5993. * @function
  5994. * @param {number} mapping - The tone mapping type.
  5995. * @param {Node<float> | number} exposure - The tone mapping exposure.
  5996. * @param {Node<vec3> | Color} color - The color node to process.
  5997. * @returns {ToneMappingNode<vec3>}
  5998. */
  5999. const toneMapping = ( mapping, exposure, color ) => nodeObject( new ToneMappingNode( mapping, nodeObject( exposure ), nodeObject( color ) ) );
  6000. /**
  6001. * TSL object that represents the global tone mapping exposure of the renderer.
  6002. *
  6003. * @tsl
  6004. * @type {RendererReferenceNode<vec3>}
  6005. */
  6006. const toneMappingExposure = /*@__PURE__*/ rendererReference( 'toneMappingExposure', 'float' );
  6007. addMethodChaining( 'toneMapping', ( color, mapping, exposure ) => toneMapping( mapping, exposure, color ) );
  6008. /**
  6009. * In earlier `three.js` versions it was only possible to define attribute data
  6010. * on geometry level. With `BufferAttributeNode`, it is also possible to do this
  6011. * on the node level.
  6012. * ```js
  6013. * const geometry = new THREE.PlaneGeometry();
  6014. * const positionAttribute = geometry.getAttribute( 'position' );
  6015. *
  6016. * const colors = [];
  6017. * for ( let i = 0; i < position.count; i ++ ) {
  6018. * colors.push( 1, 0, 0 );
  6019. * }
  6020. *
  6021. * material.colorNode = bufferAttribute( new THREE.Float32BufferAttribute( colors, 3 ) );
  6022. * ```
  6023. * This new approach is especially interesting when geometry data are generated via
  6024. * compute shaders. The below line converts a storage buffer into an attribute node.
  6025. * ```js
  6026. * material.positionNode = positionBuffer.toAttribute();
  6027. * ```
  6028. * @augments InputNode
  6029. */
  6030. class BufferAttributeNode extends InputNode {
  6031. static get type() {
  6032. return 'BufferAttributeNode';
  6033. }
  6034. /**
  6035. * Constructs a new buffer attribute node.
  6036. *
  6037. * @param {BufferAttribute|InterleavedBuffer|TypedArray} value - The attribute data.
  6038. * @param {?string} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  6039. * @param {number} [bufferStride=0] - The buffer stride.
  6040. * @param {number} [bufferOffset=0] - The buffer offset.
  6041. */
  6042. constructor( value, bufferType = null, bufferStride = 0, bufferOffset = 0 ) {
  6043. super( value, bufferType );
  6044. /**
  6045. * This flag can be used for type testing.
  6046. *
  6047. * @type {boolean}
  6048. * @readonly
  6049. * @default true
  6050. */
  6051. this.isBufferNode = true;
  6052. /**
  6053. * The buffer type (e.g. `'vec3'`).
  6054. *
  6055. * @type {?string}
  6056. * @default null
  6057. */
  6058. this.bufferType = bufferType;
  6059. /**
  6060. * The buffer stride.
  6061. *
  6062. * @type {number}
  6063. * @default 0
  6064. */
  6065. this.bufferStride = bufferStride;
  6066. /**
  6067. * The buffer offset.
  6068. *
  6069. * @type {number}
  6070. * @default 0
  6071. */
  6072. this.bufferOffset = bufferOffset;
  6073. /**
  6074. * The usage property. Set this to `THREE.DynamicDrawUsage` via `.setUsage()`,
  6075. * if you are planning to update the attribute data per frame.
  6076. *
  6077. * @type {number}
  6078. * @default StaticDrawUsage
  6079. */
  6080. this.usage = StaticDrawUsage;
  6081. /**
  6082. * Whether the attribute is instanced or not.
  6083. *
  6084. * @type {boolean}
  6085. * @default false
  6086. */
  6087. this.instanced = false;
  6088. /**
  6089. * A reference to the buffer attribute.
  6090. *
  6091. * @type {?BufferAttribute}
  6092. * @default null
  6093. */
  6094. this.attribute = null;
  6095. /**
  6096. * `BufferAttributeNode` sets this property to `true` by default.
  6097. *
  6098. * @type {boolean}
  6099. * @default true
  6100. */
  6101. this.global = true;
  6102. if ( value && value.isBufferAttribute === true ) {
  6103. this.attribute = value;
  6104. this.usage = value.usage;
  6105. this.instanced = value.isInstancedBufferAttribute;
  6106. }
  6107. }
  6108. /**
  6109. * This method is overwritten since the attribute data might be shared
  6110. * and thus the hash should be shared as well.
  6111. *
  6112. * @param {NodeBuilder} builder - The current node builder.
  6113. * @return {string} The hash.
  6114. */
  6115. getHash( builder ) {
  6116. if ( this.bufferStride === 0 && this.bufferOffset === 0 ) {
  6117. let bufferData = builder.globalCache.getData( this.value );
  6118. if ( bufferData === undefined ) {
  6119. bufferData = {
  6120. node: this
  6121. };
  6122. builder.globalCache.setData( this.value, bufferData );
  6123. }
  6124. return bufferData.node.uuid;
  6125. }
  6126. return this.uuid;
  6127. }
  6128. /**
  6129. * This method is overwritten since the node type is inferred from
  6130. * the buffer attribute.
  6131. *
  6132. * @param {NodeBuilder} builder - The current node builder.
  6133. * @return {string} The node type.
  6134. */
  6135. getNodeType( builder ) {
  6136. if ( this.bufferType === null ) {
  6137. this.bufferType = builder.getTypeFromAttribute( this.attribute );
  6138. }
  6139. return this.bufferType;
  6140. }
  6141. /**
  6142. * Depending on which value was passed to the node, `setup()` behaves
  6143. * differently. If no instance of `BufferAttribute` was passed, the method
  6144. * creates an internal attribute and configures it respectively.
  6145. *
  6146. * @param {NodeBuilder} builder - The current node builder.
  6147. */
  6148. setup( builder ) {
  6149. if ( this.attribute !== null ) return;
  6150. const type = this.getNodeType( builder );
  6151. const array = this.value;
  6152. const itemSize = builder.getTypeLength( type );
  6153. const stride = this.bufferStride || itemSize;
  6154. const offset = this.bufferOffset;
  6155. const buffer = array.isInterleavedBuffer === true ? array : new InterleavedBuffer( array, stride );
  6156. const bufferAttribute = new InterleavedBufferAttribute( buffer, itemSize, offset );
  6157. buffer.setUsage( this.usage );
  6158. this.attribute = bufferAttribute;
  6159. this.attribute.isInstancedBufferAttribute = this.instanced; // @TODO: Add a possible: InstancedInterleavedBufferAttribute
  6160. }
  6161. /**
  6162. * Generates the code snippet of the buffer attribute node.
  6163. *
  6164. * @param {NodeBuilder} builder - The current node builder.
  6165. * @return {string} The generated code snippet.
  6166. */
  6167. generate( builder ) {
  6168. const nodeType = this.getNodeType( builder );
  6169. const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType );
  6170. const propertyName = builder.getPropertyName( nodeAttribute );
  6171. let output = null;
  6172. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  6173. this.name = propertyName;
  6174. output = propertyName;
  6175. } else {
  6176. const nodeVarying = varying( this );
  6177. output = nodeVarying.build( builder, nodeType );
  6178. }
  6179. return output;
  6180. }
  6181. /**
  6182. * Overwrites the default implementation to return a fixed value `'bufferAttribute'`.
  6183. *
  6184. * @param {NodeBuilder} builder - The current node builder.
  6185. * @return {string} The input type.
  6186. */
  6187. getInputType( /*builder*/ ) {
  6188. return 'bufferAttribute';
  6189. }
  6190. /**
  6191. * Sets the `usage` property to the given value.
  6192. *
  6193. * @param {number} value - The usage to set.
  6194. * @return {BufferAttributeNode} A reference to this node.
  6195. */
  6196. setUsage( value ) {
  6197. this.usage = value;
  6198. if ( this.attribute && this.attribute.isBufferAttribute === true ) {
  6199. this.attribute.usage = value;
  6200. }
  6201. return this;
  6202. }
  6203. /**
  6204. * Sets the `instanced` property to the given value.
  6205. *
  6206. * @param {boolean} value - The value to set.
  6207. * @return {BufferAttributeNode} A reference to this node.
  6208. */
  6209. setInstanced( value ) {
  6210. this.instanced = value;
  6211. return this;
  6212. }
  6213. }
  6214. /**
  6215. * TSL function for creating a buffer attribute node.
  6216. *
  6217. * @tsl
  6218. * @function
  6219. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6220. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6221. * @param {number} [stride=0] - The buffer stride.
  6222. * @param {number} [offset=0] - The buffer offset.
  6223. * @returns {BufferAttributeNode}
  6224. */
  6225. const bufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => nodeObject( new BufferAttributeNode( array, type, stride, offset ) );
  6226. /**
  6227. * TSL function for creating a buffer attribute node but with dynamic draw usage.
  6228. * Use this function if attribute data are updated per frame.
  6229. *
  6230. * @tsl
  6231. * @function
  6232. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6233. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6234. * @param {number} [stride=0] - The buffer stride.
  6235. * @param {number} [offset=0] - The buffer offset.
  6236. * @returns {BufferAttributeNode}
  6237. */
  6238. const dynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => bufferAttribute( array, type, stride, offset ).setUsage( DynamicDrawUsage );
  6239. /**
  6240. * TSL function for creating a buffer attribute node but with enabled instancing
  6241. *
  6242. * @tsl
  6243. * @function
  6244. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6245. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6246. * @param {number} [stride=0] - The buffer stride.
  6247. * @param {number} [offset=0] - The buffer offset.
  6248. * @returns {BufferAttributeNode}
  6249. */
  6250. const instancedBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => bufferAttribute( array, type, stride, offset ).setInstanced( true );
  6251. /**
  6252. * TSL function for creating a buffer attribute node but with dynamic draw usage and enabled instancing
  6253. *
  6254. * @tsl
  6255. * @function
  6256. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6257. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6258. * @param {number} [stride=0] - The buffer stride.
  6259. * @param {number} [offset=0] - The buffer offset.
  6260. * @returns {BufferAttributeNode}
  6261. */
  6262. const instancedDynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => dynamicBufferAttribute( array, type, stride, offset ).setInstanced( true );
  6263. addMethodChaining( 'toAttribute', ( bufferNode ) => bufferAttribute( bufferNode.value ) );
  6264. /**
  6265. * TODO
  6266. *
  6267. * @augments Node
  6268. */
  6269. class ComputeNode extends Node {
  6270. static get type() {
  6271. return 'ComputeNode';
  6272. }
  6273. /**
  6274. * Constructs a new compute node.
  6275. *
  6276. * @param {Node} computeNode - TODO
  6277. * @param {number} count - TODO.
  6278. * @param {Array<number>} [workgroupSize=[64]] - TODO.
  6279. */
  6280. constructor( computeNode, count, workgroupSize = [ 64 ] ) {
  6281. super( 'void' );
  6282. /**
  6283. * This flag can be used for type testing.
  6284. *
  6285. * @type {boolean}
  6286. * @readonly
  6287. * @default true
  6288. */
  6289. this.isComputeNode = true;
  6290. /**
  6291. * TODO
  6292. *
  6293. * @type {Node}
  6294. */
  6295. this.computeNode = computeNode;
  6296. /**
  6297. * TODO
  6298. *
  6299. * @type {number}
  6300. */
  6301. this.count = count;
  6302. /**
  6303. * TODO
  6304. *
  6305. * @type {Array<number>}
  6306. * @default [64]
  6307. */
  6308. this.workgroupSize = workgroupSize;
  6309. /**
  6310. * TODO
  6311. *
  6312. * @type {number}
  6313. */
  6314. this.dispatchCount = 0;
  6315. /**
  6316. * TODO
  6317. *
  6318. * @type {number}
  6319. */
  6320. this.version = 1;
  6321. /**
  6322. * The name or label of the uniform.
  6323. *
  6324. * @type {string}
  6325. * @default ''
  6326. */
  6327. this.name = '';
  6328. /**
  6329. * The `updateBeforeType` is set to `NodeUpdateType.OBJECT` since {@link ComputeNode#updateBefore}
  6330. * is executed once per object by default.
  6331. *
  6332. * @type {string}
  6333. * @default 'object'
  6334. */
  6335. this.updateBeforeType = NodeUpdateType.OBJECT;
  6336. /**
  6337. * TODO
  6338. *
  6339. * @type {?Function}
  6340. */
  6341. this.onInitFunction = null;
  6342. this.updateDispatchCount();
  6343. }
  6344. /**
  6345. * Executes the `dispose` event for this node.
  6346. */
  6347. dispose() {
  6348. this.dispatchEvent( { type: 'dispose' } );
  6349. }
  6350. /**
  6351. * Sets the {@link ComputeNode#name} property.
  6352. *
  6353. * @param {string} name - The name of the uniform.
  6354. * @return {ComputeNode} A reference to this node.
  6355. */
  6356. label( name ) {
  6357. this.name = name;
  6358. return this;
  6359. }
  6360. /**
  6361. * TODO
  6362. */
  6363. updateDispatchCount() {
  6364. const { count, workgroupSize } = this;
  6365. let size = workgroupSize[ 0 ];
  6366. for ( let i = 1; i < workgroupSize.length; i ++ )
  6367. size *= workgroupSize[ i ];
  6368. this.dispatchCount = Math.ceil( count / size );
  6369. }
  6370. /**
  6371. * TODO
  6372. *
  6373. * @param {Function} callback - TODO.
  6374. * @return {ComputeNode} A reference to this node.
  6375. */
  6376. onInit( callback ) {
  6377. this.onInitFunction = callback;
  6378. return this;
  6379. }
  6380. /**
  6381. * The method execute the compute for this node.
  6382. *
  6383. * @param {NodeFrame} frame - A reference to the current node frame.
  6384. */
  6385. updateBefore( { renderer } ) {
  6386. renderer.compute( this );
  6387. }
  6388. setup( builder ) {
  6389. const result = this.computeNode.build( builder );
  6390. if ( result ) {
  6391. const properties = builder.getNodeProperties( this );
  6392. properties.outputComputeNode = result.outputNode;
  6393. result.outputNode = null;
  6394. }
  6395. return result;
  6396. }
  6397. generate( builder, output ) {
  6398. const { shaderStage } = builder;
  6399. if ( shaderStage === 'compute' ) {
  6400. const snippet = this.computeNode.build( builder, 'void' );
  6401. if ( snippet !== '' ) {
  6402. builder.addLineFlowCode( snippet, this );
  6403. }
  6404. } else {
  6405. const properties = builder.getNodeProperties( this );
  6406. const outputComputeNode = properties.outputComputeNode;
  6407. if ( outputComputeNode ) {
  6408. return outputComputeNode.build( builder, output );
  6409. }
  6410. }
  6411. }
  6412. }
  6413. /**
  6414. * TSL function for creating a compute node.
  6415. *
  6416. * @tsl
  6417. * @function
  6418. * @param {Node} node - TODO
  6419. * @param {number} count - TODO.
  6420. * @param {Array<number>} [workgroupSize=[64]] - TODO.
  6421. * @returns {AtomicFunctionNode}
  6422. */
  6423. const compute = ( node, count, workgroupSize ) => nodeObject( new ComputeNode( nodeObject( node ), count, workgroupSize ) );
  6424. addMethodChaining( 'compute', compute );
  6425. /**
  6426. * This node can be used as a cache management component for another node.
  6427. * Caching is in general used by default in {@link NodeBuilder} but this node
  6428. * allows the usage of a shared parent cache during the build process.
  6429. *
  6430. * @augments Node
  6431. */
  6432. class CacheNode extends Node {
  6433. static get type() {
  6434. return 'CacheNode';
  6435. }
  6436. /**
  6437. * Constructs a new cache node.
  6438. *
  6439. * @param {Node} node - The node that should be cached.
  6440. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  6441. */
  6442. constructor( node, parent = true ) {
  6443. super();
  6444. /**
  6445. * The node that should be cached.
  6446. *
  6447. * @type {Node}
  6448. */
  6449. this.node = node;
  6450. /**
  6451. * Whether this node refers to a shared parent cache or not.
  6452. *
  6453. * @type {boolean}
  6454. * @default true
  6455. */
  6456. this.parent = parent;
  6457. /**
  6458. * This flag can be used for type testing.
  6459. *
  6460. * @type {boolean}
  6461. * @readonly
  6462. * @default true
  6463. */
  6464. this.isCacheNode = true;
  6465. }
  6466. getNodeType( builder ) {
  6467. const previousCache = builder.getCache();
  6468. const cache = builder.getCacheFromNode( this, this.parent );
  6469. builder.setCache( cache );
  6470. const nodeType = this.node.getNodeType( builder );
  6471. builder.setCache( previousCache );
  6472. return nodeType;
  6473. }
  6474. build( builder, ...params ) {
  6475. const previousCache = builder.getCache();
  6476. const cache = builder.getCacheFromNode( this, this.parent );
  6477. builder.setCache( cache );
  6478. const data = this.node.build( builder, ...params );
  6479. builder.setCache( previousCache );
  6480. return data;
  6481. }
  6482. }
  6483. /**
  6484. * TSL function for creating a cache node.
  6485. *
  6486. * @tsl
  6487. * @function
  6488. * @param {Node} node - The node that should be cached.
  6489. * @param {boolean} [parent] - Whether this node refers to a shared parent cache or not.
  6490. * @returns {CacheNode}
  6491. */
  6492. const cache = ( node, parent ) => nodeObject( new CacheNode( nodeObject( node ), parent ) );
  6493. /**
  6494. * Assigns a namespace to the given node by updating its context.
  6495. *
  6496. * Important for TSL functions that use `.once( namespace )` to ensure that the namespace will run twice,
  6497. * once when the node is build in the specific namespace and once when the node is built in the others namespace.
  6498. *
  6499. * This is useful for nodes like `positionWorld` that need to be re-updated if used in `material.positionNode` and outside of it in the same material.
  6500. *
  6501. * @param {Object} node - The node to which the namespace will be assigned.
  6502. * @param {string} namespace - The namespace to be assigned to the node.
  6503. * @returns {Object} The updated node with the new namespace in its context.
  6504. */
  6505. const namespace = ( node, namespace ) => node.context( { namespace } );
  6506. addMethodChaining( 'cache', cache );
  6507. /**
  6508. * The class generates the code of a given node but returns another node in the output.
  6509. * This can be used to call a method or node that does not return a value, i.e.
  6510. * type `void` on an input where returning a value is required. Example:
  6511. *
  6512. * ```js
  6513. * material.colorNode = myColor.bypass( runVoidFn() )
  6514. *```
  6515. *
  6516. * @augments Node
  6517. */
  6518. class BypassNode extends Node {
  6519. static get type() {
  6520. return 'BypassNode';
  6521. }
  6522. /**
  6523. * Constructs a new bypass node.
  6524. *
  6525. * @param {Node} outputNode - The output node.
  6526. * @param {Node} callNode - The call node.
  6527. */
  6528. constructor( outputNode, callNode ) {
  6529. super();
  6530. /**
  6531. * This flag can be used for type testing.
  6532. *
  6533. * @type {boolean}
  6534. * @readonly
  6535. * @default true
  6536. */
  6537. this.isBypassNode = true;
  6538. /**
  6539. * The output node.
  6540. *
  6541. * @type {Node}
  6542. */
  6543. this.outputNode = outputNode;
  6544. /**
  6545. * The call node.
  6546. *
  6547. * @type {Node}
  6548. */
  6549. this.callNode = callNode;
  6550. }
  6551. getNodeType( builder ) {
  6552. return this.outputNode.getNodeType( builder );
  6553. }
  6554. generate( builder ) {
  6555. const snippet = this.callNode.build( builder, 'void' );
  6556. if ( snippet !== '' ) {
  6557. builder.addLineFlowCode( snippet, this );
  6558. }
  6559. return this.outputNode.build( builder );
  6560. }
  6561. }
  6562. /**
  6563. * TSL function for creating a bypass node.
  6564. *
  6565. * @tsl
  6566. * @function
  6567. * @param {Node} outputNode - The output node.
  6568. * @param {Node} callNode - The call node.
  6569. * @returns {BypassNode}
  6570. */
  6571. const bypass = /*@__PURE__*/ nodeProxy( BypassNode ).setParameterLength( 2 );
  6572. addMethodChaining( 'bypass', bypass );
  6573. /**
  6574. * This node allows to remap a node value from one range into another. E.g a value of
  6575. * `0.4` in the range `[ 0.3, 0.5 ]` should be remapped into the normalized range `[ 0, 1 ]`.
  6576. * `RemapNode` takes care of that and converts the original value of `0.4` to `0.5`.
  6577. *
  6578. * @augments Node
  6579. */
  6580. class RemapNode extends Node {
  6581. static get type() {
  6582. return 'RemapNode';
  6583. }
  6584. /**
  6585. * Constructs a new remap node.
  6586. *
  6587. * @param {Node} node - The node that should be remapped.
  6588. * @param {Node} inLowNode - The source or current lower bound of the range.
  6589. * @param {Node} inHighNode - The source or current upper bound of the range.
  6590. * @param {Node} [outLowNode=float(0)] - The target lower bound of the range.
  6591. * @param {Node} [outHighNode=float(1)] - The target upper bound of the range.
  6592. */
  6593. constructor( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) {
  6594. super();
  6595. /**
  6596. * The node that should be remapped.
  6597. *
  6598. * @type {Node}
  6599. */
  6600. this.node = node;
  6601. /**
  6602. * The source or current lower bound of the range.
  6603. *
  6604. * @type {Node}
  6605. */
  6606. this.inLowNode = inLowNode;
  6607. /**
  6608. * The source or current upper bound of the range.
  6609. *
  6610. * @type {Node}
  6611. */
  6612. this.inHighNode = inHighNode;
  6613. /**
  6614. * The target lower bound of the range.
  6615. *
  6616. * @type {Node}
  6617. * @default float(0)
  6618. */
  6619. this.outLowNode = outLowNode;
  6620. /**
  6621. * The target upper bound of the range.
  6622. *
  6623. * @type {Node}
  6624. * @default float(1)
  6625. */
  6626. this.outHighNode = outHighNode;
  6627. /**
  6628. * Whether the node value should be clamped before
  6629. * remapping it to the target range.
  6630. *
  6631. * @type {boolean}
  6632. * @default true
  6633. */
  6634. this.doClamp = true;
  6635. }
  6636. setup() {
  6637. const { node, inLowNode, inHighNode, outLowNode, outHighNode, doClamp } = this;
  6638. let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) );
  6639. if ( doClamp === true ) t = t.clamp();
  6640. return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode );
  6641. }
  6642. }
  6643. /**
  6644. * TSL function for creating a remap node.
  6645. *
  6646. * @tsl
  6647. * @function
  6648. * @param {Node} node - The node that should be remapped.
  6649. * @param {Node} inLowNode - The source or current lower bound of the range.
  6650. * @param {Node} inHighNode - The source or current upper bound of the range.
  6651. * @param {?Node} [outLowNode=float(0)] - The target lower bound of the range.
  6652. * @param {?Node} [outHighNode=float(1)] - The target upper bound of the range.
  6653. * @returns {RemapNode}
  6654. */
  6655. const remap = /*@__PURE__*/ nodeProxy( RemapNode, null, null, { doClamp: false } ).setParameterLength( 3, 5 );
  6656. /**
  6657. * TSL function for creating a remap node, but with enabled clamping.
  6658. *
  6659. * @tsl
  6660. * @function
  6661. * @param {Node} node - The node that should be remapped.
  6662. * @param {Node} inLowNode - The source or current lower bound of the range.
  6663. * @param {Node} inHighNode - The source or current upper bound of the range.
  6664. * @param {?Node} [outLowNode=float(0)] - The target lower bound of the range.
  6665. * @param {?Node} [outHighNode=float(1)] - The target upper bound of the range.
  6666. * @returns {RemapNode}
  6667. */
  6668. const remapClamp = /*@__PURE__*/ nodeProxy( RemapNode ).setParameterLength( 3, 5 );
  6669. addMethodChaining( 'remap', remap );
  6670. addMethodChaining( 'remapClamp', remapClamp );
  6671. /**
  6672. * This class can be used to implement basic expressions in shader code.
  6673. * Basic examples for that are `return`, `continue` or `discard` statements.
  6674. *
  6675. * @augments Node
  6676. */
  6677. class ExpressionNode extends Node {
  6678. static get type() {
  6679. return 'ExpressionNode';
  6680. }
  6681. /**
  6682. * Constructs a new expression node.
  6683. *
  6684. * @param {string} [snippet=''] - The native code snippet.
  6685. * @param {string} [nodeType='void'] - The node type.
  6686. */
  6687. constructor( snippet = '', nodeType = 'void' ) {
  6688. super( nodeType );
  6689. /**
  6690. * The native code snippet.
  6691. *
  6692. * @type {string}
  6693. * @default ''
  6694. */
  6695. this.snippet = snippet;
  6696. }
  6697. generate( builder, output ) {
  6698. const type = this.getNodeType( builder );
  6699. const snippet = this.snippet;
  6700. if ( type === 'void' ) {
  6701. builder.addLineFlowCode( snippet, this );
  6702. } else {
  6703. return builder.format( snippet, type, output );
  6704. }
  6705. }
  6706. }
  6707. /**
  6708. * TSL function for creating an expression node.
  6709. *
  6710. * @tsl
  6711. * @function
  6712. * @param {string} [snippet] - The native code snippet.
  6713. * @param {?string} [nodeType='void'] - The node type.
  6714. * @returns {ExpressionNode}
  6715. */
  6716. const expression = /*@__PURE__*/ nodeProxy( ExpressionNode ).setParameterLength( 1, 2 );
  6717. /**
  6718. * Represents a `discard` shader operation in TSL.
  6719. *
  6720. * @tsl
  6721. * @function
  6722. * @param {?ConditionalNode} conditional - An optional conditional node. It allows to decide whether the discard should be executed or not.
  6723. * @return {Node} The `discard` expression.
  6724. */
  6725. const Discard = ( conditional ) => ( conditional ? select( conditional, expression( 'discard' ) ) : expression( 'discard' ) ).toStack();
  6726. /**
  6727. * Represents a `return` shader operation in TSL.
  6728. *
  6729. * @tsl
  6730. * @function
  6731. * @return {ExpressionNode} The `return` expression.
  6732. */
  6733. const Return = () => expression( 'return' ).toStack();
  6734. addMethodChaining( 'discard', Discard );
  6735. /**
  6736. * Normally, tone mapping and color conversion happens automatically
  6737. * before outputting pixel too the default (screen) framebuffer. In certain
  6738. * post processing setups this happens to late because certain effects
  6739. * require e.g. sRGB input. For such scenarios, `RenderOutputNode` can be used
  6740. * to apply tone mapping and color space conversion at an arbitrary point
  6741. * in the effect chain.
  6742. *
  6743. * When applying tone mapping and color space conversion manually with this node,
  6744. * you have to set {@link PostProcessing#outputColorTransform} to `false`.
  6745. *
  6746. * ```js
  6747. * const postProcessing = new PostProcessing( renderer );
  6748. * postProcessing.outputColorTransform = false;
  6749. *
  6750. * const scenePass = pass( scene, camera );
  6751. * const outputPass = renderOutput( scenePass );
  6752. *
  6753. * postProcessing.outputNode = outputPass;
  6754. * ```
  6755. *
  6756. * @augments TempNode
  6757. */
  6758. class RenderOutputNode extends TempNode {
  6759. static get type() {
  6760. return 'RenderOutputNode';
  6761. }
  6762. /**
  6763. * Constructs a new render output node.
  6764. *
  6765. * @param {Node} colorNode - The color node to process.
  6766. * @param {?number} toneMapping - The tone mapping type.
  6767. * @param {?string} outputColorSpace - The output color space.
  6768. */
  6769. constructor( colorNode, toneMapping, outputColorSpace ) {
  6770. super( 'vec4' );
  6771. /**
  6772. * The color node to process.
  6773. *
  6774. * @type {Node}
  6775. */
  6776. this.colorNode = colorNode;
  6777. /**
  6778. * The tone mapping type.
  6779. *
  6780. * @type {?number}
  6781. */
  6782. this.toneMapping = toneMapping;
  6783. /**
  6784. * The output color space.
  6785. *
  6786. * @type {?string}
  6787. */
  6788. this.outputColorSpace = outputColorSpace;
  6789. /**
  6790. * This flag can be used for type testing.
  6791. *
  6792. * @type {boolean}
  6793. * @readonly
  6794. * @default true
  6795. */
  6796. this.isRenderOutputNode = true;
  6797. }
  6798. setup( { context } ) {
  6799. let outputNode = this.colorNode || context.color;
  6800. // tone mapping
  6801. const toneMapping = ( this.toneMapping !== null ? this.toneMapping : context.toneMapping ) || NoToneMapping;
  6802. const outputColorSpace = ( this.outputColorSpace !== null ? this.outputColorSpace : context.outputColorSpace ) || NoColorSpace;
  6803. if ( toneMapping !== NoToneMapping ) {
  6804. outputNode = outputNode.toneMapping( toneMapping );
  6805. }
  6806. // working to output color space
  6807. if ( outputColorSpace !== NoColorSpace && outputColorSpace !== ColorManagement.workingColorSpace ) {
  6808. outputNode = outputNode.workingToColorSpace( outputColorSpace );
  6809. }
  6810. return outputNode;
  6811. }
  6812. }
  6813. /**
  6814. * TSL function for creating a posterize node.
  6815. *
  6816. * @tsl
  6817. * @function
  6818. * @param {Node} color - The color node to process.
  6819. * @param {?number} [toneMapping=null] - The tone mapping type.
  6820. * @param {?string} [outputColorSpace=null] - The output color space.
  6821. * @returns {RenderOutputNode}
  6822. */
  6823. const renderOutput = ( color, toneMapping = null, outputColorSpace = null ) => nodeObject( new RenderOutputNode( nodeObject( color ), toneMapping, outputColorSpace ) );
  6824. addMethodChaining( 'renderOutput', renderOutput );
  6825. class DebugNode extends TempNode {
  6826. static get type() {
  6827. return 'DebugNode';
  6828. }
  6829. constructor( node, callback = null ) {
  6830. super();
  6831. this.node = node;
  6832. this.callback = callback;
  6833. }
  6834. getNodeType( builder ) {
  6835. return this.node.getNodeType( builder );
  6836. }
  6837. setup( builder ) {
  6838. return this.node.build( builder );
  6839. }
  6840. analyze( builder ) {
  6841. return this.node.build( builder );
  6842. }
  6843. generate( builder ) {
  6844. const callback = this.callback;
  6845. const snippet = this.node.build( builder );
  6846. const title = '--- TSL debug - ' + builder.shaderStage + ' shader ---';
  6847. const border = '-'.repeat( title.length );
  6848. let code = '';
  6849. code += '// #' + title + '#\n';
  6850. code += builder.flow.code.replace( /^\t/mg, '' ) + '\n';
  6851. code += '/* ... */ ' + snippet + ' /* ... */\n';
  6852. code += '// #' + border + '#\n';
  6853. if ( callback !== null ) {
  6854. callback( builder, code );
  6855. } else {
  6856. console.log( code );
  6857. }
  6858. return snippet;
  6859. }
  6860. }
  6861. /**
  6862. * TSL function for creating a debug node.
  6863. *
  6864. * @tsl
  6865. * @function
  6866. * @param {Node} node - The node to debug.
  6867. * @param {?Function} [callback=null] - Optional callback function to handle the debug output.
  6868. * @returns {DebugNode}
  6869. */
  6870. const debug = ( node, callback = null ) => nodeObject( new DebugNode( nodeObject( node ), callback ) );
  6871. addMethodChaining( 'debug', debug );
  6872. // Non-PURE exports list, side-effects are required here.
  6873. // TSL Base Syntax
  6874. function addNodeElement( name/*, nodeElement*/ ) {
  6875. console.warn( 'THREE.TSL: AddNodeElement has been removed in favor of tree-shaking. Trying add', name );
  6876. }
  6877. /**
  6878. * Base class for representing shader attributes as nodes.
  6879. *
  6880. * @augments Node
  6881. */
  6882. class AttributeNode extends Node {
  6883. static get type() {
  6884. return 'AttributeNode';
  6885. }
  6886. /**
  6887. * Constructs a new attribute node.
  6888. *
  6889. * @param {string} attributeName - The name of the attribute.
  6890. * @param {?string} nodeType - The node type.
  6891. */
  6892. constructor( attributeName, nodeType = null ) {
  6893. super( nodeType );
  6894. /**
  6895. * `AttributeNode` sets this property to `true` by default.
  6896. *
  6897. * @type {boolean}
  6898. * @default true
  6899. */
  6900. this.global = true;
  6901. this._attributeName = attributeName;
  6902. }
  6903. getHash( builder ) {
  6904. return this.getAttributeName( builder );
  6905. }
  6906. getNodeType( builder ) {
  6907. let nodeType = this.nodeType;
  6908. if ( nodeType === null ) {
  6909. const attributeName = this.getAttributeName( builder );
  6910. if ( builder.hasGeometryAttribute( attributeName ) ) {
  6911. const attribute = builder.geometry.getAttribute( attributeName );
  6912. nodeType = builder.getTypeFromAttribute( attribute );
  6913. } else {
  6914. nodeType = 'float';
  6915. }
  6916. }
  6917. return nodeType;
  6918. }
  6919. /**
  6920. * Sets the attribute name to the given value. The method can be
  6921. * overwritten in derived classes if the final name must be computed
  6922. * analytically.
  6923. *
  6924. * @param {string} attributeName - The name of the attribute.
  6925. * @return {AttributeNode} A reference to this node.
  6926. */
  6927. setAttributeName( attributeName ) {
  6928. this._attributeName = attributeName;
  6929. return this;
  6930. }
  6931. /**
  6932. * Returns the attribute name of this node. The method can be
  6933. * overwritten in derived classes if the final name must be computed
  6934. * analytically.
  6935. *
  6936. * @param {NodeBuilder} builder - The current node builder.
  6937. * @return {string} The attribute name.
  6938. */
  6939. getAttributeName( /*builder*/ ) {
  6940. return this._attributeName;
  6941. }
  6942. generate( builder ) {
  6943. const attributeName = this.getAttributeName( builder );
  6944. const nodeType = this.getNodeType( builder );
  6945. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  6946. if ( geometryAttribute === true ) {
  6947. const attribute = builder.geometry.getAttribute( attributeName );
  6948. const attributeType = builder.getTypeFromAttribute( attribute );
  6949. const nodeAttribute = builder.getAttribute( attributeName, attributeType );
  6950. if ( builder.shaderStage === 'vertex' ) {
  6951. return builder.format( nodeAttribute.name, attributeType, nodeType );
  6952. } else {
  6953. const nodeVarying = varying( this );
  6954. return nodeVarying.build( builder, nodeType );
  6955. }
  6956. } else {
  6957. console.warn( `AttributeNode: Vertex attribute "${ attributeName }" not found on geometry.` );
  6958. return builder.generateConst( nodeType );
  6959. }
  6960. }
  6961. serialize( data ) {
  6962. super.serialize( data );
  6963. data.global = this.global;
  6964. data._attributeName = this._attributeName;
  6965. }
  6966. deserialize( data ) {
  6967. super.deserialize( data );
  6968. this.global = data.global;
  6969. this._attributeName = data._attributeName;
  6970. }
  6971. }
  6972. /**
  6973. * TSL function for creating an attribute node.
  6974. *
  6975. * @tsl
  6976. * @function
  6977. * @param {string} name - The name of the attribute.
  6978. * @param {?string} [nodeType=null] - The node type.
  6979. * @returns {AttributeNode}
  6980. */
  6981. const attribute = ( name, nodeType = null ) => nodeObject( new AttributeNode( name, nodeType ) );
  6982. /**
  6983. * TSL function for creating an uv attribute node with the given index.
  6984. *
  6985. * @tsl
  6986. * @function
  6987. * @param {number} [index=0] - The uv index.
  6988. * @return {AttributeNode<vec2>} The uv attribute node.
  6989. */
  6990. const uv = ( index = 0 ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' );
  6991. /**
  6992. * A node that represents the dimensions of a texture. The texture size is
  6993. * retrieved in the shader via built-in shader functions like `textureDimensions()`
  6994. * or `textureSize()`.
  6995. *
  6996. * @augments Node
  6997. */
  6998. class TextureSizeNode extends Node {
  6999. static get type() {
  7000. return 'TextureSizeNode';
  7001. }
  7002. /**
  7003. * Constructs a new texture size node.
  7004. *
  7005. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  7006. * @param {?Node<int>} [levelNode=null] - A level node which defines the requested mip.
  7007. */
  7008. constructor( textureNode, levelNode = null ) {
  7009. super( 'uvec2' );
  7010. /**
  7011. * This flag can be used for type testing.
  7012. *
  7013. * @type {boolean}
  7014. * @readonly
  7015. * @default true
  7016. */
  7017. this.isTextureSizeNode = true;
  7018. /**
  7019. * A texture node which size should be retrieved.
  7020. *
  7021. * @type {TextureNode}
  7022. */
  7023. this.textureNode = textureNode;
  7024. /**
  7025. * A level node which defines the requested mip.
  7026. *
  7027. * @type {Node<int>}
  7028. * @default null
  7029. */
  7030. this.levelNode = levelNode;
  7031. }
  7032. generate( builder, output ) {
  7033. const textureProperty = this.textureNode.build( builder, 'property' );
  7034. const level = this.levelNode === null ? '0' : this.levelNode.build( builder, 'int' );
  7035. return builder.format( `${ builder.getMethod( 'textureDimensions' ) }( ${ textureProperty }, ${ level } )`, this.getNodeType( builder ), output );
  7036. }
  7037. }
  7038. /**
  7039. * TSL function for creating a texture size node.
  7040. *
  7041. * @tsl
  7042. * @function
  7043. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  7044. * @param {?Node<int>} [levelNode=null] - A level node which defines the requested mip.
  7045. * @returns {TextureSizeNode}
  7046. */
  7047. const textureSize = /*@__PURE__*/ nodeProxy( TextureSizeNode ).setParameterLength( 1, 2 );
  7048. /**
  7049. * A special type of uniform node that computes the
  7050. * maximum mipmap level for a given texture node.
  7051. *
  7052. * ```js
  7053. * const level = maxMipLevel( textureNode );
  7054. * ```
  7055. *
  7056. * @augments UniformNode
  7057. */
  7058. class MaxMipLevelNode extends UniformNode {
  7059. static get type() {
  7060. return 'MaxMipLevelNode';
  7061. }
  7062. /**
  7063. * Constructs a new max mip level node.
  7064. *
  7065. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  7066. */
  7067. constructor( textureNode ) {
  7068. super( 0 );
  7069. /**
  7070. * The texture node to compute the max mip level for.
  7071. *
  7072. * @private
  7073. * @type {TextureNode}
  7074. */
  7075. this._textureNode = textureNode;
  7076. /**
  7077. * The `updateType` is set to `NodeUpdateType.FRAME` since the node updates
  7078. * the texture once per frame in its {@link MaxMipLevelNode#update} method.
  7079. *
  7080. * @type {string}
  7081. * @default 'frame'
  7082. */
  7083. this.updateType = NodeUpdateType.FRAME;
  7084. }
  7085. /**
  7086. * The texture node to compute the max mip level for.
  7087. *
  7088. * @readonly
  7089. * @type {TextureNode}
  7090. */
  7091. get textureNode() {
  7092. return this._textureNode;
  7093. }
  7094. /**
  7095. * The texture.
  7096. *
  7097. * @readonly
  7098. * @type {Texture}
  7099. */
  7100. get texture() {
  7101. return this._textureNode.value;
  7102. }
  7103. update() {
  7104. const texture = this.texture;
  7105. const images = texture.images;
  7106. const image = ( images && images.length > 0 ) ? ( ( images[ 0 ] && images[ 0 ].image ) || images[ 0 ] ) : texture.image;
  7107. if ( image && image.width !== undefined ) {
  7108. const { width, height } = image;
  7109. this.value = Math.log2( Math.max( width, height ) );
  7110. }
  7111. }
  7112. }
  7113. /**
  7114. * TSL function for creating a max mip level node.
  7115. *
  7116. * @tsl
  7117. * @function
  7118. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  7119. * @returns {MaxMipLevelNode}
  7120. */
  7121. const maxMipLevel = /*@__PURE__*/ nodeProxy( MaxMipLevelNode ).setParameterLength( 1 );
  7122. const EmptyTexture$1 = /*@__PURE__*/ new Texture();
  7123. /**
  7124. * This type of uniform node represents a 2D texture.
  7125. *
  7126. * @augments UniformNode
  7127. */
  7128. class TextureNode extends UniformNode {
  7129. static get type() {
  7130. return 'TextureNode';
  7131. }
  7132. /**
  7133. * Constructs a new texture node.
  7134. *
  7135. * @param {Texture} [value=EmptyTexture] - The texture.
  7136. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  7137. * @param {?Node<int>} [levelNode=null] - The level node.
  7138. * @param {?Node<float>} [biasNode=null] - The bias node.
  7139. */
  7140. constructor( value = EmptyTexture$1, uvNode = null, levelNode = null, biasNode = null ) {
  7141. super( value );
  7142. /**
  7143. * This flag can be used for type testing.
  7144. *
  7145. * @type {boolean}
  7146. * @readonly
  7147. * @default true
  7148. */
  7149. this.isTextureNode = true;
  7150. /**
  7151. * Represents the texture coordinates.
  7152. *
  7153. * @type {?Node<vec2|vec3>}
  7154. * @default null
  7155. */
  7156. this.uvNode = uvNode;
  7157. /**
  7158. * Represents the mip level that should be selected.
  7159. *
  7160. * @type {?Node<int>}
  7161. * @default null
  7162. */
  7163. this.levelNode = levelNode;
  7164. /**
  7165. * Represents the bias to be applied during level-of-detail computation.
  7166. *
  7167. * @type {?Node<float>}
  7168. * @default null
  7169. */
  7170. this.biasNode = biasNode;
  7171. /**
  7172. * Represents a reference value a texture sample is compared to.
  7173. *
  7174. * @type {?Node<float>}
  7175. * @default null
  7176. */
  7177. this.compareNode = null;
  7178. /**
  7179. * When using texture arrays, the depth node defines the layer to select.
  7180. *
  7181. * @type {?Node<int>}
  7182. * @default null
  7183. */
  7184. this.depthNode = null;
  7185. /**
  7186. * When defined, a texture is sampled using explicit gradients.
  7187. *
  7188. * @type {?Array<Node<vec2>>}
  7189. * @default null
  7190. */
  7191. this.gradNode = null;
  7192. /**
  7193. * Whether texture values should be sampled or fetched.
  7194. *
  7195. * @type {boolean}
  7196. * @default true
  7197. */
  7198. this.sampler = true;
  7199. /**
  7200. * Whether the uv transformation matrix should be
  7201. * automatically updated or not. Use `setUpdateMatrix()`
  7202. * if you want to change the value of the property.
  7203. *
  7204. * @type {boolean}
  7205. * @default false
  7206. */
  7207. this.updateMatrix = false;
  7208. /**
  7209. * By default the `update()` method is not executed. `setUpdateMatrix()`
  7210. * sets the value to `frame` when the uv transformation matrix should
  7211. * automatically be updated.
  7212. *
  7213. * @type {string}
  7214. * @default 'none'
  7215. */
  7216. this.updateType = NodeUpdateType.NONE;
  7217. /**
  7218. * The reference node.
  7219. *
  7220. * @type {?Node}
  7221. * @default null
  7222. */
  7223. this.referenceNode = null;
  7224. /**
  7225. * The texture value is stored in a private property.
  7226. *
  7227. * @private
  7228. * @type {Texture}
  7229. */
  7230. this._value = value;
  7231. /**
  7232. * The uniform node that represents the uv transformation matrix.
  7233. *
  7234. * @private
  7235. * @type {?UniformNode<mat3>}
  7236. */
  7237. this._matrixUniform = null;
  7238. this.setUpdateMatrix( uvNode === null );
  7239. }
  7240. set value( value ) {
  7241. if ( this.referenceNode ) {
  7242. this.referenceNode.value = value;
  7243. } else {
  7244. this._value = value;
  7245. }
  7246. }
  7247. /**
  7248. * The texture value.
  7249. *
  7250. * @type {Texture}
  7251. */
  7252. get value() {
  7253. return this.referenceNode ? this.referenceNode.value : this._value;
  7254. }
  7255. /**
  7256. * Overwritten since the uniform hash is defined by the texture's UUID.
  7257. *
  7258. * @param {NodeBuilder} builder - The current node builder.
  7259. * @return {string} The uniform hash.
  7260. */
  7261. getUniformHash( /*builder*/ ) {
  7262. return this.value.uuid;
  7263. }
  7264. /**
  7265. * Overwritten since the node type is inferred from the texture type.
  7266. *
  7267. * @param {NodeBuilder} builder - The current node builder.
  7268. * @return {string} The node type.
  7269. */
  7270. getNodeType( /*builder*/ ) {
  7271. if ( this.value.isDepthTexture === true ) return 'float';
  7272. if ( this.value.type === UnsignedIntType ) {
  7273. return 'uvec4';
  7274. } else if ( this.value.type === IntType ) {
  7275. return 'ivec4';
  7276. }
  7277. return 'vec4';
  7278. }
  7279. /**
  7280. * Overwrites the default implementation to return a fixed value `'texture'`.
  7281. *
  7282. * @param {NodeBuilder} builder - The current node builder.
  7283. * @return {string} The input type.
  7284. */
  7285. getInputType( /*builder*/ ) {
  7286. return 'texture';
  7287. }
  7288. /**
  7289. * Returns a default uvs based on the current texture's channel.
  7290. *
  7291. * @return {AttributeNode<vec2>} The default uvs.
  7292. */
  7293. getDefaultUV() {
  7294. return uv( this.value.channel );
  7295. }
  7296. /**
  7297. * Overwritten to always return the texture reference of the node.
  7298. *
  7299. * @param {any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  7300. * @return {Texture} The texture reference.
  7301. */
  7302. updateReference( /*state*/ ) {
  7303. return this.value;
  7304. }
  7305. /**
  7306. * Transforms the given uv node with the texture transformation matrix.
  7307. *
  7308. * @param {Node} uvNode - The uv node to transform.
  7309. * @return {Node} The transformed uv node.
  7310. */
  7311. getTransformedUV( uvNode ) {
  7312. if ( this._matrixUniform === null ) this._matrixUniform = uniform( this.value.matrix );
  7313. return this._matrixUniform.mul( vec3( uvNode, 1 ) ).xy;
  7314. }
  7315. /**
  7316. * Defines whether the uv transformation matrix should automatically be updated or not.
  7317. *
  7318. * @param {boolean} value - The update toggle.
  7319. * @return {TextureNode} A reference to this node.
  7320. */
  7321. setUpdateMatrix( value ) {
  7322. this.updateMatrix = value;
  7323. this.updateType = value ? NodeUpdateType.OBJECT : NodeUpdateType.NONE;
  7324. return this;
  7325. }
  7326. /**
  7327. * Setups the uv node. Depending on the backend as well as texture's image and type, it might be necessary
  7328. * to modify the uv node for correct sampling.
  7329. *
  7330. * @param {NodeBuilder} builder - The current node builder.
  7331. * @param {Node} uvNode - The uv node to setup.
  7332. * @return {Node} The updated uv node.
  7333. */
  7334. setupUV( builder, uvNode ) {
  7335. const texture = this.value;
  7336. if ( builder.isFlipY() && ( ( texture.image instanceof ImageBitmap && texture.flipY === true ) || texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true || texture.isDepthTexture === true ) ) {
  7337. if ( this.sampler ) {
  7338. uvNode = uvNode.flipY();
  7339. } else {
  7340. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  7341. }
  7342. }
  7343. return uvNode;
  7344. }
  7345. /**
  7346. * Setups texture node by preparing the internal nodes for code generation.
  7347. *
  7348. * @param {NodeBuilder} builder - The current node builder.
  7349. */
  7350. setup( builder ) {
  7351. const properties = builder.getNodeProperties( this );
  7352. properties.referenceNode = this.referenceNode;
  7353. //
  7354. const texture = this.value;
  7355. if ( ! texture || texture.isTexture !== true ) {
  7356. throw new Error( 'THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().' );
  7357. }
  7358. //
  7359. let uvNode = this.uvNode;
  7360. if ( ( uvNode === null || builder.context.forceUVContext === true ) && builder.context.getUV ) {
  7361. uvNode = builder.context.getUV( this, builder );
  7362. }
  7363. if ( ! uvNode ) uvNode = this.getDefaultUV();
  7364. if ( this.updateMatrix === true ) {
  7365. uvNode = this.getTransformedUV( uvNode );
  7366. }
  7367. uvNode = this.setupUV( builder, uvNode );
  7368. //
  7369. let levelNode = this.levelNode;
  7370. if ( levelNode === null && builder.context.getTextureLevel ) {
  7371. levelNode = builder.context.getTextureLevel( this );
  7372. }
  7373. //
  7374. properties.uvNode = uvNode;
  7375. properties.levelNode = levelNode;
  7376. properties.biasNode = this.biasNode;
  7377. properties.compareNode = this.compareNode;
  7378. properties.gradNode = this.gradNode;
  7379. properties.depthNode = this.depthNode;
  7380. }
  7381. /**
  7382. * Generates the uv code snippet.
  7383. *
  7384. * @param {NodeBuilder} builder - The current node builder.
  7385. * @param {Node} uvNode - The uv node to generate code for.
  7386. * @return {string} The generated code snippet.
  7387. */
  7388. generateUV( builder, uvNode ) {
  7389. return uvNode.build( builder, this.sampler === true ? 'vec2' : 'ivec2' );
  7390. }
  7391. /**
  7392. * Generates the snippet for the texture sampling.
  7393. *
  7394. * @param {NodeBuilder} builder - The current node builder.
  7395. * @param {string} textureProperty - The texture property.
  7396. * @param {string} uvSnippet - The uv snippet.
  7397. * @param {?string} levelSnippet - The level snippet.
  7398. * @param {?string} biasSnippet - The bias snippet.
  7399. * @param {?string} depthSnippet - The depth snippet.
  7400. * @param {?string} compareSnippet - The compare snippet.
  7401. * @param {?Array<string>} gradSnippet - The grad snippet.
  7402. * @return {string} The generated code snippet.
  7403. */
  7404. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet ) {
  7405. const texture = this.value;
  7406. let snippet;
  7407. if ( levelSnippet ) {
  7408. snippet = builder.generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet );
  7409. } else if ( biasSnippet ) {
  7410. snippet = builder.generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet );
  7411. } else if ( gradSnippet ) {
  7412. snippet = builder.generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet );
  7413. } else if ( compareSnippet ) {
  7414. snippet = builder.generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet );
  7415. } else if ( this.sampler === false ) {
  7416. snippet = builder.generateTextureLoad( texture, textureProperty, uvSnippet, depthSnippet );
  7417. } else {
  7418. snippet = builder.generateTexture( texture, textureProperty, uvSnippet, depthSnippet );
  7419. }
  7420. return snippet;
  7421. }
  7422. /**
  7423. * Generates the code snippet of the texture node.
  7424. *
  7425. * @param {NodeBuilder} builder - The current node builder.
  7426. * @param {string} output - The current output.
  7427. * @return {string} The generated code snippet.
  7428. */
  7429. generate( builder, output ) {
  7430. const texture = this.value;
  7431. const properties = builder.getNodeProperties( this );
  7432. const textureProperty = super.generate( builder, 'property' );
  7433. if ( /^sampler/.test( output ) ) {
  7434. return textureProperty + '_sampler';
  7435. } else if ( builder.isReference( output ) ) {
  7436. return textureProperty;
  7437. } else {
  7438. const nodeData = builder.getDataFromNode( this );
  7439. let propertyName = nodeData.propertyName;
  7440. if ( propertyName === undefined ) {
  7441. const { uvNode, levelNode, biasNode, compareNode, depthNode, gradNode } = properties;
  7442. const uvSnippet = this.generateUV( builder, uvNode );
  7443. const levelSnippet = levelNode ? levelNode.build( builder, 'float' ) : null;
  7444. const biasSnippet = biasNode ? biasNode.build( builder, 'float' ) : null;
  7445. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  7446. const compareSnippet = compareNode ? compareNode.build( builder, 'float' ) : null;
  7447. const gradSnippet = gradNode ? [ gradNode[ 0 ].build( builder, 'vec2' ), gradNode[ 1 ].build( builder, 'vec2' ) ] : null;
  7448. const nodeVar = builder.getVarFromNode( this );
  7449. propertyName = builder.getPropertyName( nodeVar );
  7450. const snippet = this.generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet );
  7451. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  7452. nodeData.snippet = snippet;
  7453. nodeData.propertyName = propertyName;
  7454. }
  7455. let snippet = propertyName;
  7456. const nodeType = this.getNodeType( builder );
  7457. if ( builder.needsToWorkingColorSpace( texture ) ) {
  7458. snippet = colorSpaceToWorking( expression( snippet, nodeType ), texture.colorSpace ).setup( builder ).build( builder, nodeType );
  7459. }
  7460. return builder.format( snippet, nodeType, output );
  7461. }
  7462. }
  7463. /**
  7464. * Sets the sampler value.
  7465. *
  7466. * @param {boolean} value - The sampler value to set.
  7467. * @return {TextureNode} A reference to this texture node.
  7468. */
  7469. setSampler( value ) {
  7470. this.sampler = value;
  7471. return this;
  7472. }
  7473. /**
  7474. * Returns the sampler value.
  7475. *
  7476. * @return {boolean} The sampler value.
  7477. */
  7478. getSampler() {
  7479. return this.sampler;
  7480. }
  7481. // @TODO: Move to TSL
  7482. /**
  7483. * @function
  7484. * @deprecated since r172. Use {@link TextureNode#sample} instead.
  7485. *
  7486. * @param {Node} uvNode - The uv node.
  7487. * @return {TextureNode} A texture node representing the texture sample.
  7488. */
  7489. uv( uvNode ) { // @deprecated, r172
  7490. console.warn( 'THREE.TextureNode: .uv() has been renamed. Use .sample() instead.' );
  7491. return this.sample( uvNode );
  7492. }
  7493. /**
  7494. * Samples the texture with the given uv node.
  7495. *
  7496. * @param {Node} uvNode - The uv node.
  7497. * @return {TextureNode} A texture node representing the texture sample.
  7498. */
  7499. sample( uvNode ) {
  7500. const textureNode = this.clone();
  7501. textureNode.uvNode = nodeObject( uvNode );
  7502. textureNode.referenceNode = this.getSelf();
  7503. return nodeObject( textureNode );
  7504. }
  7505. /**
  7506. * Samples a blurred version of the texture by defining an internal bias.
  7507. *
  7508. * @param {Node<float>} amountNode - How blurred the texture should be.
  7509. * @return {TextureNode} A texture node representing the texture sample.
  7510. */
  7511. blur( amountNode ) {
  7512. const textureNode = this.clone();
  7513. textureNode.biasNode = nodeObject( amountNode ).mul( maxMipLevel( textureNode ) );
  7514. textureNode.referenceNode = this.getSelf();
  7515. const map = textureNode.value;
  7516. if ( textureNode.generateMipmaps === false && ( map && map.generateMipmaps === false || map.minFilter === NearestFilter || map.magFilter === NearestFilter ) ) {
  7517. console.warn( 'THREE.TSL: texture().blur() requires mipmaps and sampling. Use .generateMipmaps=true and .minFilter/.magFilter=THREE.LinearFilter in the Texture.' );
  7518. textureNode.biasNode = null;
  7519. }
  7520. return nodeObject( textureNode );
  7521. }
  7522. /**
  7523. * Samples a specific mip of the texture.
  7524. *
  7525. * @param {Node<int>} levelNode - The mip level to sample.
  7526. * @return {TextureNode} A texture node representing the texture sample.
  7527. */
  7528. level( levelNode ) {
  7529. const textureNode = this.clone();
  7530. textureNode.levelNode = nodeObject( levelNode );
  7531. textureNode.referenceNode = this.getSelf();
  7532. return nodeObject( textureNode );
  7533. }
  7534. /**
  7535. * Returns the texture size of the requested level.
  7536. *
  7537. * @param {Node<int>} levelNode - The level to compute the size for.
  7538. * @return {TextureSizeNode} The texture size.
  7539. */
  7540. size( levelNode ) {
  7541. return textureSize( this, levelNode );
  7542. }
  7543. /**
  7544. * Samples the texture with the given bias.
  7545. *
  7546. * @param {Node<float>} biasNode - The bias node.
  7547. * @return {TextureNode} A texture node representing the texture sample.
  7548. */
  7549. bias( biasNode ) {
  7550. const textureNode = this.clone();
  7551. textureNode.biasNode = nodeObject( biasNode );
  7552. textureNode.referenceNode = this.getSelf();
  7553. return nodeObject( textureNode );
  7554. }
  7555. /**
  7556. * Samples the texture by executing a compare operation.
  7557. *
  7558. * @param {Node<float>} compareNode - The node that defines the compare value.
  7559. * @return {TextureNode} A texture node representing the texture sample.
  7560. */
  7561. compare( compareNode ) {
  7562. const textureNode = this.clone();
  7563. textureNode.compareNode = nodeObject( compareNode );
  7564. textureNode.referenceNode = this.getSelf();
  7565. return nodeObject( textureNode );
  7566. }
  7567. /**
  7568. * Samples the texture using an explicit gradient.
  7569. *
  7570. * @param {Node<vec2>} gradNodeX - The gradX node.
  7571. * @param {Node<vec2>} gradNodeY - The gradY node.
  7572. * @return {TextureNode} A texture node representing the texture sample.
  7573. */
  7574. grad( gradNodeX, gradNodeY ) {
  7575. const textureNode = this.clone();
  7576. textureNode.gradNode = [ nodeObject( gradNodeX ), nodeObject( gradNodeY ) ];
  7577. textureNode.referenceNode = this.getSelf();
  7578. return nodeObject( textureNode );
  7579. }
  7580. /**
  7581. * Samples the texture by defining a depth node.
  7582. *
  7583. * @param {Node<int>} depthNode - The depth node.
  7584. * @return {TextureNode} A texture node representing the texture sample.
  7585. */
  7586. depth( depthNode ) {
  7587. const textureNode = this.clone();
  7588. textureNode.depthNode = nodeObject( depthNode );
  7589. textureNode.referenceNode = this.getSelf();
  7590. return nodeObject( textureNode );
  7591. }
  7592. // --
  7593. serialize( data ) {
  7594. super.serialize( data );
  7595. data.value = this.value.toJSON( data.meta ).uuid;
  7596. data.sampler = this.sampler;
  7597. data.updateMatrix = this.updateMatrix;
  7598. data.updateType = this.updateType;
  7599. }
  7600. deserialize( data ) {
  7601. super.deserialize( data );
  7602. this.value = data.meta.textures[ data.value ];
  7603. this.sampler = data.sampler;
  7604. this.updateMatrix = data.updateMatrix;
  7605. this.updateType = data.updateType;
  7606. }
  7607. /**
  7608. * The update is used to implement the update of the uv transformation matrix.
  7609. */
  7610. update() {
  7611. const texture = this.value;
  7612. const matrixUniform = this._matrixUniform;
  7613. if ( matrixUniform !== null ) matrixUniform.value = texture.matrix;
  7614. if ( texture.matrixAutoUpdate === true ) {
  7615. texture.updateMatrix();
  7616. }
  7617. }
  7618. /**
  7619. * Clones the texture node.
  7620. *
  7621. * @return {TextureNode} The cloned texture node.
  7622. */
  7623. clone() {
  7624. const newNode = new this.constructor( this.value, this.uvNode, this.levelNode, this.biasNode );
  7625. newNode.sampler = this.sampler;
  7626. newNode.depthNode = this.depthNode;
  7627. newNode.compareNode = this.compareNode;
  7628. newNode.gradNode = this.gradNode;
  7629. return newNode;
  7630. }
  7631. }
  7632. /**
  7633. * TSL function for creating a texture node.
  7634. *
  7635. * @tsl
  7636. * @function
  7637. * @param {?Texture} value - The texture.
  7638. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  7639. * @param {?Node<int>} [levelNode=null] - The level node.
  7640. * @param {?Node<float>} [biasNode=null] - The bias node.
  7641. * @returns {TextureNode}
  7642. */
  7643. const textureBase = /*@__PURE__*/ nodeProxy( TextureNode ).setParameterLength( 1, 4 ).setName( 'texture' );
  7644. /**
  7645. * TSL function for creating a texture node or sample a texture node already existing.
  7646. *
  7647. * @tsl
  7648. * @function
  7649. * @param {?Texture|TextureNode} [value=EmptyTexture] - The texture.
  7650. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  7651. * @param {?Node<int>} [levelNode=null] - The level node.
  7652. * @param {?Node<float>} [biasNode=null] - The bias node.
  7653. * @returns {TextureNode}
  7654. */
  7655. const texture = ( value = EmptyTexture$1, uvNode = null, levelNode = null, biasNode = null ) => {
  7656. let textureNode;
  7657. if ( value && value.isTextureNode === true ) {
  7658. textureNode = nodeObject( value.clone() );
  7659. textureNode.referenceNode = value.getSelf(); // Ensure the reference is set to the original node
  7660. if ( uvNode !== null ) textureNode.uvNode = nodeObject( uvNode );
  7661. if ( levelNode !== null ) textureNode.levelNode = nodeObject( levelNode );
  7662. if ( biasNode !== null ) textureNode.biasNode = nodeObject( biasNode );
  7663. } else {
  7664. textureNode = textureBase( value, uvNode, levelNode, biasNode );
  7665. }
  7666. return textureNode;
  7667. };
  7668. /**
  7669. * TSL function for creating a uniform texture node.
  7670. *
  7671. * @tsl
  7672. * @function
  7673. * @param {?Texture} value - The texture.
  7674. * @returns {TextureNode}
  7675. */
  7676. const uniformTexture = ( value = EmptyTexture$1 ) => texture( value );
  7677. /**
  7678. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  7679. *
  7680. * @tsl
  7681. * @function
  7682. * @param {?Texture|TextureNode} [value=EmptyTexture] - The texture.
  7683. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  7684. * @param {?Node<int>} [levelNode=null] - The level node.
  7685. * @param {?Node<float>} [biasNode=null] - The bias node.
  7686. * @returns {TextureNode}
  7687. */
  7688. const textureLoad = ( ...params ) => texture( ...params ).setSampler( false );
  7689. //export const textureLevel = ( value, uv, level ) => texture( value, uv ).level( level );
  7690. /**
  7691. * Converts a texture or texture node to a sampler.
  7692. *
  7693. * @tsl
  7694. * @function
  7695. * @param {TextureNode|Texture} value - The texture or texture node to convert.
  7696. * @returns {Node}
  7697. */
  7698. const sampler = ( value ) => ( value.isNode === true ? value : texture( value ) ).convert( 'sampler' );
  7699. /**
  7700. * Converts a texture or texture node to a sampler comparison.
  7701. *
  7702. * @tsl
  7703. * @function
  7704. * @param {TextureNode|Texture} value - The texture or texture node to convert.
  7705. * @returns {Node}
  7706. */
  7707. const samplerComparison = ( value ) => ( value.isNode === true ? value : texture( value ) ).convert( 'samplerComparison' );
  7708. /**
  7709. * A special type of uniform node which represents array-like data
  7710. * as uniform buffers. The access usually happens via `element()`
  7711. * which returns an instance of {@link ArrayElementNode}. For example:
  7712. *
  7713. * ```js
  7714. * const bufferNode = buffer( array, 'mat4', count );
  7715. * const matrixNode = bufferNode.element( index ); // access a matrix from the buffer
  7716. * ```
  7717. * In general, it is recommended to use the more managed {@link UniformArrayNode}
  7718. * since it handles more input types and automatically cares about buffer paddings.
  7719. *
  7720. * @augments UniformNode
  7721. */
  7722. class BufferNode extends UniformNode {
  7723. static get type() {
  7724. return 'BufferNode';
  7725. }
  7726. /**
  7727. * Constructs a new buffer node.
  7728. *
  7729. * @param {Array<number>} value - Array-like buffer data.
  7730. * @param {string} bufferType - The data type of the buffer.
  7731. * @param {number} [bufferCount=0] - The count of buffer elements.
  7732. */
  7733. constructor( value, bufferType, bufferCount = 0 ) {
  7734. super( value, bufferType );
  7735. /**
  7736. * This flag can be used for type testing.
  7737. *
  7738. * @type {boolean}
  7739. * @readonly
  7740. * @default true
  7741. */
  7742. this.isBufferNode = true;
  7743. /**
  7744. * The data type of the buffer.
  7745. *
  7746. * @type {string}
  7747. */
  7748. this.bufferType = bufferType;
  7749. /**
  7750. * The uniform node that holds the value of the reference node.
  7751. *
  7752. * @type {number}
  7753. * @default 0
  7754. */
  7755. this.bufferCount = bufferCount;
  7756. }
  7757. /**
  7758. * The data type of the buffer elements.
  7759. *
  7760. * @param {NodeBuilder} builder - The current node builder.
  7761. * @return {string} The element type.
  7762. */
  7763. getElementType( builder ) {
  7764. return this.getNodeType( builder );
  7765. }
  7766. /**
  7767. * Overwrites the default implementation to return a fixed value `'buffer'`.
  7768. *
  7769. * @param {NodeBuilder} builder - The current node builder.
  7770. * @return {string} The input type.
  7771. */
  7772. getInputType( /*builder*/ ) {
  7773. return 'buffer';
  7774. }
  7775. }
  7776. /**
  7777. * TSL function for creating a buffer node.
  7778. *
  7779. * @tsl
  7780. * @function
  7781. * @param {Array} value - Array-like buffer data.
  7782. * @param {string} type - The data type of a buffer element.
  7783. * @param {number} count - The count of buffer elements.
  7784. * @returns {BufferNode}
  7785. */
  7786. const buffer = ( value, type, count ) => nodeObject( new BufferNode( value, type, count ) );
  7787. /**
  7788. * Represents the element access on uniform array nodes.
  7789. *
  7790. * @augments ArrayElementNode
  7791. */
  7792. class UniformArrayElementNode extends ArrayElementNode {
  7793. static get type() {
  7794. return 'UniformArrayElementNode';
  7795. }
  7796. /**
  7797. * Constructs a new buffer node.
  7798. *
  7799. * @param {UniformArrayNode} uniformArrayNode - The uniform array node to access.
  7800. * @param {IndexNode} indexNode - The index data that define the position of the accessed element in the array.
  7801. */
  7802. constructor( uniformArrayNode, indexNode ) {
  7803. super( uniformArrayNode, indexNode );
  7804. /**
  7805. * This flag can be used for type testing.
  7806. *
  7807. * @type {boolean}
  7808. * @readonly
  7809. * @default true
  7810. */
  7811. this.isArrayBufferElementNode = true;
  7812. }
  7813. generate( builder ) {
  7814. const snippet = super.generate( builder );
  7815. const type = this.getNodeType();
  7816. const paddedType = this.node.getPaddedType();
  7817. return builder.format( snippet, paddedType, type );
  7818. }
  7819. }
  7820. /**
  7821. * Similar to {@link BufferNode} this module represents array-like data as
  7822. * uniform buffers. Unlike {@link BufferNode}, it can handle more common
  7823. * data types in the array (e.g `three.js` primitives) and automatically
  7824. * manage buffer padding. It should be the first choice when working with
  7825. * uniforms buffers.
  7826. * ```js
  7827. * const tintColors = uniformArray( [
  7828. * new Color( 1, 0, 0 ),
  7829. * new Color( 0, 1, 0 ),
  7830. * new Color( 0, 0, 1 )
  7831. * ], 'color' );
  7832. *
  7833. * const redColor = tintColors.element( 0 );
  7834. *
  7835. * @augments BufferNode
  7836. */
  7837. class UniformArrayNode extends BufferNode {
  7838. static get type() {
  7839. return 'UniformArrayNode';
  7840. }
  7841. /**
  7842. * Constructs a new uniform array node.
  7843. *
  7844. * @param {Array<any>} value - Array holding the buffer data.
  7845. * @param {?string} [elementType=null] - The data type of a buffer element.
  7846. */
  7847. constructor( value, elementType = null ) {
  7848. super( null );
  7849. /**
  7850. * Array holding the buffer data. Unlike {@link BufferNode}, the array can
  7851. * hold number primitives as well as three.js objects like vectors, matrices
  7852. * or colors.
  7853. *
  7854. * @type {Array<any>}
  7855. */
  7856. this.array = value;
  7857. /**
  7858. * The data type of an array element.
  7859. *
  7860. * @type {string}
  7861. */
  7862. this.elementType = elementType === null ? getValueType( value[ 0 ] ) : elementType;
  7863. /**
  7864. * The padded type. Uniform buffers must conform to a certain buffer layout
  7865. * so a separate type is computed to ensure correct buffer size.
  7866. *
  7867. * @type {string}
  7868. */
  7869. this.paddedType = this.getPaddedType();
  7870. /**
  7871. * Overwritten since uniform array nodes are updated per render.
  7872. *
  7873. * @type {string}
  7874. * @default 'render'
  7875. */
  7876. this.updateType = NodeUpdateType.RENDER;
  7877. /**
  7878. * This flag can be used for type testing.
  7879. *
  7880. * @type {boolean}
  7881. * @readonly
  7882. * @default true
  7883. */
  7884. this.isArrayBufferNode = true;
  7885. }
  7886. /**
  7887. * This method is overwritten since the node type is inferred from the
  7888. * {@link UniformArrayNode#paddedType}.
  7889. *
  7890. * @param {NodeBuilder} builder - The current node builder.
  7891. * @return {string} The node type.
  7892. */
  7893. getNodeType( /*builder*/ ) {
  7894. return this.paddedType;
  7895. }
  7896. /**
  7897. * The data type of the array elements.
  7898. *
  7899. * @param {NodeBuilder} builder - The current node builder.
  7900. * @return {string} The element type.
  7901. */
  7902. getElementType() {
  7903. return this.elementType;
  7904. }
  7905. /**
  7906. * Returns the padded type based on the element type.
  7907. *
  7908. * @return {string} The padded type.
  7909. */
  7910. getPaddedType() {
  7911. const elementType = this.elementType;
  7912. let paddedType = 'vec4';
  7913. if ( elementType === 'mat2' ) {
  7914. paddedType = 'mat2';
  7915. } else if ( /mat/.test( elementType ) === true ) {
  7916. paddedType = 'mat4';
  7917. } else if ( elementType.charAt( 0 ) === 'i' ) {
  7918. paddedType = 'ivec4';
  7919. } else if ( elementType.charAt( 0 ) === 'u' ) {
  7920. paddedType = 'uvec4';
  7921. }
  7922. return paddedType;
  7923. }
  7924. /**
  7925. * The update makes sure to correctly transfer the data from the (complex) objects
  7926. * in the array to the internal, correctly padded value buffer.
  7927. *
  7928. * @param {NodeFrame} frame - A reference to the current node frame.
  7929. */
  7930. update( /*frame*/ ) {
  7931. const { array, value } = this;
  7932. const elementType = this.elementType;
  7933. if ( elementType === 'float' || elementType === 'int' || elementType === 'uint' ) {
  7934. for ( let i = 0; i < array.length; i ++ ) {
  7935. const index = i * 4;
  7936. value[ index ] = array[ i ];
  7937. }
  7938. } else if ( elementType === 'color' ) {
  7939. for ( let i = 0; i < array.length; i ++ ) {
  7940. const index = i * 4;
  7941. const vector = array[ i ];
  7942. value[ index ] = vector.r;
  7943. value[ index + 1 ] = vector.g;
  7944. value[ index + 2 ] = vector.b || 0;
  7945. //value[ index + 3 ] = vector.a || 0;
  7946. }
  7947. } else if ( elementType === 'mat2' ) {
  7948. for ( let i = 0; i < array.length; i ++ ) {
  7949. const index = i * 4;
  7950. const matrix = array[ i ];
  7951. value[ index ] = matrix.elements[ 0 ];
  7952. value[ index + 1 ] = matrix.elements[ 1 ];
  7953. value[ index + 2 ] = matrix.elements[ 2 ];
  7954. value[ index + 3 ] = matrix.elements[ 3 ];
  7955. }
  7956. } else if ( elementType === 'mat3' ) {
  7957. for ( let i = 0; i < array.length; i ++ ) {
  7958. const index = i * 16;
  7959. const matrix = array[ i ];
  7960. value[ index ] = matrix.elements[ 0 ];
  7961. value[ index + 1 ] = matrix.elements[ 1 ];
  7962. value[ index + 2 ] = matrix.elements[ 2 ];
  7963. value[ index + 4 ] = matrix.elements[ 3 ];
  7964. value[ index + 5 ] = matrix.elements[ 4 ];
  7965. value[ index + 6 ] = matrix.elements[ 5 ];
  7966. value[ index + 8 ] = matrix.elements[ 6 ];
  7967. value[ index + 9 ] = matrix.elements[ 7 ];
  7968. value[ index + 10 ] = matrix.elements[ 8 ];
  7969. value[ index + 15 ] = 1;
  7970. }
  7971. } else if ( elementType === 'mat4' ) {
  7972. for ( let i = 0; i < array.length; i ++ ) {
  7973. const index = i * 16;
  7974. const matrix = array[ i ];
  7975. for ( let i = 0; i < matrix.elements.length; i ++ ) {
  7976. value[ index + i ] = matrix.elements[ i ];
  7977. }
  7978. }
  7979. } else {
  7980. for ( let i = 0; i < array.length; i ++ ) {
  7981. const index = i * 4;
  7982. const vector = array[ i ];
  7983. value[ index ] = vector.x;
  7984. value[ index + 1 ] = vector.y;
  7985. value[ index + 2 ] = vector.z || 0;
  7986. value[ index + 3 ] = vector.w || 0;
  7987. }
  7988. }
  7989. }
  7990. /**
  7991. * Implement the value buffer creation based on the array data.
  7992. *
  7993. * @param {NodeBuilder} builder - A reference to the current node builder.
  7994. * @return {null}
  7995. */
  7996. setup( builder ) {
  7997. const length = this.array.length;
  7998. const elementType = this.elementType;
  7999. let arrayType = Float32Array;
  8000. const paddedType = this.paddedType;
  8001. const paddedElementLength = builder.getTypeLength( paddedType );
  8002. if ( elementType.charAt( 0 ) === 'i' ) arrayType = Int32Array;
  8003. if ( elementType.charAt( 0 ) === 'u' ) arrayType = Uint32Array;
  8004. this.value = new arrayType( length * paddedElementLength );
  8005. this.bufferCount = length;
  8006. this.bufferType = paddedType;
  8007. return super.setup( builder );
  8008. }
  8009. /**
  8010. * Overwrites the default `element()` method to provide element access
  8011. * based on {@link UniformArrayNode}.
  8012. *
  8013. * @param {IndexNode} indexNode - The index node.
  8014. * @return {UniformArrayElementNode}
  8015. */
  8016. element( indexNode ) {
  8017. return nodeObject( new UniformArrayElementNode( this, nodeObject( indexNode ) ) );
  8018. }
  8019. }
  8020. /**
  8021. * TSL function for creating an uniform array node.
  8022. *
  8023. * @tsl
  8024. * @function
  8025. * @param {Array<any>} values - Array-like data.
  8026. * @param {?string} [nodeType] - The data type of the array elements.
  8027. * @returns {UniformArrayNode}
  8028. */
  8029. const uniformArray = ( values, nodeType ) => nodeObject( new UniformArrayNode( values, nodeType ) );
  8030. /**
  8031. * @tsl
  8032. * @function
  8033. * @deprecated since r168. Use {@link uniformArray} instead.
  8034. *
  8035. * @param {Array<any>} values - Array-like data.
  8036. * @param {string} nodeType - The data type of the array elements.
  8037. * @returns {UniformArrayNode}
  8038. */
  8039. const uniforms = ( values, nodeType ) => { // @deprecated, r168
  8040. console.warn( 'THREE.TSL: uniforms() has been renamed to uniformArray().' );
  8041. return nodeObject( new UniformArrayNode( values, nodeType ) );
  8042. };
  8043. /**
  8044. * The node allows to set values for built-in shader variables. That is
  8045. * required for features like hardware-accelerated vertex clipping.
  8046. *
  8047. * @augments Node
  8048. */
  8049. class BuiltinNode extends Node {
  8050. /**
  8051. * Constructs a new builtin node.
  8052. *
  8053. * @param {string} name - The name of the built-in shader variable.
  8054. */
  8055. constructor( name ) {
  8056. super( 'float' );
  8057. /**
  8058. * The name of the built-in shader variable.
  8059. *
  8060. * @type {string}
  8061. */
  8062. this.name = name;
  8063. /**
  8064. * This flag can be used for type testing.
  8065. *
  8066. * @type {boolean}
  8067. * @readonly
  8068. * @default true
  8069. */
  8070. this.isBuiltinNode = true;
  8071. }
  8072. /**
  8073. * Generates the code snippet of the builtin node.
  8074. *
  8075. * @param {NodeBuilder} builder - The current node builder.
  8076. * @return {string} The generated code snippet.
  8077. */
  8078. generate( /* builder */ ) {
  8079. return this.name;
  8080. }
  8081. }
  8082. /**
  8083. * TSL function for creating a builtin node.
  8084. *
  8085. * @tsl
  8086. * @function
  8087. * @param {string} name - The name of the built-in shader variable.
  8088. * @returns {BuiltinNode}
  8089. */
  8090. const builtin = nodeProxy( BuiltinNode ).setParameterLength( 1 );
  8091. /**
  8092. * TSL object that represents the current `index` value of the camera if used ArrayCamera.
  8093. *
  8094. * @tsl
  8095. * @type {UniformNode<uint>}
  8096. */
  8097. const cameraIndex = /*@__PURE__*/ uniform( 0, 'uint' ).label( 'u_cameraIndex' ).setGroup( sharedUniformGroup( 'cameraIndex' ) ).toVarying( 'v_cameraIndex' );
  8098. /**
  8099. * TSL object that represents the `near` value of the camera used for the current render.
  8100. *
  8101. * @tsl
  8102. * @type {UniformNode<float>}
  8103. */
  8104. const cameraNear = /*@__PURE__*/ uniform( 'float' ).label( 'cameraNear' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.near );
  8105. /**
  8106. * TSL object that represents the `far` value of the camera used for the current render.
  8107. *
  8108. * @tsl
  8109. * @type {UniformNode<float>}
  8110. */
  8111. const cameraFar = /*@__PURE__*/ uniform( 'float' ).label( 'cameraFar' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.far );
  8112. /**
  8113. * TSL object that represents the projection matrix of the camera used for the current render.
  8114. *
  8115. * @tsl
  8116. * @type {UniformNode<mat4>}
  8117. */
  8118. const cameraProjectionMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  8119. let cameraProjectionMatrix;
  8120. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  8121. const matrices = [];
  8122. for ( const subCamera of camera.cameras ) {
  8123. matrices.push( subCamera.projectionMatrix );
  8124. }
  8125. const cameraProjectionMatrices = uniformArray( matrices ).setGroup( renderGroup ).label( 'cameraProjectionMatrices' );
  8126. cameraProjectionMatrix = cameraProjectionMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toVar( 'cameraProjectionMatrix' );
  8127. } else {
  8128. cameraProjectionMatrix = uniform( 'mat4' ).label( 'cameraProjectionMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrix );
  8129. }
  8130. return cameraProjectionMatrix;
  8131. } ).once() )();
  8132. /**
  8133. * TSL object that represents the inverse projection matrix of the camera used for the current render.
  8134. *
  8135. * @tsl
  8136. * @type {UniformNode<mat4>}
  8137. */
  8138. const cameraProjectionMatrixInverse = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  8139. let cameraProjectionMatrixInverse;
  8140. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  8141. const matrices = [];
  8142. for ( const subCamera of camera.cameras ) {
  8143. matrices.push( subCamera.projectionMatrixInverse );
  8144. }
  8145. const cameraProjectionMatricesInverse = uniformArray( matrices ).setGroup( renderGroup ).label( 'cameraProjectionMatricesInverse' );
  8146. cameraProjectionMatrixInverse = cameraProjectionMatricesInverse.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toVar( 'cameraProjectionMatrixInverse' );
  8147. } else {
  8148. cameraProjectionMatrixInverse = uniform( 'mat4' ).label( 'cameraProjectionMatrixInverse' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrixInverse );
  8149. }
  8150. return cameraProjectionMatrixInverse;
  8151. } ).once() )();
  8152. /**
  8153. * TSL object that represents the view matrix of the camera used for the current render.
  8154. *
  8155. * @tsl
  8156. * @type {UniformNode<mat4>}
  8157. */
  8158. const cameraViewMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  8159. let cameraViewMatrix;
  8160. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  8161. const matrices = [];
  8162. for ( const subCamera of camera.cameras ) {
  8163. matrices.push( subCamera.matrixWorldInverse );
  8164. }
  8165. const cameraViewMatrices = uniformArray( matrices ).setGroup( renderGroup ).label( 'cameraViewMatrices' );
  8166. cameraViewMatrix = cameraViewMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toVar( 'cameraViewMatrix' );
  8167. } else {
  8168. cameraViewMatrix = uniform( 'mat4' ).label( 'cameraViewMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorldInverse );
  8169. }
  8170. return cameraViewMatrix;
  8171. } ).once() )();
  8172. /**
  8173. * TSL object that represents the world matrix of the camera used for the current render.
  8174. *
  8175. * @tsl
  8176. * @type {UniformNode<mat4>}
  8177. */
  8178. const cameraWorldMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraWorldMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorld );
  8179. /**
  8180. * TSL object that represents the normal matrix of the camera used for the current render.
  8181. *
  8182. * @tsl
  8183. * @type {UniformNode<mat3>}
  8184. */
  8185. const cameraNormalMatrix = /*@__PURE__*/ uniform( 'mat3' ).label( 'cameraNormalMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.normalMatrix );
  8186. /**
  8187. * TSL object that represents the position in world space of the camera used for the current render.
  8188. *
  8189. * @tsl
  8190. * @type {UniformNode<vec3>}
  8191. */
  8192. const cameraPosition = /*@__PURE__*/ uniform( new Vector3() ).label( 'cameraPosition' ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => self.value.setFromMatrixPosition( camera.matrixWorld ) );
  8193. const _sphere = /*@__PURE__*/ new Sphere();
  8194. /**
  8195. * This node can be used to access transformation related metrics of 3D objects.
  8196. * Depending on the selected scope, a different metric is represented as a uniform
  8197. * in the shader. The following scopes are supported:
  8198. *
  8199. * - `POSITION`: The object's position in world space.
  8200. * - `VIEW_POSITION`: The object's position in view/camera space.
  8201. * - `DIRECTION`: The object's direction in world space.
  8202. * - `SCALE`: The object's scale in world space.
  8203. * - `WORLD_MATRIX`: The object's matrix in world space.
  8204. *
  8205. * @augments Node
  8206. */
  8207. class Object3DNode extends Node {
  8208. static get type() {
  8209. return 'Object3DNode';
  8210. }
  8211. /**
  8212. * Constructs a new object 3D node.
  8213. *
  8214. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  8215. * @param {?Object3D} [object3d=null] - The 3D object.
  8216. */
  8217. constructor( scope, object3d = null ) {
  8218. super();
  8219. /**
  8220. * The node reports a different type of transformation depending on the scope.
  8221. *
  8222. * @type {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')}
  8223. */
  8224. this.scope = scope;
  8225. /**
  8226. * The 3D object.
  8227. *
  8228. * @type {?Object3D}
  8229. * @default null
  8230. */
  8231. this.object3d = object3d;
  8232. /**
  8233. * Overwritten since this type of node is updated per object.
  8234. *
  8235. * @type {string}
  8236. * @default 'object'
  8237. */
  8238. this.updateType = NodeUpdateType.OBJECT;
  8239. /**
  8240. * Holds the value of the node as a uniform.
  8241. *
  8242. * @type {UniformNode}
  8243. */
  8244. this.uniformNode = new UniformNode( null );
  8245. }
  8246. /**
  8247. * Overwritten since the node type is inferred from the scope.
  8248. *
  8249. * @return {string} The node type.
  8250. */
  8251. getNodeType() {
  8252. const scope = this.scope;
  8253. if ( scope === Object3DNode.WORLD_MATRIX ) {
  8254. return 'mat4';
  8255. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  8256. return 'vec3';
  8257. } else if ( scope === Object3DNode.RADIUS ) {
  8258. return 'float';
  8259. }
  8260. }
  8261. /**
  8262. * Updates the uniform value depending on the scope.
  8263. *
  8264. * @param {NodeFrame} frame - The current node frame.
  8265. */
  8266. update( frame ) {
  8267. const object = this.object3d;
  8268. const uniformNode = this.uniformNode;
  8269. const scope = this.scope;
  8270. if ( scope === Object3DNode.WORLD_MATRIX ) {
  8271. uniformNode.value = object.matrixWorld;
  8272. } else if ( scope === Object3DNode.POSITION ) {
  8273. uniformNode.value = uniformNode.value || new Vector3();
  8274. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  8275. } else if ( scope === Object3DNode.SCALE ) {
  8276. uniformNode.value = uniformNode.value || new Vector3();
  8277. uniformNode.value.setFromMatrixScale( object.matrixWorld );
  8278. } else if ( scope === Object3DNode.DIRECTION ) {
  8279. uniformNode.value = uniformNode.value || new Vector3();
  8280. object.getWorldDirection( uniformNode.value );
  8281. } else if ( scope === Object3DNode.VIEW_POSITION ) {
  8282. const camera = frame.camera;
  8283. uniformNode.value = uniformNode.value || new Vector3();
  8284. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  8285. uniformNode.value.applyMatrix4( camera.matrixWorldInverse );
  8286. } else if ( scope === Object3DNode.RADIUS ) {
  8287. const geometry = frame.object.geometry;
  8288. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  8289. _sphere.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  8290. uniformNode.value = _sphere.radius;
  8291. }
  8292. }
  8293. /**
  8294. * Generates the code snippet of the uniform node. The node type of the uniform
  8295. * node also depends on the selected scope.
  8296. *
  8297. * @param {NodeBuilder} builder - The current node builder.
  8298. * @return {string} The generated code snippet.
  8299. */
  8300. generate( builder ) {
  8301. const scope = this.scope;
  8302. if ( scope === Object3DNode.WORLD_MATRIX ) {
  8303. this.uniformNode.nodeType = 'mat4';
  8304. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  8305. this.uniformNode.nodeType = 'vec3';
  8306. } else if ( scope === Object3DNode.RADIUS ) {
  8307. this.uniformNode.nodeType = 'float';
  8308. }
  8309. return this.uniformNode.build( builder );
  8310. }
  8311. serialize( data ) {
  8312. super.serialize( data );
  8313. data.scope = this.scope;
  8314. }
  8315. deserialize( data ) {
  8316. super.deserialize( data );
  8317. this.scope = data.scope;
  8318. }
  8319. }
  8320. Object3DNode.WORLD_MATRIX = 'worldMatrix';
  8321. Object3DNode.POSITION = 'position';
  8322. Object3DNode.SCALE = 'scale';
  8323. Object3DNode.VIEW_POSITION = 'viewPosition';
  8324. Object3DNode.DIRECTION = 'direction';
  8325. Object3DNode.RADIUS = 'radius';
  8326. /**
  8327. * TSL function for creating an object 3D node that represents the object's direction in world space.
  8328. *
  8329. * @tsl
  8330. * @function
  8331. * @param {?Object3D} [object3d] - The 3D object.
  8332. * @returns {Object3DNode<vec3>}
  8333. */
  8334. const objectDirection = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.DIRECTION ).setParameterLength( 1 );
  8335. /**
  8336. * TSL function for creating an object 3D node that represents the object's world matrix.
  8337. *
  8338. * @tsl
  8339. * @function
  8340. * @param {?Object3D} [object3d] - The 3D object.
  8341. * @returns {Object3DNode<mat4>}
  8342. */
  8343. const objectWorldMatrix = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX ).setParameterLength( 1 );
  8344. /**
  8345. * TSL function for creating an object 3D node that represents the object's position in world space.
  8346. *
  8347. * @tsl
  8348. * @function
  8349. * @param {?Object3D} [object3d] - The 3D object.
  8350. * @returns {Object3DNode<vec3>}
  8351. */
  8352. const objectPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.POSITION ).setParameterLength( 1 );
  8353. /**
  8354. * TSL function for creating an object 3D node that represents the object's scale in world space.
  8355. *
  8356. * @tsl
  8357. * @function
  8358. * @param {?Object3D} [object3d] - The 3D object.
  8359. * @returns {Object3DNode<vec3>}
  8360. */
  8361. const objectScale = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.SCALE ).setParameterLength( 1 );
  8362. /**
  8363. * TSL function for creating an object 3D node that represents the object's position in view/camera space.
  8364. *
  8365. * @tsl
  8366. * @function
  8367. * @param {?Object3D} [object3d] - The 3D object.
  8368. * @returns {Object3DNode<vec3>}
  8369. */
  8370. const objectViewPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION ).setParameterLength( 1 );
  8371. /**
  8372. * TSL function for creating an object 3D node that represents the object's radius.
  8373. *
  8374. * @tsl
  8375. * @function
  8376. * @param {?Object3D} [object3d] - The 3D object.
  8377. * @returns {Object3DNode<vec3>}
  8378. */
  8379. const objectRadius = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.RADIUS ).setParameterLength( 1 );
  8380. /**
  8381. * This type of node is a specialized version of `Object3DNode`
  8382. * with larger set of model related metrics. Unlike `Object3DNode`,
  8383. * `ModelNode` extracts the reference to the 3D object from the
  8384. * current node frame state.
  8385. *
  8386. * @augments Object3DNode
  8387. */
  8388. class ModelNode extends Object3DNode {
  8389. static get type() {
  8390. return 'ModelNode';
  8391. }
  8392. /**
  8393. * Constructs a new object model node.
  8394. *
  8395. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  8396. */
  8397. constructor( scope ) {
  8398. super( scope );
  8399. }
  8400. /**
  8401. * Extracts the model reference from the frame state and then
  8402. * updates the uniform value depending on the scope.
  8403. *
  8404. * @param {NodeFrame} frame - The current node frame.
  8405. */
  8406. update( frame ) {
  8407. this.object3d = frame.object;
  8408. super.update( frame );
  8409. }
  8410. }
  8411. /**
  8412. * TSL object that represents the object's direction in world space.
  8413. *
  8414. * @tsl
  8415. * @type {ModelNode<vec3>}
  8416. */
  8417. const modelDirection = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.DIRECTION );
  8418. /**
  8419. * TSL object that represents the object's world matrix.
  8420. *
  8421. * @tsl
  8422. * @type {ModelNode<mat4>}
  8423. */
  8424. const modelWorldMatrix = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX );
  8425. /**
  8426. * TSL object that represents the object's position in world space.
  8427. *
  8428. * @tsl
  8429. * @type {ModelNode<vec3>}
  8430. */
  8431. const modelPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.POSITION );
  8432. /**
  8433. * TSL object that represents the object's scale in world space.
  8434. *
  8435. * @tsl
  8436. * @type {ModelNode<vec3>}
  8437. */
  8438. const modelScale = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.SCALE );
  8439. /**
  8440. * TSL object that represents the object's position in view/camera space.
  8441. *
  8442. * @tsl
  8443. * @type {ModelNode<vec3>}
  8444. */
  8445. const modelViewPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.VIEW_POSITION );
  8446. /**
  8447. * TSL object that represents the object's radius.
  8448. *
  8449. * @tsl
  8450. * @type {ModelNode<float>}
  8451. */
  8452. const modelRadius = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.RADIUS );
  8453. /**
  8454. * TSL object that represents the object's normal matrix.
  8455. *
  8456. * @tsl
  8457. * @type {UniformNode<mat3>}
  8458. */
  8459. const modelNormalMatrix = /*@__PURE__*/ uniform( new Matrix3() ).onObjectUpdate( ( { object }, self ) => self.value.getNormalMatrix( object.matrixWorld ) );
  8460. /**
  8461. * TSL object that represents the object's inverse world matrix.
  8462. *
  8463. * @tsl
  8464. * @type {UniformNode<mat4>}
  8465. */
  8466. const modelWorldMatrixInverse = /*@__PURE__*/ uniform( new Matrix4() ).onObjectUpdate( ( { object }, self ) => self.value.copy( object.matrixWorld ).invert() );
  8467. /**
  8468. * TSL object that represents the object's model view matrix.
  8469. *
  8470. * @tsl
  8471. * @type {Node<mat4>}
  8472. */
  8473. const modelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  8474. return builder.renderer.overrideNodes.modelViewMatrix || mediumpModelViewMatrix;
  8475. } ).once() )().toVar( 'modelViewMatrix' );
  8476. // GPU Precision
  8477. /**
  8478. * TSL object that represents the object's model view in `mediump` precision.
  8479. *
  8480. * @tsl
  8481. * @type {Node<mat4>}
  8482. */
  8483. const mediumpModelViewMatrix = /*@__PURE__*/ cameraViewMatrix.mul( modelWorldMatrix );
  8484. // CPU Precision
  8485. /**
  8486. * TSL object that represents the object's model view in `highp` precision
  8487. * which is achieved by computing the matrix in JS and not in the shader.
  8488. *
  8489. * @tsl
  8490. * @type {Node<mat4>}
  8491. */
  8492. const highpModelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  8493. builder.context.isHighPrecisionModelViewMatrix = true;
  8494. return uniform( 'mat4' ).onObjectUpdate( ( { object, camera } ) => {
  8495. return object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  8496. } );
  8497. } ).once() )().toVar( 'highpModelViewMatrix' );
  8498. /**
  8499. * TSL object that represents the object's model normal view in `highp` precision
  8500. * which is achieved by computing the matrix in JS and not in the shader.
  8501. *
  8502. * @tsl
  8503. * @type {Node<mat3>}
  8504. */
  8505. const highpModelNormalViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  8506. const isHighPrecisionModelViewMatrix = builder.context.isHighPrecisionModelViewMatrix;
  8507. return uniform( 'mat3' ).onObjectUpdate( ( { object, camera } ) => {
  8508. if ( isHighPrecisionModelViewMatrix !== true ) {
  8509. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  8510. }
  8511. return object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  8512. } );
  8513. } ).once() )().toVar( 'highpModelNormalViewMatrix' );
  8514. /**
  8515. * TSL object that represents the position attribute of the current rendered object.
  8516. *
  8517. * @tsl
  8518. * @type {AttributeNode<vec3>}
  8519. */
  8520. const positionGeometry = /*@__PURE__*/ attribute( 'position', 'vec3' );
  8521. /**
  8522. * TSL object that represents the vertex position in local space of the current rendered object.
  8523. *
  8524. * @tsl
  8525. * @type {AttributeNode<vec3>}
  8526. */
  8527. const positionLocal = /*@__PURE__*/ positionGeometry.toVarying( 'positionLocal' );
  8528. /**
  8529. * TSL object that represents the previous vertex position in local space of the current rendered object.
  8530. * Used in context of {@link VelocityNode} for rendering motion vectors.
  8531. *
  8532. * @tsl
  8533. * @type {AttributeNode<vec3>}
  8534. */
  8535. const positionPrevious = /*@__PURE__*/ positionGeometry.toVarying( 'positionPrevious' );
  8536. /**
  8537. * TSL object that represents the vertex position in world space of the current rendered object.
  8538. *
  8539. * @tsl
  8540. * @type {VaryingNode<vec3>}
  8541. */
  8542. const positionWorld = /*@__PURE__*/ ( Fn( ( builder ) => {
  8543. return modelWorldMatrix.mul( positionLocal ).xyz.toVarying( builder.getNamespace( 'v_positionWorld' ) );
  8544. }, 'vec3' ).once( 'POSITION' ) )();
  8545. /**
  8546. * TSL object that represents the position world direction of the current rendered object.
  8547. *
  8548. * @tsl
  8549. * @type {Node<vec3>}
  8550. */
  8551. const positionWorldDirection = /*@__PURE__*/ ( Fn( ( builder ) => {
  8552. const vertexPWD = positionLocal.transformDirection( modelWorldMatrix ).toVarying( builder.getNamespace( 'v_positionWorldDirection' ) );
  8553. return vertexPWD.normalize().toVar( 'positionWorldDirection' );
  8554. }, 'vec3' ).once( 'POSITION' ) )();
  8555. /**
  8556. * TSL object that represents the vertex position in view space of the current rendered object.
  8557. *
  8558. * @tsl
  8559. * @type {VaryingNode<vec3>}
  8560. */
  8561. const positionView = /*@__PURE__*/ ( Fn( ( builder ) => {
  8562. return builder.context.setupPositionView().toVarying( builder.getNamespace( 'v_positionView' ) );
  8563. }, 'vec3' ).once( 'POSITION' ) )();
  8564. /**
  8565. * TSL object that represents the position view direction of the current rendered object.
  8566. *
  8567. * @tsl
  8568. * @type {VaryingNode<vec3>}
  8569. */
  8570. const positionViewDirection = /*@__PURE__*/ positionView.negate().toVarying( 'v_positionViewDirection' ).normalize().toVar( 'positionViewDirection' );
  8571. /**
  8572. * This node can be used to evaluate whether a primitive is front or back facing.
  8573. *
  8574. * @augments Node
  8575. */
  8576. class FrontFacingNode extends Node {
  8577. static get type() {
  8578. return 'FrontFacingNode';
  8579. }
  8580. /**
  8581. * Constructs a new front facing node.
  8582. */
  8583. constructor() {
  8584. super( 'bool' );
  8585. /**
  8586. * This flag can be used for type testing.
  8587. *
  8588. * @type {boolean}
  8589. * @readonly
  8590. * @default true
  8591. */
  8592. this.isFrontFacingNode = true;
  8593. }
  8594. generate( builder ) {
  8595. const { renderer, material } = builder;
  8596. if ( renderer.coordinateSystem === WebGLCoordinateSystem ) {
  8597. if ( material.side === BackSide ) {
  8598. return 'false';
  8599. }
  8600. }
  8601. return builder.getFrontFacing();
  8602. }
  8603. }
  8604. /**
  8605. * TSL object that represents whether a primitive is front or back facing
  8606. *
  8607. * @tsl
  8608. * @type {FrontFacingNode<bool>}
  8609. */
  8610. const frontFacing = /*@__PURE__*/ nodeImmutable( FrontFacingNode );
  8611. /**
  8612. * TSL object that represents the front facing status as a number instead of a bool.
  8613. * `1` means front facing, `-1` means back facing.
  8614. *
  8615. * @tsl
  8616. * @type {Node<float>}
  8617. */
  8618. const faceDirection = /*@__PURE__*/ float( frontFacing ).mul( 2.0 ).sub( 1.0 );
  8619. /**
  8620. * TSL object that represents the normal attribute of the current rendered object.
  8621. *
  8622. * @tsl
  8623. * @type {Node<vec3>}
  8624. */
  8625. const normalGeometry = /*@__PURE__*/ attribute( 'normal', 'vec3' );
  8626. /**
  8627. * TSL object that represents the vertex normal in local space of the current rendered object.
  8628. *
  8629. * @tsl
  8630. * @type {Node<vec3>}
  8631. */
  8632. const normalLocal = /*@__PURE__*/ ( Fn( ( builder ) => {
  8633. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  8634. console.warn( 'THREE.TSL: Vertex attribute "normal" not found on geometry.' );
  8635. return vec3( 0, 1, 0 );
  8636. }
  8637. return normalGeometry;
  8638. }, 'vec3' ).once() )().toVar( 'normalLocal' );
  8639. /**
  8640. * TSL object that represents the flat vertex normal in view space of the current rendered object.
  8641. *
  8642. * @tsl
  8643. * @type {Node<vec3>}
  8644. */
  8645. const normalFlat = /*@__PURE__*/ positionView.dFdx().cross( positionView.dFdy() ).normalize().toVar( 'normalFlat' );
  8646. /**
  8647. * TSL object that represents the vertex normal in view space of the current rendered object.
  8648. *
  8649. * @tsl
  8650. * @type {Node<vec3>}
  8651. */
  8652. const normalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  8653. let node;
  8654. if ( builder.material.flatShading === true ) {
  8655. node = normalFlat;
  8656. } else {
  8657. node = varying( transformNormalToView( normalLocal ), 'v_normalView' ).normalize();
  8658. }
  8659. return node;
  8660. }, 'vec3' ).once() )().toVar( 'normalView' );
  8661. /**
  8662. * TSL object that represents the vertex normal in world space of the current rendered object.
  8663. *
  8664. * @tsl
  8665. * @type {Node<vec3>}
  8666. */
  8667. const normalWorld = /*@__PURE__*/ ( Fn( ( builder ) => {
  8668. let normal = normalView.transformDirection( cameraViewMatrix );
  8669. if ( builder.material.flatShading !== true ) {
  8670. normal = varying( normal, 'v_normalWorld' );
  8671. }
  8672. return normal;
  8673. }, 'vec3' ).once() )().normalize().toVar( 'normalWorld' );
  8674. /**
  8675. * TSL object that represents the transformed vertex normal in view space of the current rendered object.
  8676. *
  8677. * @tsl
  8678. * @type {Node<vec3>}
  8679. */
  8680. const transformedNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  8681. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  8682. let node = builder.context.setupNormal().context( { getUV: null } );
  8683. if ( builder.material.flatShading !== true ) node = node.mul( faceDirection );
  8684. return node;
  8685. }, 'vec3' ).once() )().toVar( 'transformedNormalView' );
  8686. /**
  8687. * TSL object that represents the transformed vertex normal in world space of the current rendered object.
  8688. *
  8689. * @tsl
  8690. * @type {Node<vec3>}
  8691. */
  8692. const transformedNormalWorld = /*@__PURE__*/ transformedNormalView.transformDirection( cameraViewMatrix ).toVar( 'transformedNormalWorld' );
  8693. /**
  8694. * TSL object that represents the transformed clearcoat vertex normal in view space of the current rendered object.
  8695. *
  8696. * @tsl
  8697. * @type {Node<vec3>}
  8698. */
  8699. const transformedClearcoatNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  8700. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  8701. let node = builder.context.setupClearcoatNormal().context( { getUV: null } );
  8702. if ( builder.material.flatShading !== true ) node = node.mul( faceDirection );
  8703. return node;
  8704. }, 'vec3' ).once() )().toVar( 'transformedClearcoatNormalView' );
  8705. /**
  8706. * Transforms the normal with the given matrix.
  8707. *
  8708. * @tsl
  8709. * @function
  8710. * @param {Node<vec3>} normal - The normal.
  8711. * @param {Node<mat3>} [matrix=modelWorldMatrix] - The matrix.
  8712. * @return {Node<vec3>} The transformed normal.
  8713. */
  8714. const transformNormal = /*@__PURE__*/ Fn( ( [ normal, matrix = modelWorldMatrix ] ) => {
  8715. const m = mat3( matrix );
  8716. const transformedNormal = normal.div( vec3( m[ 0 ].dot( m[ 0 ] ), m[ 1 ].dot( m[ 1 ] ), m[ 2 ].dot( m[ 2 ] ) ) );
  8717. return m.mul( transformedNormal ).xyz;
  8718. } );
  8719. /**
  8720. * Transforms the given normal from local to view space.
  8721. *
  8722. * @tsl
  8723. * @function
  8724. * @param {Node<vec3>} normal - The normal.
  8725. * @param {NodeBuilder} builder - The current node builder.
  8726. * @return {Node<vec3>} The transformed normal.
  8727. */
  8728. const transformNormalToView = /*@__PURE__*/ Fn( ( [ normal ], builder ) => {
  8729. const modelNormalViewMatrix = builder.renderer.overrideNodes.modelNormalViewMatrix;
  8730. if ( modelNormalViewMatrix !== null ) {
  8731. return modelNormalViewMatrix.transformDirection( normal );
  8732. }
  8733. //
  8734. const transformedNormal = modelNormalMatrix.mul( normal );
  8735. return cameraViewMatrix.transformDirection( transformedNormal );
  8736. } );
  8737. const _e1$1 = /*@__PURE__*/ new Euler();
  8738. const _m1$1 = /*@__PURE__*/ new Matrix4();
  8739. /**
  8740. * TSL object that represents the refraction ratio of the material used for rendering the current object.
  8741. *
  8742. * @tsl
  8743. * @type {UniformNode<float>}
  8744. */
  8745. const materialRefractionRatio = /*@__PURE__*/ uniform( 0 ).onReference( ( { material } ) => material ).onObjectUpdate( ( { material } ) => material.refractionRatio );
  8746. /**
  8747. * TSL object that represents the intensity of environment maps of PBR materials.
  8748. * When `material.envMap` is set, the value is `material.envMapIntensity` otherwise `scene.environmentIntensity`.
  8749. *
  8750. * @tsl
  8751. * @type {Node<float>}
  8752. */
  8753. const materialEnvIntensity = /*@__PURE__*/ uniform( 1 ).onReference( ( { material } ) => material ).onObjectUpdate( function ( { material, scene } ) {
  8754. return material.envMap ? material.envMapIntensity : scene.environmentIntensity;
  8755. } );
  8756. /**
  8757. * TSL object that represents the rotation of environment maps.
  8758. * When `material.envMap` is set, the value is `material.envMapRotation`. `scene.environmentRotation` controls the
  8759. * rotation of `scene.environment` instead.
  8760. *
  8761. * @tsl
  8762. * @type {Node<mat4>}
  8763. */
  8764. const materialEnvRotation = /*@__PURE__*/ uniform( new Matrix4() ).onReference( function ( frame ) {
  8765. return frame.material;
  8766. } ).onObjectUpdate( function ( { material, scene } ) {
  8767. const rotation = ( scene.environment !== null && material.envMap === null ) ? scene.environmentRotation : material.envMapRotation;
  8768. if ( rotation ) {
  8769. _e1$1.copy( rotation );
  8770. _m1$1.makeRotationFromEuler( _e1$1 );
  8771. } else {
  8772. _m1$1.identity();
  8773. }
  8774. return _m1$1;
  8775. } );
  8776. /**
  8777. * The reflect vector in view space.
  8778. *
  8779. * @tsl
  8780. * @type {Node<vec3>}
  8781. */
  8782. const reflectView = /*@__PURE__*/ positionViewDirection.negate().reflect( transformedNormalView );
  8783. /**
  8784. * The refract vector in view space.
  8785. *
  8786. * @tsl
  8787. * @type {Node<vec3>}
  8788. */
  8789. const refractView = /*@__PURE__*/ positionViewDirection.negate().refract( transformedNormalView, materialRefractionRatio );
  8790. /**
  8791. * Used for sampling cube maps when using cube reflection mapping.
  8792. *
  8793. * @tsl
  8794. * @type {Node<vec3>}
  8795. */
  8796. const reflectVector = /*@__PURE__*/ reflectView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  8797. /**
  8798. * Used for sampling cube maps when using cube refraction mapping.
  8799. *
  8800. * @tsl
  8801. * @type {Node<vec3>}
  8802. */
  8803. const refractVector = /*@__PURE__*/ refractView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  8804. const EmptyTexture = /*@__PURE__*/ new CubeTexture();
  8805. /**
  8806. * This type of uniform node represents a cube texture.
  8807. *
  8808. * @augments TextureNode
  8809. */
  8810. class CubeTextureNode extends TextureNode {
  8811. static get type() {
  8812. return 'CubeTextureNode';
  8813. }
  8814. /**
  8815. * Constructs a new cube texture node.
  8816. *
  8817. * @param {CubeTexture} value - The cube texture.
  8818. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  8819. * @param {?Node<int>} [levelNode=null] - The level node.
  8820. * @param {?Node<float>} [biasNode=null] - The bias node.
  8821. */
  8822. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  8823. super( value, uvNode, levelNode, biasNode );
  8824. /**
  8825. * This flag can be used for type testing.
  8826. *
  8827. * @type {boolean}
  8828. * @readonly
  8829. * @default true
  8830. */
  8831. this.isCubeTextureNode = true;
  8832. }
  8833. /**
  8834. * Overwrites the default implementation to return a fixed value `'cubeTexture'`.
  8835. *
  8836. * @param {NodeBuilder} builder - The current node builder.
  8837. * @return {string} The input type.
  8838. */
  8839. getInputType( /*builder*/ ) {
  8840. return 'cubeTexture';
  8841. }
  8842. /**
  8843. * Returns a default uvs based on the mapping type of the cube texture.
  8844. *
  8845. * @return {Node<vec3>} The default uv attribute.
  8846. */
  8847. getDefaultUV() {
  8848. const texture = this.value;
  8849. if ( texture.mapping === CubeReflectionMapping ) {
  8850. return reflectVector;
  8851. } else if ( texture.mapping === CubeRefractionMapping ) {
  8852. return refractVector;
  8853. } else {
  8854. console.error( 'THREE.CubeTextureNode: Mapping "%s" not supported.', texture.mapping );
  8855. return vec3( 0, 0, 0 );
  8856. }
  8857. }
  8858. /**
  8859. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  8860. * for cube textures. The uv transformation matrix is not applied to cube textures.
  8861. *
  8862. * @param {boolean} value - The update toggle.
  8863. */
  8864. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for CubeTextureNode
  8865. /**
  8866. * Setups the uv node. Depending on the backend as well as the texture type, it might be necessary
  8867. * to modify the uv node for correct sampling.
  8868. *
  8869. * @param {NodeBuilder} builder - The current node builder.
  8870. * @param {Node} uvNode - The uv node to setup.
  8871. * @return {Node} The updated uv node.
  8872. */
  8873. setupUV( builder, uvNode ) {
  8874. const texture = this.value;
  8875. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem || ! texture.isRenderTargetTexture ) {
  8876. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  8877. }
  8878. return materialEnvRotation.mul( uvNode );
  8879. }
  8880. /**
  8881. * Generates the uv code snippet.
  8882. *
  8883. * @param {NodeBuilder} builder - The current node builder.
  8884. * @param {Node} cubeUV - The uv node to generate code for.
  8885. * @return {string} The generated code snippet.
  8886. */
  8887. generateUV( builder, cubeUV ) {
  8888. return cubeUV.build( builder, 'vec3' );
  8889. }
  8890. }
  8891. /**
  8892. * TSL function for creating a cube texture node.
  8893. *
  8894. * @tsl
  8895. * @function
  8896. * @param {CubeTexture} value - The cube texture.
  8897. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  8898. * @param {?Node<int>} [levelNode=null] - The level node.
  8899. * @param {?Node<float>} [biasNode=null] - The bias node.
  8900. * @returns {CubeTextureNode}
  8901. */
  8902. const cubeTextureBase = /*@__PURE__*/ nodeProxy( CubeTextureNode ).setParameterLength( 1, 4 ).setName( 'cubeTexture' );
  8903. /**
  8904. * TSL function for creating a cube texture uniform node.
  8905. *
  8906. * @tsl
  8907. * @function
  8908. * @param {?CubeTexture|CubeTextureNode} [value=EmptyTexture] - The cube texture.
  8909. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  8910. * @param {?Node<int>} [levelNode=null] - The level node.
  8911. * @param {?Node<float>} [biasNode=null] - The bias node.
  8912. * @returns {CubeTextureNode}
  8913. */
  8914. const cubeTexture = ( value = EmptyTexture, uvNode = null, levelNode = null, biasNode = null ) => {
  8915. let textureNode;
  8916. if ( value && value.isCubeTextureNode === true ) {
  8917. textureNode = nodeObject( value.clone() );
  8918. textureNode.referenceNode = value.getSelf(); // Ensure the reference is set to the original node
  8919. if ( uvNode !== null ) textureNode.uvNode = nodeObject( uvNode );
  8920. if ( levelNode !== null ) textureNode.levelNode = nodeObject( levelNode );
  8921. if ( biasNode !== null ) textureNode.biasNode = nodeObject( biasNode );
  8922. } else {
  8923. textureNode = cubeTextureBase( value, uvNode, levelNode, biasNode );
  8924. }
  8925. return textureNode;
  8926. };
  8927. /**
  8928. * TSL function for creating a uniform cube texture node.
  8929. *
  8930. * @tsl
  8931. * @function
  8932. * @param {?CubeTexture} [value=EmptyTexture] - The cube texture.
  8933. * @returns {CubeTextureNode}
  8934. */
  8935. const uniformCubeTexture = ( value = EmptyTexture ) => cubeTextureBase( value );
  8936. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  8937. /**
  8938. * This class is only relevant if the referenced property is array-like.
  8939. * In this case, `ReferenceElementNode` allows to refer to a specific
  8940. * element inside the data structure via an index.
  8941. *
  8942. * @augments ArrayElementNode
  8943. */
  8944. class ReferenceElementNode extends ArrayElementNode {
  8945. static get type() {
  8946. return 'ReferenceElementNode';
  8947. }
  8948. /**
  8949. * Constructs a new reference element node.
  8950. *
  8951. * @param {?ReferenceNode} referenceNode - The reference node.
  8952. * @param {Node} indexNode - The index node that defines the element access.
  8953. */
  8954. constructor( referenceNode, indexNode ) {
  8955. super( referenceNode, indexNode );
  8956. /**
  8957. * Similar to {@link ReferenceNode#reference}, an additional
  8958. * property references to the current node.
  8959. *
  8960. * @type {?ReferenceNode}
  8961. * @default null
  8962. */
  8963. this.referenceNode = referenceNode;
  8964. /**
  8965. * This flag can be used for type testing.
  8966. *
  8967. * @type {boolean}
  8968. * @readonly
  8969. * @default true
  8970. */
  8971. this.isReferenceElementNode = true;
  8972. }
  8973. /**
  8974. * This method is overwritten since the node type is inferred from
  8975. * the uniform type of the reference node.
  8976. *
  8977. * @return {string} The node type.
  8978. */
  8979. getNodeType() {
  8980. return this.referenceNode.uniformType;
  8981. }
  8982. generate( builder ) {
  8983. const snippet = super.generate( builder );
  8984. const arrayType = this.referenceNode.getNodeType();
  8985. const elementType = this.getNodeType();
  8986. return builder.format( snippet, arrayType, elementType );
  8987. }
  8988. }
  8989. /**
  8990. * This type of node establishes a reference to a property of another object.
  8991. * In this way, the value of the node is automatically linked to the value of
  8992. * referenced object. Reference nodes internally represent the linked value
  8993. * as a uniform.
  8994. *
  8995. * @augments Node
  8996. */
  8997. class ReferenceNode extends Node {
  8998. static get type() {
  8999. return 'ReferenceNode';
  9000. }
  9001. /**
  9002. * Constructs a new reference node.
  9003. *
  9004. * @param {string} property - The name of the property the node refers to.
  9005. * @param {string} uniformType - The uniform type that should be used to represent the property value.
  9006. * @param {?Object} [object=null] - The object the property belongs to.
  9007. * @param {?number} [count=null] - When the linked property is an array-like, this parameter defines its length.
  9008. */
  9009. constructor( property, uniformType, object = null, count = null ) {
  9010. super();
  9011. /**
  9012. * The name of the property the node refers to.
  9013. *
  9014. * @type {string}
  9015. */
  9016. this.property = property;
  9017. /**
  9018. * The uniform type that should be used to represent the property value.
  9019. *
  9020. * @type {string}
  9021. */
  9022. this.uniformType = uniformType;
  9023. /**
  9024. * The object the property belongs to.
  9025. *
  9026. * @type {?Object}
  9027. * @default null
  9028. */
  9029. this.object = object;
  9030. /**
  9031. * When the linked property is an array, this parameter defines its length.
  9032. *
  9033. * @type {?number}
  9034. * @default null
  9035. */
  9036. this.count = count;
  9037. /**
  9038. * The property name might have dots so nested properties can be referred.
  9039. * The hierarchy of the names is stored inside this array.
  9040. *
  9041. * @type {Array<string>}
  9042. */
  9043. this.properties = property.split( '.' );
  9044. /**
  9045. * Points to the current referred object. This property exists next to {@link ReferenceNode#object}
  9046. * since the final reference might be updated from calling code.
  9047. *
  9048. * @type {?Object}
  9049. * @default null
  9050. */
  9051. this.reference = object;
  9052. /**
  9053. * The uniform node that holds the value of the reference node.
  9054. *
  9055. * @type {UniformNode}
  9056. * @default null
  9057. */
  9058. this.node = null;
  9059. /**
  9060. * The uniform group of the internal uniform.
  9061. *
  9062. * @type {UniformGroupNode}
  9063. * @default null
  9064. */
  9065. this.group = null;
  9066. /**
  9067. * An optional label of the internal uniform node.
  9068. *
  9069. * @type {?string}
  9070. * @default null
  9071. */
  9072. this.name = null;
  9073. /**
  9074. * Overwritten since reference nodes are updated per object.
  9075. *
  9076. * @type {string}
  9077. * @default 'object'
  9078. */
  9079. this.updateType = NodeUpdateType.OBJECT;
  9080. }
  9081. /**
  9082. * When the referred property is array-like, this method can be used
  9083. * to access elements via an index node.
  9084. *
  9085. * @param {IndexNode} indexNode - indexNode.
  9086. * @return {ReferenceElementNode} A reference to an element.
  9087. */
  9088. element( indexNode ) {
  9089. return nodeObject( new ReferenceElementNode( this, nodeObject( indexNode ) ) );
  9090. }
  9091. /**
  9092. * Sets the uniform group for this reference node.
  9093. *
  9094. * @param {UniformGroupNode} group - The uniform group to set.
  9095. * @return {ReferenceNode} A reference to this node.
  9096. */
  9097. setGroup( group ) {
  9098. this.group = group;
  9099. return this;
  9100. }
  9101. /**
  9102. * Sets the label for the internal uniform.
  9103. *
  9104. * @param {string} name - The label to set.
  9105. * @return {ReferenceNode} A reference to this node.
  9106. */
  9107. label( name ) {
  9108. this.name = name;
  9109. return this;
  9110. }
  9111. /**
  9112. * Sets the node type which automatically defines the internal
  9113. * uniform type.
  9114. *
  9115. * @param {string} uniformType - The type to set.
  9116. */
  9117. setNodeType( uniformType ) {
  9118. let node = null;
  9119. if ( this.count !== null ) {
  9120. node = buffer( null, uniformType, this.count );
  9121. } else if ( Array.isArray( this.getValueFromReference() ) ) {
  9122. node = uniformArray( null, uniformType );
  9123. } else if ( uniformType === 'texture' ) {
  9124. node = texture( null );
  9125. } else if ( uniformType === 'cubeTexture' ) {
  9126. node = cubeTexture( null );
  9127. } else {
  9128. node = uniform( null, uniformType );
  9129. }
  9130. if ( this.group !== null ) {
  9131. node.setGroup( this.group );
  9132. }
  9133. if ( this.name !== null ) node.label( this.name );
  9134. this.node = node.getSelf();
  9135. }
  9136. /**
  9137. * This method is overwritten since the node type is inferred from
  9138. * the type of the reference node.
  9139. *
  9140. * @param {NodeBuilder} builder - The current node builder.
  9141. * @return {string} The node type.
  9142. */
  9143. getNodeType( builder ) {
  9144. if ( this.node === null ) {
  9145. this.updateReference( builder );
  9146. this.updateValue();
  9147. }
  9148. return this.node.getNodeType( builder );
  9149. }
  9150. /**
  9151. * Returns the property value from the given referred object.
  9152. *
  9153. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  9154. * @return {any} The value.
  9155. */
  9156. getValueFromReference( object = this.reference ) {
  9157. const { properties } = this;
  9158. let value = object[ properties[ 0 ] ];
  9159. for ( let i = 1; i < properties.length; i ++ ) {
  9160. value = value[ properties[ i ] ];
  9161. }
  9162. return value;
  9163. }
  9164. /**
  9165. * Allows to update the reference based on the given state. The state is only
  9166. * evaluated {@link ReferenceNode#object} is not set.
  9167. *
  9168. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  9169. * @return {Object} The updated reference.
  9170. */
  9171. updateReference( state ) {
  9172. this.reference = this.object !== null ? this.object : state.object;
  9173. return this.reference;
  9174. }
  9175. /**
  9176. * The output of the reference node is the internal uniform node.
  9177. *
  9178. * @param {NodeBuilder} builder - The current node builder.
  9179. * @return {UniformNode} The output node.
  9180. */
  9181. setup( /* builder */ ) {
  9182. this.updateValue();
  9183. return this.node;
  9184. }
  9185. /**
  9186. * Overwritten to update the internal uniform value.
  9187. *
  9188. * @param {NodeFrame} frame - A reference to the current node frame.
  9189. */
  9190. update( /*frame*/ ) {
  9191. this.updateValue();
  9192. }
  9193. /**
  9194. * Retrieves the value from the referred object property and uses it
  9195. * to updated the internal uniform.
  9196. */
  9197. updateValue() {
  9198. if ( this.node === null ) this.setNodeType( this.uniformType );
  9199. const value = this.getValueFromReference();
  9200. if ( Array.isArray( value ) ) {
  9201. this.node.array = value;
  9202. } else {
  9203. this.node.value = value;
  9204. }
  9205. }
  9206. }
  9207. /**
  9208. * TSL function for creating a reference node.
  9209. *
  9210. * @tsl
  9211. * @function
  9212. * @param {string} name - The name of the property the node refers to.
  9213. * @param {string} type - The uniform type that should be used to represent the property value.
  9214. * @param {?Object} [object] - The object the property belongs to.
  9215. * @returns {ReferenceNode}
  9216. */
  9217. const reference = ( name, type, object ) => nodeObject( new ReferenceNode( name, type, object ) );
  9218. /**
  9219. * TSL function for creating a reference node. Use this function if you want need a reference
  9220. * to an array-like property that should be represented as a uniform buffer.
  9221. *
  9222. * @tsl
  9223. * @function
  9224. * @param {string} name - The name of the property the node refers to.
  9225. * @param {string} type - The uniform type that should be used to represent the property value.
  9226. * @param {number} count - The number of value inside the array-like object.
  9227. * @param {Object} object - An array-like object the property belongs to.
  9228. * @returns {ReferenceNode}
  9229. */
  9230. const referenceBuffer = ( name, type, count, object ) => nodeObject( new ReferenceNode( name, type, object, count ) );
  9231. /**
  9232. * This node is a special type of reference node which is intended
  9233. * for linking material properties with node values.
  9234. * ```js
  9235. * const opacityNode = materialReference( 'opacity', 'float', material );
  9236. * ```
  9237. * When changing `material.opacity`, the node value of `opacityNode` will
  9238. * automatically be updated.
  9239. *
  9240. * @augments ReferenceNode
  9241. */
  9242. class MaterialReferenceNode extends ReferenceNode {
  9243. static get type() {
  9244. return 'MaterialReferenceNode';
  9245. }
  9246. /**
  9247. * Constructs a new material reference node.
  9248. *
  9249. * @param {string} property - The name of the property the node refers to.
  9250. * @param {string} inputType - The uniform type that should be used to represent the property value.
  9251. * @param {?Material} [material=null] - The material the property belongs to. When no material is set,
  9252. * the node refers to the material of the current rendered object.
  9253. */
  9254. constructor( property, inputType, material = null ) {
  9255. super( property, inputType, material );
  9256. /**
  9257. * The material the property belongs to. When no material is set,
  9258. * the node refers to the material of the current rendered object.
  9259. *
  9260. * @type {?Material}
  9261. * @default null
  9262. */
  9263. this.material = material;
  9264. /**
  9265. * This flag can be used for type testing.
  9266. *
  9267. * @type {boolean}
  9268. * @readonly
  9269. * @default true
  9270. */
  9271. this.isMaterialReferenceNode = true;
  9272. }
  9273. /**
  9274. * Updates the reference based on the given state. The state is only evaluated
  9275. * {@link MaterialReferenceNode#material} is not set.
  9276. *
  9277. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  9278. * @return {Object} The updated reference.
  9279. */
  9280. updateReference( state ) {
  9281. this.reference = this.material !== null ? this.material : state.material;
  9282. return this.reference;
  9283. }
  9284. }
  9285. /**
  9286. * TSL function for creating a material reference node.
  9287. *
  9288. * @tsl
  9289. * @function
  9290. * @param {string} name - The name of the property the node refers to.
  9291. * @param {string} type - The uniform type that should be used to represent the property value.
  9292. * @param {?Material} [material=null] - The material the property belongs to.
  9293. * When no material is set, the node refers to the material of the current rendered object.
  9294. * @returns {MaterialReferenceNode}
  9295. */
  9296. const materialReference = ( name, type, material = null ) => nodeObject( new MaterialReferenceNode( name, type, material ) );
  9297. /**
  9298. * TSL object that represents the tangent attribute of the current rendered object.
  9299. *
  9300. * @tsl
  9301. * @type {Node<vec4>}
  9302. */
  9303. const tangentGeometry = /*@__PURE__*/ Fn( ( builder ) => {
  9304. if ( builder.geometry.hasAttribute( 'tangent' ) === false ) {
  9305. builder.geometry.computeTangents();
  9306. }
  9307. return attribute( 'tangent', 'vec4' );
  9308. } )();
  9309. /**
  9310. * TSL object that represents the vertex tangent in local space of the current rendered object.
  9311. *
  9312. * @tsl
  9313. * @type {Node<vec3>}
  9314. */
  9315. const tangentLocal = /*@__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' );
  9316. /**
  9317. * TSL object that represents the vertex tangent in view space of the current rendered object.
  9318. *
  9319. * @tsl
  9320. * @type {Node<vec3>}
  9321. */
  9322. const tangentView = /*@__PURE__*/ modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz.toVarying( 'v_tangentView' ).normalize().toVar( 'tangentView' );
  9323. /**
  9324. * TSL object that represents the vertex tangent in world space of the current rendered object.
  9325. *
  9326. * @tsl
  9327. * @type {Node<vec3>}
  9328. */
  9329. const tangentWorld = /*@__PURE__*/ tangentView.transformDirection( cameraViewMatrix ).toVarying( 'v_tangentWorld' ).normalize().toVar( 'tangentWorld' );
  9330. /**
  9331. * TSL object that represents the transformed vertex tangent in view space of the current rendered object.
  9332. *
  9333. * @tsl
  9334. * @type {Node<vec3>}
  9335. */
  9336. const transformedTangentView = /*@__PURE__*/ tangentView.toVar( 'transformedTangentView' );
  9337. /**
  9338. * TSL object that represents the transformed vertex tangent in world space of the current rendered object.
  9339. *
  9340. * @tsl
  9341. * @type {Node<vec3>}
  9342. */
  9343. const transformedTangentWorld = /*@__PURE__*/ transformedTangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedTangentWorld' );
  9344. /**
  9345. * Returns the bitangent node and assigns it to a varying if the material is not flat shaded.
  9346. *
  9347. * @tsl
  9348. * @private
  9349. * @param {Node<vec3>} crossNormalTangent - The cross product of the normal and tangent vectors.
  9350. * @param {string} varyingName - The name of the varying to assign the bitangent to.
  9351. * @returns {Node<vec3>} The bitangent node.
  9352. */
  9353. const getBitangent = /*@__PURE__*/ Fn( ( [ crossNormalTangent, varyingName ], builder ) => {
  9354. let bitangent = crossNormalTangent.mul( tangentGeometry.w ).xyz;
  9355. if ( builder.material.flatShading !== true ) {
  9356. bitangent = varying( bitangent, varyingName );
  9357. }
  9358. return bitangent;
  9359. } ).once();
  9360. /**
  9361. * TSL object that represents the bitangent attribute of the current rendered object.
  9362. *
  9363. * @tsl
  9364. * @type {Node<vec3>}
  9365. */
  9366. const bitangentGeometry = /*@__PURE__*/ getBitangent( normalGeometry.cross( tangentGeometry ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' );
  9367. /**
  9368. * TSL object that represents the vertex bitangent in local space of the current rendered object.
  9369. *
  9370. * @tsl
  9371. * @type {Node<vec3>}
  9372. */
  9373. const bitangentLocal = /*@__PURE__*/ getBitangent( normalLocal.cross( tangentLocal ), 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' );
  9374. /**
  9375. * TSL object that represents the vertex bitangent in view space of the current rendered object.
  9376. *
  9377. * @tsl
  9378. * @type {Node<vec3>}
  9379. */
  9380. const bitangentView = getBitangent( normalView.cross( tangentView ), 'v_bitangentView' ).normalize().toVar( 'bitangentView' );
  9381. /**
  9382. * TSL object that represents the vertex bitangent in world space of the current rendered object.
  9383. *
  9384. * @tsl
  9385. * @type {Node<vec3>}
  9386. */
  9387. const bitangentWorld = /*@__PURE__*/ getBitangent( normalWorld.cross( tangentWorld ), 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' );
  9388. /**
  9389. * TSL object that represents the transformed vertex bitangent in view space of the current rendered object.
  9390. *
  9391. * @tsl
  9392. * @type {Node<vec3>}
  9393. */
  9394. const transformedBitangentView = /*@__PURE__*/ getBitangent( transformedNormalView.cross( transformedTangentView ), 'v_transformedBitangentView' ).normalize().toVar( 'transformedBitangentView' );
  9395. /**
  9396. * TSL object that represents the transformed vertex bitangent in world space of the current rendered object.
  9397. *
  9398. * @tsl
  9399. * @type {Node<vec4>}
  9400. */
  9401. const transformedBitangentWorld = /*@__PURE__*/ transformedBitangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedBitangentWorld' );
  9402. /**
  9403. * TSL object that represents the TBN matrix in view space.
  9404. *
  9405. * @tsl
  9406. * @type {Node<mat3>}
  9407. */
  9408. const TBNViewMatrix = /*@__PURE__*/ mat3( tangentView, bitangentView, normalView );
  9409. /**
  9410. * TSL object that represents the parallax direction.
  9411. *
  9412. * @tsl
  9413. * @type {Node<mat3>}
  9414. */
  9415. const parallaxDirection = /*@__PURE__*/ positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/;
  9416. /**
  9417. * TSL function for computing parallax uv coordinates.
  9418. *
  9419. * @tsl
  9420. * @function
  9421. * @param {Node<vec2>} uv - A uv node.
  9422. * @param {Node<vec2>} scale - A scale node.
  9423. * @returns {Node<vec2>} Parallax uv coordinates.
  9424. */
  9425. const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) );
  9426. /**
  9427. * TSL function for computing bent normals.
  9428. *
  9429. * @tsl
  9430. * @function
  9431. * @returns {Node<vec3>} Bent normals.
  9432. */
  9433. const transformedBentNormalView = /*@__PURE__*/ ( () => {
  9434. // https://google.github.io/filament/Filament.md.html#lighting/imagebasedlights/anisotropy
  9435. let bentNormal = anisotropyB.cross( positionViewDirection );
  9436. bentNormal = bentNormal.cross( anisotropyB ).normalize();
  9437. bentNormal = mix( bentNormal, transformedNormalView, anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2() ).normalize();
  9438. return bentNormal;
  9439. } )();
  9440. // Normal Mapping Without Precomputed Tangents
  9441. // http://www.thetenthplanet.de/archives/1180
  9442. const perturbNormal2Arb = /*@__PURE__*/ Fn( ( inputs ) => {
  9443. const { eye_pos, surf_norm, mapN, uv } = inputs;
  9444. const q0 = eye_pos.dFdx();
  9445. const q1 = eye_pos.dFdy();
  9446. const st0 = uv.dFdx();
  9447. const st1 = uv.dFdy();
  9448. const N = surf_norm; // normalized
  9449. const q1perp = q1.cross( N );
  9450. const q0perp = N.cross( q0 );
  9451. const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) );
  9452. const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) );
  9453. const det = T.dot( T ).max( B.dot( B ) );
  9454. const scale = faceDirection.mul( det.inverseSqrt() );
  9455. return add( T.mul( mapN.x, scale ), B.mul( mapN.y, scale ), N.mul( mapN.z ) ).normalize();
  9456. } );
  9457. /**
  9458. * This class can be used for applying normals maps to materials.
  9459. *
  9460. * ```js
  9461. * material.normalNode = normalMap( texture( normalTex ) );
  9462. * ```
  9463. *
  9464. * @augments TempNode
  9465. */
  9466. class NormalMapNode extends TempNode {
  9467. static get type() {
  9468. return 'NormalMapNode';
  9469. }
  9470. /**
  9471. * Constructs a new normal map node.
  9472. *
  9473. * @param {Node<vec3>} node - Represents the normal map data.
  9474. * @param {?Node<vec2>} [scaleNode=null] - Controls the intensity of the effect.
  9475. */
  9476. constructor( node, scaleNode = null ) {
  9477. super( 'vec3' );
  9478. /**
  9479. * Represents the normal map data.
  9480. *
  9481. * @type {Node<vec3>}
  9482. */
  9483. this.node = node;
  9484. /**
  9485. * Controls the intensity of the effect.
  9486. *
  9487. * @type {?Node<vec2>}
  9488. * @default null
  9489. */
  9490. this.scaleNode = scaleNode;
  9491. /**
  9492. * The normal map type.
  9493. *
  9494. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  9495. * @default TangentSpaceNormalMap
  9496. */
  9497. this.normalMapType = TangentSpaceNormalMap;
  9498. }
  9499. setup( builder ) {
  9500. const { normalMapType, scaleNode } = this;
  9501. let normalMap = this.node.mul( 2.0 ).sub( 1.0 );
  9502. if ( scaleNode !== null ) {
  9503. normalMap = vec3( normalMap.xy.mul( scaleNode ), normalMap.z );
  9504. }
  9505. let outputNode = null;
  9506. if ( normalMapType === ObjectSpaceNormalMap ) {
  9507. outputNode = transformNormalToView( normalMap );
  9508. } else if ( normalMapType === TangentSpaceNormalMap ) {
  9509. const tangent = builder.hasGeometryAttribute( 'tangent' );
  9510. if ( tangent === true ) {
  9511. outputNode = TBNViewMatrix.mul( normalMap ).normalize();
  9512. } else {
  9513. outputNode = perturbNormal2Arb( {
  9514. eye_pos: positionView,
  9515. surf_norm: normalView,
  9516. mapN: normalMap,
  9517. uv: uv()
  9518. } );
  9519. }
  9520. }
  9521. return outputNode;
  9522. }
  9523. }
  9524. /**
  9525. * TSL function for creating a normal map node.
  9526. *
  9527. * @tsl
  9528. * @function
  9529. * @param {Node<vec3>} node - Represents the normal map data.
  9530. * @param {?Node<vec2>} [scaleNode=null] - Controls the intensity of the effect.
  9531. * @returns {NormalMapNode}
  9532. */
  9533. const normalMap = /*@__PURE__*/ nodeProxy( NormalMapNode ).setParameterLength( 1, 2 );
  9534. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  9535. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  9536. const dHdxy_fwd = Fn( ( { textureNode, bumpScale } ) => {
  9537. // It's used to preserve the same TextureNode instance
  9538. const sampleTexture = ( callback ) => textureNode.cache().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv() ), forceUVContext: true } );
  9539. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  9540. return vec2(
  9541. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  9542. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  9543. ).mul( bumpScale );
  9544. } );
  9545. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  9546. const perturbNormalArb = Fn( ( inputs ) => {
  9547. const { surf_pos, surf_norm, dHdxy } = inputs;
  9548. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  9549. const vSigmaX = surf_pos.dFdx().normalize();
  9550. const vSigmaY = surf_pos.dFdy().normalize();
  9551. const vN = surf_norm; // normalized
  9552. const R1 = vSigmaY.cross( vN );
  9553. const R2 = vN.cross( vSigmaX );
  9554. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  9555. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  9556. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  9557. } );
  9558. /**
  9559. * This class can be used for applying bump maps to materials.
  9560. *
  9561. * ```js
  9562. * material.normalNode = bumpMap( texture( bumpTex ) );
  9563. * ```
  9564. *
  9565. * @augments TempNode
  9566. */
  9567. class BumpMapNode extends TempNode {
  9568. static get type() {
  9569. return 'BumpMapNode';
  9570. }
  9571. /**
  9572. * Constructs a new bump map node.
  9573. *
  9574. * @param {Node<float>} textureNode - Represents the bump map data.
  9575. * @param {?Node<float>} [scaleNode=null] - Controls the intensity of the bump effect.
  9576. */
  9577. constructor( textureNode, scaleNode = null ) {
  9578. super( 'vec3' );
  9579. /**
  9580. * Represents the bump map data.
  9581. *
  9582. * @type {Node<float>}
  9583. */
  9584. this.textureNode = textureNode;
  9585. /**
  9586. * Controls the intensity of the bump effect.
  9587. *
  9588. * @type {?Node<float>}
  9589. * @default null
  9590. */
  9591. this.scaleNode = scaleNode;
  9592. }
  9593. setup() {
  9594. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  9595. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  9596. return perturbNormalArb( {
  9597. surf_pos: positionView,
  9598. surf_norm: normalView,
  9599. dHdxy
  9600. } );
  9601. }
  9602. }
  9603. /**
  9604. * TSL function for creating a bump map node.
  9605. *
  9606. * @tsl
  9607. * @function
  9608. * @param {Node<float>} textureNode - Represents the bump map data.
  9609. * @param {?Node<float>} [scaleNode=null] - Controls the intensity of the bump effect.
  9610. * @returns {BumpMapNode}
  9611. */
  9612. const bumpMap = /*@__PURE__*/ nodeProxy( BumpMapNode ).setParameterLength( 1, 2 );
  9613. const _propertyCache = new Map();
  9614. /**
  9615. * This class should simplify the node access to material properties.
  9616. * It internal uses reference nodes to make sure changes to material
  9617. * properties are automatically reflected to predefined TSL objects
  9618. * like e.g. `materialColor`.
  9619. *
  9620. * @augments Node
  9621. */
  9622. class MaterialNode extends Node {
  9623. static get type() {
  9624. return 'MaterialNode';
  9625. }
  9626. /**
  9627. * Constructs a new material node.
  9628. *
  9629. * @param {string} scope - The scope defines what kind of material property is referred by the node.
  9630. */
  9631. constructor( scope ) {
  9632. super();
  9633. /**
  9634. * The scope defines what material property is referred by the node.
  9635. *
  9636. * @type {string}
  9637. */
  9638. this.scope = scope;
  9639. }
  9640. /**
  9641. * Returns a cached reference node for the given property and type.
  9642. *
  9643. * @param {string} property - The name of the material property.
  9644. * @param {string} type - The uniform type of the property.
  9645. * @return {MaterialReferenceNode} A material reference node representing the property access.
  9646. */
  9647. getCache( property, type ) {
  9648. let node = _propertyCache.get( property );
  9649. if ( node === undefined ) {
  9650. node = materialReference( property, type );
  9651. _propertyCache.set( property, node );
  9652. }
  9653. return node;
  9654. }
  9655. /**
  9656. * Returns a float-typed material reference node for the given property name.
  9657. *
  9658. * @param {string} property - The name of the material property.
  9659. * @return {MaterialReferenceNode<float>} A material reference node representing the property access.
  9660. */
  9661. getFloat( property ) {
  9662. return this.getCache( property, 'float' );
  9663. }
  9664. /**
  9665. * Returns a color-typed material reference node for the given property name.
  9666. *
  9667. * @param {string} property - The name of the material property.
  9668. * @return {MaterialReferenceNode<color>} A material reference node representing the property access.
  9669. */
  9670. getColor( property ) {
  9671. return this.getCache( property, 'color' );
  9672. }
  9673. /**
  9674. * Returns a texture-typed material reference node for the given property name.
  9675. *
  9676. * @param {string} property - The name of the material property.
  9677. * @return {MaterialReferenceNode} A material reference node representing the property access.
  9678. */
  9679. getTexture( property ) {
  9680. return this.getCache( property === 'map' ? 'map' : property + 'Map', 'texture' );
  9681. }
  9682. /**
  9683. * The node setup is done depending on the selected scope. Multiple material properties
  9684. * might be grouped into a single node composition if they logically belong together.
  9685. *
  9686. * @param {NodeBuilder} builder - The current node builder.
  9687. * @return {Node} The node representing the selected scope.
  9688. */
  9689. setup( builder ) {
  9690. const material = builder.context.material;
  9691. const scope = this.scope;
  9692. let node = null;
  9693. if ( scope === MaterialNode.COLOR ) {
  9694. const colorNode = material.color !== undefined ? this.getColor( scope ) : vec3();
  9695. if ( material.map && material.map.isTexture === true ) {
  9696. node = colorNode.mul( this.getTexture( 'map' ) );
  9697. } else {
  9698. node = colorNode;
  9699. }
  9700. } else if ( scope === MaterialNode.OPACITY ) {
  9701. const opacityNode = this.getFloat( scope );
  9702. if ( material.alphaMap && material.alphaMap.isTexture === true ) {
  9703. node = opacityNode.mul( this.getTexture( 'alpha' ) );
  9704. } else {
  9705. node = opacityNode;
  9706. }
  9707. } else if ( scope === MaterialNode.SPECULAR_STRENGTH ) {
  9708. if ( material.specularMap && material.specularMap.isTexture === true ) {
  9709. node = this.getTexture( 'specular' ).r;
  9710. } else {
  9711. node = float( 1 );
  9712. }
  9713. } else if ( scope === MaterialNode.SPECULAR_INTENSITY ) {
  9714. const specularIntensityNode = this.getFloat( scope );
  9715. if ( material.specularIntensityMap && material.specularIntensityMap.isTexture === true ) {
  9716. node = specularIntensityNode.mul( this.getTexture( scope ).a );
  9717. } else {
  9718. node = specularIntensityNode;
  9719. }
  9720. } else if ( scope === MaterialNode.SPECULAR_COLOR ) {
  9721. const specularColorNode = this.getColor( scope );
  9722. if ( material.specularColorMap && material.specularColorMap.isTexture === true ) {
  9723. node = specularColorNode.mul( this.getTexture( scope ).rgb );
  9724. } else {
  9725. node = specularColorNode;
  9726. }
  9727. } else if ( scope === MaterialNode.ROUGHNESS ) { // TODO: cleanup similar branches
  9728. const roughnessNode = this.getFloat( scope );
  9729. if ( material.roughnessMap && material.roughnessMap.isTexture === true ) {
  9730. node = roughnessNode.mul( this.getTexture( scope ).g );
  9731. } else {
  9732. node = roughnessNode;
  9733. }
  9734. } else if ( scope === MaterialNode.METALNESS ) {
  9735. const metalnessNode = this.getFloat( scope );
  9736. if ( material.metalnessMap && material.metalnessMap.isTexture === true ) {
  9737. node = metalnessNode.mul( this.getTexture( scope ).b );
  9738. } else {
  9739. node = metalnessNode;
  9740. }
  9741. } else if ( scope === MaterialNode.EMISSIVE ) {
  9742. const emissiveIntensityNode = this.getFloat( 'emissiveIntensity' );
  9743. const emissiveNode = this.getColor( scope ).mul( emissiveIntensityNode );
  9744. if ( material.emissiveMap && material.emissiveMap.isTexture === true ) {
  9745. node = emissiveNode.mul( this.getTexture( scope ) );
  9746. } else {
  9747. node = emissiveNode;
  9748. }
  9749. } else if ( scope === MaterialNode.NORMAL ) {
  9750. if ( material.normalMap ) {
  9751. node = normalMap( this.getTexture( 'normal' ), this.getCache( 'normalScale', 'vec2' ) );
  9752. node.normalMapType = material.normalMapType;
  9753. } else if ( material.bumpMap ) {
  9754. node = bumpMap( this.getTexture( 'bump' ).r, this.getFloat( 'bumpScale' ) );
  9755. } else {
  9756. node = normalView;
  9757. }
  9758. } else if ( scope === MaterialNode.CLEARCOAT ) {
  9759. const clearcoatNode = this.getFloat( scope );
  9760. if ( material.clearcoatMap && material.clearcoatMap.isTexture === true ) {
  9761. node = clearcoatNode.mul( this.getTexture( scope ).r );
  9762. } else {
  9763. node = clearcoatNode;
  9764. }
  9765. } else if ( scope === MaterialNode.CLEARCOAT_ROUGHNESS ) {
  9766. const clearcoatRoughnessNode = this.getFloat( scope );
  9767. if ( material.clearcoatRoughnessMap && material.clearcoatRoughnessMap.isTexture === true ) {
  9768. node = clearcoatRoughnessNode.mul( this.getTexture( scope ).r );
  9769. } else {
  9770. node = clearcoatRoughnessNode;
  9771. }
  9772. } else if ( scope === MaterialNode.CLEARCOAT_NORMAL ) {
  9773. if ( material.clearcoatNormalMap ) {
  9774. node = normalMap( this.getTexture( scope ), this.getCache( scope + 'Scale', 'vec2' ) );
  9775. } else {
  9776. node = normalView;
  9777. }
  9778. } else if ( scope === MaterialNode.SHEEN ) {
  9779. const sheenNode = this.getColor( 'sheenColor' ).mul( this.getFloat( 'sheen' ) ); // Move this mul() to CPU
  9780. if ( material.sheenColorMap && material.sheenColorMap.isTexture === true ) {
  9781. node = sheenNode.mul( this.getTexture( 'sheenColor' ).rgb );
  9782. } else {
  9783. node = sheenNode;
  9784. }
  9785. } else if ( scope === MaterialNode.SHEEN_ROUGHNESS ) {
  9786. const sheenRoughnessNode = this.getFloat( scope );
  9787. if ( material.sheenRoughnessMap && material.sheenRoughnessMap.isTexture === true ) {
  9788. node = sheenRoughnessNode.mul( this.getTexture( scope ).a );
  9789. } else {
  9790. node = sheenRoughnessNode;
  9791. }
  9792. node = node.clamp( 0.07, 1.0 );
  9793. } else if ( scope === MaterialNode.ANISOTROPY ) {
  9794. if ( material.anisotropyMap && material.anisotropyMap.isTexture === true ) {
  9795. const anisotropyPolar = this.getTexture( scope );
  9796. const anisotropyMat = mat2( materialAnisotropyVector.x, materialAnisotropyVector.y, materialAnisotropyVector.y.negate(), materialAnisotropyVector.x );
  9797. node = anisotropyMat.mul( anisotropyPolar.rg.mul( 2.0 ).sub( vec2( 1.0 ) ).normalize().mul( anisotropyPolar.b ) );
  9798. } else {
  9799. node = materialAnisotropyVector;
  9800. }
  9801. } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) {
  9802. const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange );
  9803. if ( material.iridescenceThicknessMap ) {
  9804. const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange );
  9805. node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum );
  9806. } else {
  9807. node = iridescenceThicknessMaximum;
  9808. }
  9809. } else if ( scope === MaterialNode.TRANSMISSION ) {
  9810. const transmissionNode = this.getFloat( scope );
  9811. if ( material.transmissionMap ) {
  9812. node = transmissionNode.mul( this.getTexture( scope ).r );
  9813. } else {
  9814. node = transmissionNode;
  9815. }
  9816. } else if ( scope === MaterialNode.THICKNESS ) {
  9817. const thicknessNode = this.getFloat( scope );
  9818. if ( material.thicknessMap ) {
  9819. node = thicknessNode.mul( this.getTexture( scope ).g );
  9820. } else {
  9821. node = thicknessNode;
  9822. }
  9823. } else if ( scope === MaterialNode.IOR ) {
  9824. node = this.getFloat( scope );
  9825. } else if ( scope === MaterialNode.LIGHT_MAP ) {
  9826. node = this.getTexture( scope ).rgb.mul( this.getFloat( 'lightMapIntensity' ) );
  9827. } else if ( scope === MaterialNode.AO ) {
  9828. node = this.getTexture( scope ).r.sub( 1.0 ).mul( this.getFloat( 'aoMapIntensity' ) ).add( 1.0 );
  9829. } else if ( scope === MaterialNode.LINE_DASH_OFFSET ) {
  9830. node = ( material.dashOffset ) ? this.getFloat( scope ) : float( 0 );
  9831. } else {
  9832. const outputType = this.getNodeType( builder );
  9833. node = this.getCache( scope, outputType );
  9834. }
  9835. return node;
  9836. }
  9837. }
  9838. MaterialNode.ALPHA_TEST = 'alphaTest';
  9839. MaterialNode.COLOR = 'color';
  9840. MaterialNode.OPACITY = 'opacity';
  9841. MaterialNode.SHININESS = 'shininess';
  9842. MaterialNode.SPECULAR = 'specular';
  9843. MaterialNode.SPECULAR_STRENGTH = 'specularStrength';
  9844. MaterialNode.SPECULAR_INTENSITY = 'specularIntensity';
  9845. MaterialNode.SPECULAR_COLOR = 'specularColor';
  9846. MaterialNode.REFLECTIVITY = 'reflectivity';
  9847. MaterialNode.ROUGHNESS = 'roughness';
  9848. MaterialNode.METALNESS = 'metalness';
  9849. MaterialNode.NORMAL = 'normal';
  9850. MaterialNode.CLEARCOAT = 'clearcoat';
  9851. MaterialNode.CLEARCOAT_ROUGHNESS = 'clearcoatRoughness';
  9852. MaterialNode.CLEARCOAT_NORMAL = 'clearcoatNormal';
  9853. MaterialNode.EMISSIVE = 'emissive';
  9854. MaterialNode.ROTATION = 'rotation';
  9855. MaterialNode.SHEEN = 'sheen';
  9856. MaterialNode.SHEEN_ROUGHNESS = 'sheenRoughness';
  9857. MaterialNode.ANISOTROPY = 'anisotropy';
  9858. MaterialNode.IRIDESCENCE = 'iridescence';
  9859. MaterialNode.IRIDESCENCE_IOR = 'iridescenceIOR';
  9860. MaterialNode.IRIDESCENCE_THICKNESS = 'iridescenceThickness';
  9861. MaterialNode.IOR = 'ior';
  9862. MaterialNode.TRANSMISSION = 'transmission';
  9863. MaterialNode.THICKNESS = 'thickness';
  9864. MaterialNode.ATTENUATION_DISTANCE = 'attenuationDistance';
  9865. MaterialNode.ATTENUATION_COLOR = 'attenuationColor';
  9866. MaterialNode.LINE_SCALE = 'scale';
  9867. MaterialNode.LINE_DASH_SIZE = 'dashSize';
  9868. MaterialNode.LINE_GAP_SIZE = 'gapSize';
  9869. MaterialNode.LINE_WIDTH = 'linewidth';
  9870. MaterialNode.LINE_DASH_OFFSET = 'dashOffset';
  9871. MaterialNode.POINT_SIZE = 'size';
  9872. MaterialNode.DISPERSION = 'dispersion';
  9873. MaterialNode.LIGHT_MAP = 'light';
  9874. MaterialNode.AO = 'ao';
  9875. /**
  9876. * TSL object that represents alpha test of the current material.
  9877. *
  9878. * @tsl
  9879. * @type {Node<float>}
  9880. */
  9881. const materialAlphaTest = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ALPHA_TEST );
  9882. /**
  9883. * TSL object that represents the diffuse color of the current material.
  9884. * The value is composed via `color` * `map`.
  9885. *
  9886. * @tsl
  9887. * @type {Node<vec3>}
  9888. */
  9889. const materialColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.COLOR );
  9890. /**
  9891. * TSL object that represents the shininess of the current material.
  9892. *
  9893. * @tsl
  9894. * @type {Node<float>}
  9895. */
  9896. const materialShininess = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHININESS );
  9897. /**
  9898. * TSL object that represents the emissive color of the current material.
  9899. * The value is composed via `emissive` * `emissiveIntensity` * `emissiveMap`.
  9900. *
  9901. * @tsl
  9902. * @type {Node<vec3>}
  9903. */
  9904. const materialEmissive = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.EMISSIVE );
  9905. /**
  9906. * TSL object that represents the opacity of the current material.
  9907. * The value is composed via `opacity` * `alphaMap`.
  9908. *
  9909. * @tsl
  9910. * @type {Node<float>}
  9911. */
  9912. const materialOpacity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.OPACITY );
  9913. /**
  9914. * TSL object that represents the specular of the current material.
  9915. *
  9916. * @tsl
  9917. * @type {Node<vec3>}
  9918. */
  9919. const materialSpecular = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR );
  9920. /**
  9921. * TSL object that represents the specular intensity of the current material.
  9922. * The value is composed via `specularIntensity` * `specularMap.a`.
  9923. *
  9924. * @tsl
  9925. * @type {Node<float>}
  9926. */
  9927. const materialSpecularIntensity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_INTENSITY );
  9928. /**
  9929. * TSL object that represents the specular color of the current material.
  9930. * The value is composed via `specularColor` * `specularMap.rgb`.
  9931. *
  9932. * @tsl
  9933. * @type {Node<vec3>}
  9934. */
  9935. const materialSpecularColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_COLOR );
  9936. /**
  9937. * TSL object that represents the specular strength of the current material.
  9938. * The value is composed via `specularMap.r`.
  9939. *
  9940. * @tsl
  9941. * @type {Node<float>}
  9942. */
  9943. const materialSpecularStrength = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_STRENGTH );
  9944. /**
  9945. * TSL object that represents the reflectivity of the current material.
  9946. *
  9947. * @tsl
  9948. * @type {Node<float>}
  9949. */
  9950. const materialReflectivity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.REFLECTIVITY );
  9951. /**
  9952. * TSL object that represents the roughness of the current material.
  9953. * The value is composed via `roughness` * `roughnessMap.g`.
  9954. *
  9955. * @tsl
  9956. * @type {Node<float>}
  9957. */
  9958. const materialRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROUGHNESS );
  9959. /**
  9960. * TSL object that represents the metalness of the current material.
  9961. * The value is composed via `metalness` * `metalnessMap.b`.
  9962. *
  9963. * @tsl
  9964. * @type {Node<float>}
  9965. */
  9966. const materialMetalness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.METALNESS );
  9967. /**
  9968. * TSL object that represents the normal of the current material.
  9969. * The value will be either `normalMap` * `normalScale`, `bumpMap` * `bumpScale` or `normalView`.
  9970. *
  9971. * @tsl
  9972. * @type {Node<vec3>}
  9973. */
  9974. const materialNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.NORMAL );
  9975. /**
  9976. * TSL object that represents the clearcoat of the current material.
  9977. * The value is composed via `clearcoat` * `clearcoatMap.r`
  9978. *
  9979. * @tsl
  9980. * @type {Node<float>}
  9981. */
  9982. const materialClearcoat = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT );
  9983. /**
  9984. * TSL object that represents the clearcoat roughness of the current material.
  9985. * The value is composed via `clearcoatRoughness` * `clearcoatRoughnessMap.r`.
  9986. *
  9987. * @tsl
  9988. * @type {Node<float>}
  9989. */
  9990. const materialClearcoatRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_ROUGHNESS );
  9991. /**
  9992. * TSL object that represents the clearcoat normal of the current material.
  9993. * The value will be either `clearcoatNormalMap` or `normalView`.
  9994. *
  9995. * @tsl
  9996. * @type {Node<vec3>}
  9997. */
  9998. const materialClearcoatNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_NORMAL );
  9999. /**
  10000. * TSL object that represents the rotation of the current sprite material.
  10001. *
  10002. * @tsl
  10003. * @type {Node<float>}
  10004. */
  10005. const materialRotation = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROTATION );
  10006. /**
  10007. * TSL object that represents the sheen color of the current material.
  10008. * The value is composed via `sheen` * `sheenColor` * `sheenColorMap`.
  10009. *
  10010. * @tsl
  10011. * @type {Node<vec3>}
  10012. */
  10013. const materialSheen = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN );
  10014. /**
  10015. * TSL object that represents the sheen roughness of the current material.
  10016. * The value is composed via `sheenRoughness` * `sheenRoughnessMap.a`.
  10017. *
  10018. * @tsl
  10019. * @type {Node<float>}
  10020. */
  10021. const materialSheenRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN_ROUGHNESS );
  10022. /**
  10023. * TSL object that represents the anisotropy of the current material.
  10024. *
  10025. * @tsl
  10026. * @type {Node<vec2>}
  10027. */
  10028. const materialAnisotropy = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ANISOTROPY );
  10029. /**
  10030. * TSL object that represents the iridescence of the current material.
  10031. *
  10032. * @tsl
  10033. * @type {Node<float>}
  10034. */
  10035. const materialIridescence = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE );
  10036. /**
  10037. * TSL object that represents the iridescence IOR of the current material.
  10038. *
  10039. * @tsl
  10040. * @type {Node<float>}
  10041. */
  10042. const materialIridescenceIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_IOR );
  10043. /**
  10044. * TSL object that represents the iridescence thickness of the current material.
  10045. *
  10046. * @tsl
  10047. * @type {Node<float>}
  10048. */
  10049. const materialIridescenceThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_THICKNESS );
  10050. /**
  10051. * TSL object that represents the transmission of the current material.
  10052. * The value is composed via `transmission` * `transmissionMap.r`.
  10053. *
  10054. * @tsl
  10055. * @type {Node<float>}
  10056. */
  10057. const materialTransmission = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.TRANSMISSION );
  10058. /**
  10059. * TSL object that represents the thickness of the current material.
  10060. * The value is composed via `thickness` * `thicknessMap.g`.
  10061. *
  10062. * @tsl
  10063. * @type {Node<float>}
  10064. */
  10065. const materialThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.THICKNESS );
  10066. /**
  10067. * TSL object that represents the IOR of the current material.
  10068. *
  10069. * @tsl
  10070. * @type {Node<float>}
  10071. */
  10072. const materialIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IOR );
  10073. /**
  10074. * TSL object that represents the attenuation distance of the current material.
  10075. *
  10076. * @tsl
  10077. * @type {Node<float>}
  10078. */
  10079. const materialAttenuationDistance = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_DISTANCE );
  10080. /**
  10081. * TSL object that represents the attenuation color of the current material.
  10082. *
  10083. * @tsl
  10084. * @type {Node<vec3>}
  10085. */
  10086. const materialAttenuationColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_COLOR );
  10087. /**
  10088. * TSL object that represents the scale of the current dashed line material.
  10089. *
  10090. * @tsl
  10091. * @type {Node<float>}
  10092. */
  10093. const materialLineScale = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_SCALE );
  10094. /**
  10095. * TSL object that represents the dash size of the current dashed line material.
  10096. *
  10097. * @tsl
  10098. * @type {Node<float>}
  10099. */
  10100. const materialLineDashSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_SIZE );
  10101. /**
  10102. * TSL object that represents the gap size of the current dashed line material.
  10103. *
  10104. * @tsl
  10105. * @type {Node<float>}
  10106. */
  10107. const materialLineGapSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_GAP_SIZE );
  10108. /**
  10109. * TSL object that represents the line width of the current line material.
  10110. *
  10111. * @tsl
  10112. * @type {Node<float>}
  10113. */
  10114. const materialLineWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_WIDTH );
  10115. /**
  10116. * TSL object that represents the dash offset of the current line material.
  10117. *
  10118. * @tsl
  10119. * @type {Node<float>}
  10120. */
  10121. const materialLineDashOffset = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_OFFSET );
  10122. /**
  10123. * TSL object that represents the point size of the current points material.
  10124. *
  10125. * @tsl
  10126. * @type {Node<float>}
  10127. */
  10128. const materialPointSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.POINT_SIZE );
  10129. /**
  10130. * TSL object that represents the dispersion of the current material.
  10131. *
  10132. * @tsl
  10133. * @type {Node<float>}
  10134. */
  10135. const materialDispersion = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.DISPERSION );
  10136. /**
  10137. * TSL object that represents the light map of the current material.
  10138. * The value is composed via `lightMapIntensity` * `lightMap.rgb`.
  10139. *
  10140. * @tsl
  10141. * @type {Node<vec3>}
  10142. */
  10143. const materialLightMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LIGHT_MAP );
  10144. /**
  10145. * TSL object that represents the ambient occlusion map of the current material.
  10146. * The value is composed via `aoMap.r` - 1 * `aoMapIntensity` + 1.
  10147. *
  10148. * @tsl
  10149. * @type {Node<float>}
  10150. */
  10151. const materialAO = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.AO );
  10152. /**
  10153. * TSL object that represents the anisotropy vector of the current material.
  10154. *
  10155. * @tsl
  10156. * @type {Node<vec2>}
  10157. */
  10158. const materialAnisotropyVector = /*@__PURE__*/ uniform( new Vector2() ).onReference( function ( frame ) {
  10159. return frame.material;
  10160. } ).onRenderUpdate( function ( { material } ) {
  10161. this.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  10162. } );
  10163. /**
  10164. * TSL object that represents the position in clip space after the model-view-projection transform of the current rendered object.
  10165. *
  10166. * @tsl
  10167. * @type {VaryingNode<vec4>}
  10168. */
  10169. const modelViewProjection = /*@__PURE__*/ ( Fn( ( builder ) => {
  10170. return builder.context.setupModelViewProjection();
  10171. }, 'vec4' ).once() )().toVarying( 'v_modelViewProjection' );
  10172. /**
  10173. * This class represents shader indices of different types. The following predefined node
  10174. * objects cover frequent use cases:
  10175. *
  10176. * - `vertexIndex`: The index of a vertex within a mesh.
  10177. * - `instanceIndex`: The index of either a mesh instance or an invocation of a compute shader.
  10178. * - `drawIndex`: The index of a draw call.
  10179. * - `invocationLocalIndex`: The index of a compute invocation within the scope of a workgroup load.
  10180. * - `invocationSubgroupIndex`: The index of a compute invocation within the scope of a subgroup.
  10181. * - `subgroupIndex`: The index of the subgroup the current compute invocation belongs to.
  10182. *
  10183. * @augments Node
  10184. */
  10185. class IndexNode extends Node {
  10186. static get type() {
  10187. return 'IndexNode';
  10188. }
  10189. /**
  10190. * Constructs a new index node.
  10191. *
  10192. * @param {('vertex'|'instance'|'subgroup'|'invocationLocal'|'invocationSubgroup'|'draw')} scope - The scope of the index node.
  10193. */
  10194. constructor( scope ) {
  10195. super( 'uint' );
  10196. /**
  10197. * The scope of the index node.
  10198. *
  10199. * @type {string}
  10200. */
  10201. this.scope = scope;
  10202. /**
  10203. * This flag can be used for type testing.
  10204. *
  10205. * @type {boolean}
  10206. * @readonly
  10207. * @default true
  10208. */
  10209. this.isIndexNode = true;
  10210. }
  10211. generate( builder ) {
  10212. const nodeType = this.getNodeType( builder );
  10213. const scope = this.scope;
  10214. let propertyName;
  10215. if ( scope === IndexNode.VERTEX ) {
  10216. propertyName = builder.getVertexIndex();
  10217. } else if ( scope === IndexNode.INSTANCE ) {
  10218. propertyName = builder.getInstanceIndex();
  10219. } else if ( scope === IndexNode.DRAW ) {
  10220. propertyName = builder.getDrawIndex();
  10221. } else if ( scope === IndexNode.INVOCATION_LOCAL ) {
  10222. propertyName = builder.getInvocationLocalIndex();
  10223. } else if ( scope === IndexNode.INVOCATION_SUBGROUP ) {
  10224. propertyName = builder.getInvocationSubgroupIndex();
  10225. } else if ( scope === IndexNode.SUBGROUP ) {
  10226. propertyName = builder.getSubgroupIndex();
  10227. } else {
  10228. throw new Error( 'THREE.IndexNode: Unknown scope: ' + scope );
  10229. }
  10230. let output;
  10231. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  10232. output = propertyName;
  10233. } else {
  10234. const nodeVarying = varying( this );
  10235. output = nodeVarying.build( builder, nodeType );
  10236. }
  10237. return output;
  10238. }
  10239. }
  10240. IndexNode.VERTEX = 'vertex';
  10241. IndexNode.INSTANCE = 'instance';
  10242. IndexNode.SUBGROUP = 'subgroup';
  10243. IndexNode.INVOCATION_LOCAL = 'invocationLocal';
  10244. IndexNode.INVOCATION_SUBGROUP = 'invocationSubgroup';
  10245. IndexNode.DRAW = 'draw';
  10246. /**
  10247. * TSL object that represents the index of a vertex within a mesh.
  10248. *
  10249. * @tsl
  10250. * @type {IndexNode}
  10251. */
  10252. const vertexIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.VERTEX );
  10253. /**
  10254. * TSL object that represents the index of either a mesh instance or an invocation of a compute shader.
  10255. *
  10256. * @tsl
  10257. * @type {IndexNode}
  10258. */
  10259. const instanceIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INSTANCE );
  10260. /**
  10261. * TSL object that represents the index of the subgroup the current compute invocation belongs to.
  10262. *
  10263. * @tsl
  10264. * @type {IndexNode}
  10265. */
  10266. const subgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.SUBGROUP );
  10267. /**
  10268. * TSL object that represents the index of a compute invocation within the scope of a subgroup.
  10269. *
  10270. * @tsl
  10271. * @type {IndexNode}
  10272. */
  10273. const invocationSubgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_SUBGROUP );
  10274. /**
  10275. * TSL object that represents the index of a compute invocation within the scope of a workgroup load.
  10276. *
  10277. * @tsl
  10278. * @type {IndexNode}
  10279. */
  10280. const invocationLocalIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_LOCAL );
  10281. /**
  10282. * TSL object that represents the index of a draw call.
  10283. *
  10284. * @tsl
  10285. * @type {IndexNode}
  10286. */
  10287. const drawIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.DRAW );
  10288. /**
  10289. * This node implements the vertex shader logic which is required
  10290. * when rendering 3D objects via instancing. The code makes sure
  10291. * vertex positions, normals and colors can be modified via instanced
  10292. * data.
  10293. *
  10294. * @augments Node
  10295. */
  10296. class InstanceNode extends Node {
  10297. static get type() {
  10298. return 'InstanceNode';
  10299. }
  10300. /**
  10301. * Constructs a new instance node.
  10302. *
  10303. * @param {number} count - The number of instances.
  10304. * @param {InstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  10305. * @param {?InstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  10306. */
  10307. constructor( count, instanceMatrix, instanceColor = null ) {
  10308. super( 'void' );
  10309. /**
  10310. * The number of instances.
  10311. *
  10312. * @type {number}
  10313. */
  10314. this.count = count;
  10315. /**
  10316. * Instanced buffer attribute representing the transformation of instances.
  10317. *
  10318. * @type {InstancedBufferAttribute}
  10319. */
  10320. this.instanceMatrix = instanceMatrix;
  10321. /**
  10322. * Instanced buffer attribute representing the color of instances.
  10323. *
  10324. * @type {InstancedBufferAttribute}
  10325. */
  10326. this.instanceColor = instanceColor;
  10327. /**
  10328. * The node that represents the instance matrix data.
  10329. *
  10330. * @type {?Node}
  10331. */
  10332. this.instanceMatrixNode = null;
  10333. /**
  10334. * The node that represents the instance color data.
  10335. *
  10336. * @type {?Node}
  10337. * @default null
  10338. */
  10339. this.instanceColorNode = null;
  10340. /**
  10341. * The update type is set to `frame` since an update
  10342. * of instanced buffer data must be checked per frame.
  10343. *
  10344. * @type {string}
  10345. * @default 'frame'
  10346. */
  10347. this.updateType = NodeUpdateType.FRAME;
  10348. /**
  10349. * A reference to a buffer that is used by `instanceMatrixNode`.
  10350. *
  10351. * @type {?InstancedInterleavedBuffer}
  10352. */
  10353. this.buffer = null;
  10354. /**
  10355. * A reference to a buffer that is used by `instanceColorNode`.
  10356. *
  10357. * @type {?InstancedBufferAttribute}
  10358. */
  10359. this.bufferColor = null;
  10360. }
  10361. /**
  10362. * Setups the internal buffers and nodes and assigns the transformed vertex data
  10363. * to predefined node variables for accumulation. That follows the same patterns
  10364. * like with morph and skinning nodes.
  10365. *
  10366. * @param {NodeBuilder} builder - The current node builder.
  10367. */
  10368. setup( builder ) {
  10369. const { count, instanceMatrix, instanceColor } = this;
  10370. let { instanceMatrixNode, instanceColorNode } = this;
  10371. if ( instanceMatrixNode === null ) {
  10372. // 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.
  10373. if ( count <= 1000 ) {
  10374. instanceMatrixNode = buffer( instanceMatrix.array, 'mat4', Math.max( count, 1 ) ).element( instanceIndex );
  10375. } else {
  10376. const buffer = new InstancedInterleavedBuffer( instanceMatrix.array, 16, 1 );
  10377. this.buffer = buffer;
  10378. const bufferFn = instanceMatrix.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  10379. const instanceBuffers = [
  10380. // F.Signature -> bufferAttribute( array, type, stride, offset )
  10381. bufferFn( buffer, 'vec4', 16, 0 ),
  10382. bufferFn( buffer, 'vec4', 16, 4 ),
  10383. bufferFn( buffer, 'vec4', 16, 8 ),
  10384. bufferFn( buffer, 'vec4', 16, 12 )
  10385. ];
  10386. instanceMatrixNode = mat4( ...instanceBuffers );
  10387. }
  10388. this.instanceMatrixNode = instanceMatrixNode;
  10389. }
  10390. if ( instanceColor && instanceColorNode === null ) {
  10391. const buffer = new InstancedBufferAttribute( instanceColor.array, 3 );
  10392. const bufferFn = instanceColor.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  10393. this.bufferColor = buffer;
  10394. instanceColorNode = vec3( bufferFn( buffer, 'vec3', 3, 0 ) );
  10395. this.instanceColorNode = instanceColorNode;
  10396. }
  10397. // POSITION
  10398. const instancePosition = instanceMatrixNode.mul( positionLocal ).xyz;
  10399. positionLocal.assign( instancePosition );
  10400. // NORMAL
  10401. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  10402. const instanceNormal = transformNormal( normalLocal, instanceMatrixNode );
  10403. // ASSIGNS
  10404. normalLocal.assign( instanceNormal );
  10405. }
  10406. // COLOR
  10407. if ( this.instanceColorNode !== null ) {
  10408. varyingProperty( 'vec3', 'vInstanceColor' ).assign( this.instanceColorNode );
  10409. }
  10410. }
  10411. /**
  10412. * Checks if the internal buffers required an update.
  10413. *
  10414. * @param {NodeFrame} frame - The current node frame.
  10415. */
  10416. update( /*frame*/ ) {
  10417. if ( this.instanceMatrix.usage !== DynamicDrawUsage && this.buffer !== null && this.instanceMatrix.version !== this.buffer.version ) {
  10418. this.buffer.version = this.instanceMatrix.version;
  10419. }
  10420. if ( this.instanceColor && this.instanceColor.usage !== DynamicDrawUsage && this.bufferColor !== null && this.instanceColor.version !== this.bufferColor.version ) {
  10421. this.bufferColor.version = this.instanceColor.version;
  10422. }
  10423. }
  10424. }
  10425. /**
  10426. * TSL function for creating an instance node.
  10427. *
  10428. * @tsl
  10429. * @function
  10430. * @param {number} count - The number of instances.
  10431. * @param {InstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  10432. * @param {?InstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  10433. * @returns {InstanceNode}
  10434. */
  10435. const instance = /*@__PURE__*/ nodeProxy( InstanceNode ).setParameterLength( 2, 3 );
  10436. /**
  10437. * This is a special version of `InstanceNode` which requires the usage of {@link InstancedMesh}.
  10438. * It allows an easier setup of the instance node.
  10439. *
  10440. * @augments InstanceNode
  10441. */
  10442. class InstancedMeshNode extends InstanceNode {
  10443. static get type() {
  10444. return 'InstancedMeshNode';
  10445. }
  10446. /**
  10447. * Constructs a new instanced mesh node.
  10448. *
  10449. * @param {InstancedMesh} instancedMesh - The instanced mesh.
  10450. */
  10451. constructor( instancedMesh ) {
  10452. const { count, instanceMatrix, instanceColor } = instancedMesh;
  10453. super( count, instanceMatrix, instanceColor );
  10454. /**
  10455. * A reference to the instanced mesh.
  10456. *
  10457. * @type {InstancedMesh}
  10458. */
  10459. this.instancedMesh = instancedMesh;
  10460. }
  10461. }
  10462. /**
  10463. * TSL function for creating an instanced mesh node.
  10464. *
  10465. * @tsl
  10466. * @function
  10467. * @param {InstancedMesh} instancedMesh - The instancedMesh.
  10468. * @returns {InstancedMeshNode}
  10469. */
  10470. const instancedMesh = /*@__PURE__*/ nodeProxy( InstancedMeshNode ).setParameterLength( 1 );
  10471. /**
  10472. * This node implements the vertex shader logic which is required
  10473. * when rendering 3D objects via batching. `BatchNode` must be used
  10474. * with instances of {@link BatchedMesh}.
  10475. *
  10476. * @augments Node
  10477. */
  10478. class BatchNode extends Node {
  10479. static get type() {
  10480. return 'BatchNode';
  10481. }
  10482. /**
  10483. * Constructs a new batch node.
  10484. *
  10485. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  10486. */
  10487. constructor( batchMesh ) {
  10488. super( 'void' );
  10489. /**
  10490. * A reference to batched mesh.
  10491. *
  10492. * @type {BatchedMesh}
  10493. */
  10494. this.batchMesh = batchMesh;
  10495. /**
  10496. * The batching index node.
  10497. *
  10498. * @type {?IndexNode}
  10499. * @default null
  10500. */
  10501. this.batchingIdNode = null;
  10502. }
  10503. /**
  10504. * Setups the internal buffers and nodes and assigns the transformed vertex data
  10505. * to predefined node variables for accumulation. That follows the same patterns
  10506. * like with morph and skinning nodes.
  10507. *
  10508. * @param {NodeBuilder} builder - The current node builder.
  10509. */
  10510. setup( builder ) {
  10511. if ( this.batchingIdNode === null ) {
  10512. if ( builder.getDrawIndex() === null ) {
  10513. this.batchingIdNode = instanceIndex;
  10514. } else {
  10515. this.batchingIdNode = drawIndex;
  10516. }
  10517. }
  10518. const getIndirectIndex = Fn( ( [ id ] ) => {
  10519. const size = int( textureSize( textureLoad( this.batchMesh._indirectTexture ), 0 ).x );
  10520. const x = int( id ).mod( size );
  10521. const y = int( id ).div( size );
  10522. return textureLoad( this.batchMesh._indirectTexture, ivec2( x, y ) ).x;
  10523. } ).setLayout( {
  10524. name: 'getIndirectIndex',
  10525. type: 'uint',
  10526. inputs: [
  10527. { name: 'id', type: 'int' }
  10528. ]
  10529. } );
  10530. const indirectId = getIndirectIndex( int( this.batchingIdNode ) );
  10531. const matricesTexture = this.batchMesh._matricesTexture;
  10532. const size = int( textureSize( textureLoad( matricesTexture ), 0 ).x );
  10533. const j = float( indirectId ).mul( 4 ).toInt().toVar();
  10534. const x = j.mod( size );
  10535. const y = j.div( size );
  10536. const batchingMatrix = mat4(
  10537. textureLoad( matricesTexture, ivec2( x, y ) ),
  10538. textureLoad( matricesTexture, ivec2( x.add( 1 ), y ) ),
  10539. textureLoad( matricesTexture, ivec2( x.add( 2 ), y ) ),
  10540. textureLoad( matricesTexture, ivec2( x.add( 3 ), y ) )
  10541. );
  10542. const colorsTexture = this.batchMesh._colorsTexture;
  10543. if ( colorsTexture !== null ) {
  10544. const getBatchingColor = Fn( ( [ id ] ) => {
  10545. const size = int( textureSize( textureLoad( colorsTexture ), 0 ).x );
  10546. const j = id;
  10547. const x = j.mod( size );
  10548. const y = j.div( size );
  10549. return textureLoad( colorsTexture, ivec2( x, y ) ).rgb;
  10550. } ).setLayout( {
  10551. name: 'getBatchingColor',
  10552. type: 'vec3',
  10553. inputs: [
  10554. { name: 'id', type: 'int' }
  10555. ]
  10556. } );
  10557. const color = getBatchingColor( indirectId );
  10558. varyingProperty( 'vec3', 'vBatchColor' ).assign( color );
  10559. }
  10560. const bm = mat3( batchingMatrix );
  10561. positionLocal.assign( batchingMatrix.mul( positionLocal ) );
  10562. const transformedNormal = normalLocal.div( vec3( bm[ 0 ].dot( bm[ 0 ] ), bm[ 1 ].dot( bm[ 1 ] ), bm[ 2 ].dot( bm[ 2 ] ) ) );
  10563. const batchingNormal = bm.mul( transformedNormal ).xyz;
  10564. normalLocal.assign( batchingNormal );
  10565. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  10566. tangentLocal.mulAssign( bm );
  10567. }
  10568. }
  10569. }
  10570. /**
  10571. * TSL function for creating a batch node.
  10572. *
  10573. * @tsl
  10574. * @function
  10575. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  10576. * @returns {BatchNode}
  10577. */
  10578. const batch = /*@__PURE__*/ nodeProxy( BatchNode ).setParameterLength( 1 );
  10579. /**
  10580. * This class enables element access on instances of {@link StorageBufferNode}.
  10581. * In most cases, it is indirectly used when accessing elements with the
  10582. * {@link StorageBufferNode#element} method.
  10583. *
  10584. * ```js
  10585. * const position = positionStorage.element( instanceIndex );
  10586. * ```
  10587. *
  10588. * @augments ArrayElementNode
  10589. */
  10590. class StorageArrayElementNode extends ArrayElementNode {
  10591. static get type() {
  10592. return 'StorageArrayElementNode';
  10593. }
  10594. /**
  10595. * Constructs storage buffer element node.
  10596. *
  10597. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  10598. * @param {Node} indexNode - The index node that defines the element access.
  10599. */
  10600. constructor( storageBufferNode, indexNode ) {
  10601. super( storageBufferNode, indexNode );
  10602. /**
  10603. * This flag can be used for type testing.
  10604. *
  10605. * @type {boolean}
  10606. * @readonly
  10607. * @default true
  10608. */
  10609. this.isStorageArrayElementNode = true;
  10610. }
  10611. /**
  10612. * The storage buffer node.
  10613. *
  10614. * @param {Node} value
  10615. * @type {StorageBufferNode}
  10616. */
  10617. set storageBufferNode( value ) {
  10618. this.node = value;
  10619. }
  10620. get storageBufferNode() {
  10621. return this.node;
  10622. }
  10623. getMemberType( builder, name ) {
  10624. const structTypeNode = this.storageBufferNode.structTypeNode;
  10625. if ( structTypeNode ) {
  10626. return structTypeNode.getMemberType( builder, name );
  10627. }
  10628. return 'void';
  10629. }
  10630. setup( builder ) {
  10631. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  10632. if ( this.node.isPBO === true ) {
  10633. builder.setupPBO( this.node );
  10634. }
  10635. }
  10636. return super.setup( builder );
  10637. }
  10638. generate( builder, output ) {
  10639. let snippet;
  10640. const isAssignContext = builder.context.assign;
  10641. //
  10642. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  10643. if ( this.node.isPBO === true && isAssignContext !== true && ( this.node.value.isInstancedBufferAttribute || builder.shaderStage !== 'compute' ) ) {
  10644. snippet = builder.generatePBO( this );
  10645. } else {
  10646. snippet = this.node.build( builder );
  10647. }
  10648. } else {
  10649. snippet = super.generate( builder );
  10650. }
  10651. if ( isAssignContext !== true ) {
  10652. const type = this.getNodeType( builder );
  10653. snippet = builder.format( snippet, type, output );
  10654. }
  10655. return snippet;
  10656. }
  10657. }
  10658. /**
  10659. * TSL function for creating a storage element node.
  10660. *
  10661. * @tsl
  10662. * @function
  10663. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  10664. * @param {Node} indexNode - The index node that defines the element access.
  10665. * @returns {StorageArrayElementNode}
  10666. */
  10667. const storageElement = /*@__PURE__*/ nodeProxy( StorageArrayElementNode ).setParameterLength( 2 );
  10668. /**
  10669. * This node is used in context of compute shaders and allows to define a
  10670. * storage buffer for data. A typical workflow is to create instances of
  10671. * this node with the convenience functions `attributeArray()` or `instancedArray()`,
  10672. * setup up a compute shader that writes into the buffers and then convert
  10673. * the storage buffers to attribute nodes for rendering.
  10674. *
  10675. * ```js
  10676. * const positionBuffer = instancedArray( particleCount, 'vec3' ); // the storage buffer node
  10677. *
  10678. * const computeInit = Fn( () => { // the compute shader
  10679. *
  10680. * const position = positionBuffer.element( instanceIndex );
  10681. *
  10682. * // compute position data
  10683. *
  10684. * position.x = 1;
  10685. * position.y = 1;
  10686. * position.z = 1;
  10687. *
  10688. * } )().compute( particleCount );
  10689. *
  10690. * const particleMaterial = new THREE.SpriteNodeMaterial();
  10691. * particleMaterial.positionNode = positionBuffer.toAttribute();
  10692. *
  10693. * renderer.computeAsync( computeInit );
  10694. *
  10695. * ```
  10696. *
  10697. * @augments BufferNode
  10698. */
  10699. class StorageBufferNode extends BufferNode {
  10700. static get type() {
  10701. return 'StorageBufferNode';
  10702. }
  10703. /**
  10704. * Constructs a new storage buffer node.
  10705. *
  10706. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  10707. * @param {?(string|Struct)} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  10708. * @param {number} [bufferCount=0] - The buffer count.
  10709. */
  10710. constructor( value, bufferType = null, bufferCount = 0 ) {
  10711. let nodeType, structTypeNode = null;
  10712. if ( bufferType && bufferType.isStruct ) {
  10713. nodeType = 'struct';
  10714. structTypeNode = bufferType.layout;
  10715. if ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) {
  10716. bufferCount = value.count;
  10717. }
  10718. } else if ( bufferType === null && ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) ) {
  10719. nodeType = getTypeFromLength( value.itemSize );
  10720. bufferCount = value.count;
  10721. } else {
  10722. nodeType = bufferType;
  10723. }
  10724. super( value, nodeType, bufferCount );
  10725. /**
  10726. * This flag can be used for type testing.
  10727. *
  10728. * @type {boolean}
  10729. * @readonly
  10730. * @default true
  10731. */
  10732. this.isStorageBufferNode = true;
  10733. /**
  10734. * The buffer struct type.
  10735. *
  10736. * @type {?StructTypeNode}
  10737. * @default null
  10738. */
  10739. this.structTypeNode = structTypeNode;
  10740. /**
  10741. * The access type of the texture node.
  10742. *
  10743. * @type {string}
  10744. * @default 'readWrite'
  10745. */
  10746. this.access = NodeAccess.READ_WRITE;
  10747. /**
  10748. * Whether the node is atomic or not.
  10749. *
  10750. * @type {boolean}
  10751. * @default false
  10752. */
  10753. this.isAtomic = false;
  10754. /**
  10755. * Whether the node represents a PBO or not.
  10756. * Only relevant for WebGL.
  10757. *
  10758. * @type {boolean}
  10759. * @default false
  10760. */
  10761. this.isPBO = false;
  10762. /**
  10763. * A reference to the internal buffer attribute node.
  10764. *
  10765. * @type {?BufferAttributeNode}
  10766. * @default null
  10767. */
  10768. this._attribute = null;
  10769. /**
  10770. * A reference to the internal varying node.
  10771. *
  10772. * @type {?VaryingNode}
  10773. * @default null
  10774. */
  10775. this._varying = null;
  10776. /**
  10777. * `StorageBufferNode` sets this property to `true` by default.
  10778. *
  10779. * @type {boolean}
  10780. * @default true
  10781. */
  10782. this.global = true;
  10783. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  10784. // TODO: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  10785. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  10786. else value.isStorageBufferAttribute = true;
  10787. }
  10788. }
  10789. /**
  10790. * This method is overwritten since the buffer data might be shared
  10791. * and thus the hash should be shared as well.
  10792. *
  10793. * @param {NodeBuilder} builder - The current node builder.
  10794. * @return {string} The hash.
  10795. */
  10796. getHash( builder ) {
  10797. if ( this.bufferCount === 0 ) {
  10798. let bufferData = builder.globalCache.getData( this.value );
  10799. if ( bufferData === undefined ) {
  10800. bufferData = {
  10801. node: this
  10802. };
  10803. builder.globalCache.setData( this.value, bufferData );
  10804. }
  10805. return bufferData.node.uuid;
  10806. }
  10807. return this.uuid;
  10808. }
  10809. /**
  10810. * Overwrites the default implementation to return a fixed value `'indirectStorageBuffer'` or `'storageBuffer'`.
  10811. *
  10812. * @param {NodeBuilder} builder - The current node builder.
  10813. * @return {string} The input type.
  10814. */
  10815. getInputType( /*builder*/ ) {
  10816. return this.value.isIndirectStorageBufferAttribute ? 'indirectStorageBuffer' : 'storageBuffer';
  10817. }
  10818. /**
  10819. * Enables element access with the given index node.
  10820. *
  10821. * @param {IndexNode} indexNode - The index node.
  10822. * @return {StorageArrayElementNode} A node representing the element access.
  10823. */
  10824. element( indexNode ) {
  10825. return storageElement( this, indexNode );
  10826. }
  10827. /**
  10828. * Defines whether this node is a PBO or not. Only relevant for WebGL.
  10829. *
  10830. * @param {boolean} value - The value so set.
  10831. * @return {StorageBufferNode} A reference to this node.
  10832. */
  10833. setPBO( value ) {
  10834. this.isPBO = value;
  10835. return this;
  10836. }
  10837. /**
  10838. * Returns the `isPBO` value.
  10839. *
  10840. * @return {boolean} Whether the node represents a PBO or not.
  10841. */
  10842. getPBO() {
  10843. return this.isPBO;
  10844. }
  10845. /**
  10846. * Defines the node access.
  10847. *
  10848. * @param {string} value - The node access.
  10849. * @return {StorageBufferNode} A reference to this node.
  10850. */
  10851. setAccess( value ) {
  10852. this.access = value;
  10853. return this;
  10854. }
  10855. /**
  10856. * Convenience method for configuring a read-only node access.
  10857. *
  10858. * @return {StorageBufferNode} A reference to this node.
  10859. */
  10860. toReadOnly() {
  10861. return this.setAccess( NodeAccess.READ_ONLY );
  10862. }
  10863. /**
  10864. * Defines whether the node is atomic or not.
  10865. *
  10866. * @param {boolean} value - The atomic flag.
  10867. * @return {StorageBufferNode} A reference to this node.
  10868. */
  10869. setAtomic( value ) {
  10870. this.isAtomic = value;
  10871. return this;
  10872. }
  10873. /**
  10874. * Convenience method for making this node atomic.
  10875. *
  10876. * @return {StorageBufferNode} A reference to this node.
  10877. */
  10878. toAtomic() {
  10879. return this.setAtomic( true );
  10880. }
  10881. /**
  10882. * Returns attribute data for this storage buffer node.
  10883. *
  10884. * @return {{attribute: BufferAttributeNode, varying: VaryingNode}} The attribute data.
  10885. */
  10886. getAttributeData() {
  10887. if ( this._attribute === null ) {
  10888. this._attribute = bufferAttribute( this.value );
  10889. this._varying = varying( this._attribute );
  10890. }
  10891. return {
  10892. attribute: this._attribute,
  10893. varying: this._varying
  10894. };
  10895. }
  10896. /**
  10897. * This method is overwritten since the node type from the availability of storage buffers
  10898. * and the attribute data.
  10899. *
  10900. * @param {NodeBuilder} builder - The current node builder.
  10901. * @return {string} The node type.
  10902. */
  10903. getNodeType( builder ) {
  10904. if ( this.structTypeNode !== null ) {
  10905. return this.structTypeNode.getNodeType( builder );
  10906. }
  10907. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  10908. return super.getNodeType( builder );
  10909. }
  10910. const { attribute } = this.getAttributeData();
  10911. return attribute.getNodeType( builder );
  10912. }
  10913. /**
  10914. * Returns the type of a member of the struct.
  10915. *
  10916. * @param {NodeBuilder} builder - The current node builder.
  10917. * @param {string} name - The name of the member.
  10918. * @return {string} The type of the member.
  10919. */
  10920. getMemberType( builder, name ) {
  10921. if ( this.structTypeNode !== null ) {
  10922. return this.structTypeNode.getMemberType( builder, name );
  10923. }
  10924. return 'void';
  10925. }
  10926. /**
  10927. * Generates the code snippet of the storage buffer node.
  10928. *
  10929. * @param {NodeBuilder} builder - The current node builder.
  10930. * @return {string} The generated code snippet.
  10931. */
  10932. generate( builder ) {
  10933. if ( this.structTypeNode !== null ) this.structTypeNode.build( builder );
  10934. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  10935. return super.generate( builder );
  10936. }
  10937. const { attribute, varying } = this.getAttributeData();
  10938. const output = varying.build( builder );
  10939. builder.registerTransform( output, attribute );
  10940. return output;
  10941. }
  10942. }
  10943. /**
  10944. * TSL function for creating a storage buffer node.
  10945. *
  10946. * @tsl
  10947. * @function
  10948. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  10949. * @param {?(string|Struct)} [type=null] - The buffer type (e.g. `'vec3'`).
  10950. * @param {number} [count=0] - The buffer count.
  10951. * @returns {StorageBufferNode}
  10952. */
  10953. const storage = ( value, type = null, count = 0 ) => nodeObject( new StorageBufferNode( value, type, count ) );
  10954. /**
  10955. * @tsl
  10956. * @function
  10957. * @deprecated since r171. Use `storage().setPBO( true )` instead.
  10958. *
  10959. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  10960. * @param {?string} type - The buffer type (e.g. `'vec3'`).
  10961. * @param {number} count - The buffer count.
  10962. * @returns {StorageBufferNode}
  10963. */
  10964. const storageObject = ( value, type, count ) => { // @deprecated, r171
  10965. console.warn( 'THREE.TSL: "storageObject()" is deprecated. Use "storage().setPBO( true )" instead.' );
  10966. return storage( value, type, count ).setPBO( true );
  10967. };
  10968. const _frameId = new WeakMap();
  10969. /**
  10970. * This node implements the vertex transformation shader logic which is required
  10971. * for skinning/skeletal animation.
  10972. *
  10973. * @augments Node
  10974. */
  10975. class SkinningNode extends Node {
  10976. static get type() {
  10977. return 'SkinningNode';
  10978. }
  10979. /**
  10980. * Constructs a new skinning node.
  10981. *
  10982. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  10983. */
  10984. constructor( skinnedMesh ) {
  10985. super( 'void' );
  10986. /**
  10987. * The skinned mesh.
  10988. *
  10989. * @type {SkinnedMesh}
  10990. */
  10991. this.skinnedMesh = skinnedMesh;
  10992. /**
  10993. * The update type overwritten since skinning nodes are updated per object.
  10994. *
  10995. * @type {string}
  10996. */
  10997. this.updateType = NodeUpdateType.OBJECT;
  10998. //
  10999. /**
  11000. * The skin index attribute.
  11001. *
  11002. * @type {AttributeNode}
  11003. */
  11004. this.skinIndexNode = attribute( 'skinIndex', 'uvec4' );
  11005. /**
  11006. * The skin weight attribute.
  11007. *
  11008. * @type {AttributeNode}
  11009. */
  11010. this.skinWeightNode = attribute( 'skinWeight', 'vec4' );
  11011. /**
  11012. * The bind matrix node.
  11013. *
  11014. * @type {Node<mat4>}
  11015. */
  11016. this.bindMatrixNode = reference( 'bindMatrix', 'mat4' );
  11017. /**
  11018. * The bind matrix inverse node.
  11019. *
  11020. * @type {Node<mat4>}
  11021. */
  11022. this.bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' );
  11023. /**
  11024. * The bind matrices as a uniform buffer node.
  11025. *
  11026. * @type {Node}
  11027. */
  11028. this.boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  11029. /**
  11030. * The current vertex position in local space.
  11031. *
  11032. * @type {Node<vec3>}
  11033. */
  11034. this.positionNode = positionLocal;
  11035. /**
  11036. * The result of vertex position in local space.
  11037. *
  11038. * @type {Node<vec3>}
  11039. */
  11040. this.toPositionNode = positionLocal;
  11041. /**
  11042. * The previous bind matrices as a uniform buffer node.
  11043. * Required for computing motion vectors.
  11044. *
  11045. * @type {?Node}
  11046. * @default null
  11047. */
  11048. this.previousBoneMatricesNode = null;
  11049. }
  11050. /**
  11051. * Transforms the given vertex position via skinning.
  11052. *
  11053. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  11054. * @param {Node<vec3>} [position=this.positionNode] - The vertex position in local space.
  11055. * @return {Node<vec3>} The transformed vertex position.
  11056. */
  11057. getSkinnedPosition( boneMatrices = this.boneMatricesNode, position = this.positionNode ) {
  11058. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  11059. const boneMatX = boneMatrices.element( skinIndexNode.x );
  11060. const boneMatY = boneMatrices.element( skinIndexNode.y );
  11061. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  11062. const boneMatW = boneMatrices.element( skinIndexNode.w );
  11063. // POSITION
  11064. const skinVertex = bindMatrixNode.mul( position );
  11065. const skinned = add(
  11066. boneMatX.mul( skinWeightNode.x ).mul( skinVertex ),
  11067. boneMatY.mul( skinWeightNode.y ).mul( skinVertex ),
  11068. boneMatZ.mul( skinWeightNode.z ).mul( skinVertex ),
  11069. boneMatW.mul( skinWeightNode.w ).mul( skinVertex )
  11070. );
  11071. return bindMatrixInverseNode.mul( skinned ).xyz;
  11072. }
  11073. /**
  11074. * Transforms the given vertex normal via skinning.
  11075. *
  11076. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  11077. * @param {Node<vec3>} [normal=normalLocal] - The vertex normal in local space.
  11078. * @return {Node<vec3>} The transformed vertex normal.
  11079. */
  11080. getSkinnedNormal( boneMatrices = this.boneMatricesNode, normal = normalLocal ) {
  11081. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  11082. const boneMatX = boneMatrices.element( skinIndexNode.x );
  11083. const boneMatY = boneMatrices.element( skinIndexNode.y );
  11084. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  11085. const boneMatW = boneMatrices.element( skinIndexNode.w );
  11086. // NORMAL
  11087. let skinMatrix = add(
  11088. skinWeightNode.x.mul( boneMatX ),
  11089. skinWeightNode.y.mul( boneMatY ),
  11090. skinWeightNode.z.mul( boneMatZ ),
  11091. skinWeightNode.w.mul( boneMatW )
  11092. );
  11093. skinMatrix = bindMatrixInverseNode.mul( skinMatrix ).mul( bindMatrixNode );
  11094. return skinMatrix.transformDirection( normal ).xyz;
  11095. }
  11096. /**
  11097. * Computes the transformed/skinned vertex position of the previous frame.
  11098. *
  11099. * @param {NodeBuilder} builder - The current node builder.
  11100. * @return {Node<vec3>} The skinned position from the previous frame.
  11101. */
  11102. getPreviousSkinnedPosition( builder ) {
  11103. const skinnedMesh = builder.object;
  11104. if ( this.previousBoneMatricesNode === null ) {
  11105. skinnedMesh.skeleton.previousBoneMatrices = new Float32Array( skinnedMesh.skeleton.boneMatrices );
  11106. this.previousBoneMatricesNode = referenceBuffer( 'skeleton.previousBoneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  11107. }
  11108. return this.getSkinnedPosition( this.previousBoneMatricesNode, positionPrevious );
  11109. }
  11110. /**
  11111. * Returns `true` if bone matrices from the previous frame are required. Relevant
  11112. * when computing motion vectors with {@link VelocityNode}.
  11113. *
  11114. * @param {NodeBuilder} builder - The current node builder.
  11115. * @return {boolean} Whether bone matrices from the previous frame are required or not.
  11116. */
  11117. needsPreviousBoneMatrices( builder ) {
  11118. const mrt = builder.renderer.getMRT();
  11119. return ( mrt && mrt.has( 'velocity' ) ) || getDataFromObject( builder.object ).useVelocity === true;
  11120. }
  11121. /**
  11122. * Setups the skinning node by assigning the transformed vertex data to predefined node variables.
  11123. *
  11124. * @param {NodeBuilder} builder - The current node builder.
  11125. * @return {Node<vec3>} The transformed vertex position.
  11126. */
  11127. setup( builder ) {
  11128. if ( this.needsPreviousBoneMatrices( builder ) ) {
  11129. positionPrevious.assign( this.getPreviousSkinnedPosition( builder ) );
  11130. }
  11131. const skinPosition = this.getSkinnedPosition();
  11132. if ( this.toPositionNode ) this.toPositionNode.assign( skinPosition );
  11133. //
  11134. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  11135. const skinNormal = this.getSkinnedNormal();
  11136. normalLocal.assign( skinNormal );
  11137. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  11138. tangentLocal.assign( skinNormal );
  11139. }
  11140. }
  11141. return skinPosition;
  11142. }
  11143. /**
  11144. * Generates the code snippet of the skinning node.
  11145. *
  11146. * @param {NodeBuilder} builder - The current node builder.
  11147. * @param {string} output - The current output.
  11148. * @return {string} The generated code snippet.
  11149. */
  11150. generate( builder, output ) {
  11151. if ( output !== 'void' ) {
  11152. return super.generate( builder, output );
  11153. }
  11154. }
  11155. /**
  11156. * Updates the state of the skinned mesh by updating the skeleton once per frame.
  11157. *
  11158. * @param {NodeFrame} frame - The current node frame.
  11159. */
  11160. update( frame ) {
  11161. const skeleton = frame.object && frame.object.skeleton ? frame.object.skeleton : this.skinnedMesh.skeleton;
  11162. if ( _frameId.get( skeleton ) === frame.frameId ) return;
  11163. _frameId.set( skeleton, frame.frameId );
  11164. if ( this.previousBoneMatricesNode !== null ) skeleton.previousBoneMatrices.set( skeleton.boneMatrices );
  11165. skeleton.update();
  11166. }
  11167. }
  11168. /**
  11169. * TSL function for creating a skinning node.
  11170. *
  11171. * @tsl
  11172. * @function
  11173. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  11174. * @returns {SkinningNode}
  11175. */
  11176. const skinning = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh ) );
  11177. /**
  11178. * TSL function for computing skinning.
  11179. *
  11180. * @tsl
  11181. * @function
  11182. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  11183. * @param {Node<vec3>} [toPosition=null] - The target position.
  11184. * @returns {SkinningNode}
  11185. */
  11186. const computeSkinning = ( skinnedMesh, toPosition = null ) => {
  11187. const node = new SkinningNode( skinnedMesh );
  11188. node.positionNode = storage( new InstancedBufferAttribute( skinnedMesh.geometry.getAttribute( 'position' ).array, 3 ), 'vec3' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  11189. node.skinIndexNode = storage( new InstancedBufferAttribute( new Uint32Array( skinnedMesh.geometry.getAttribute( 'skinIndex' ).array ), 4 ), 'uvec4' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  11190. node.skinWeightNode = storage( new InstancedBufferAttribute( skinnedMesh.geometry.getAttribute( 'skinWeight' ).array, 4 ), 'vec4' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  11191. node.bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' );
  11192. node.bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' );
  11193. node.boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length );
  11194. node.toPositionNode = toPosition;
  11195. return nodeObject( node );
  11196. };
  11197. /**
  11198. * This module offers a variety of ways to implement loops in TSL. In it's basic form it's:
  11199. * ```js
  11200. * Loop( count, ( { i } ) => {
  11201. *
  11202. * } );
  11203. * ```
  11204. * However, it is also possible to define a start and end ranges, data types and loop conditions:
  11205. * ```js
  11206. * Loop( { start: int( 0 ), end: int( 10 ), type: 'int', condition: '<' }, ( { i } ) => {
  11207. *
  11208. * } );
  11209. *```
  11210. * Nested loops can be defined in a compacted form:
  11211. * ```js
  11212. * Loop( 10, 5, ( { i, j } ) => {
  11213. *
  11214. * } );
  11215. * ```
  11216. * Loops that should run backwards can be defined like so:
  11217. * ```js
  11218. * Loop( { start: 10 }, () => {} );
  11219. * ```
  11220. * It is possible to execute with boolean values, similar to the `while` syntax.
  11221. * ```js
  11222. * const value = float( 0 ).toVar();
  11223. *
  11224. * Loop( value.lessThan( 10 ), () => {
  11225. *
  11226. * value.addAssign( 1 );
  11227. *
  11228. * } );
  11229. * ```
  11230. * The module also provides `Break()` and `Continue()` TSL expression for loop control.
  11231. * @augments Node
  11232. */
  11233. class LoopNode extends Node {
  11234. static get type() {
  11235. return 'LoopNode';
  11236. }
  11237. /**
  11238. * Constructs a new loop node.
  11239. *
  11240. * @param {Array<any>} params - Depending on the loop type, array holds different parameterization values for the loop.
  11241. */
  11242. constructor( params = [] ) {
  11243. super();
  11244. this.params = params;
  11245. }
  11246. /**
  11247. * Returns a loop variable name based on an index. The pattern is
  11248. * `0` = `i`, `1`= `j`, `2`= `k` and so on.
  11249. *
  11250. * @param {number} index - The index.
  11251. * @return {string} The loop variable name.
  11252. */
  11253. getVarName( index ) {
  11254. return String.fromCharCode( 'i'.charCodeAt( 0 ) + index );
  11255. }
  11256. /**
  11257. * Returns properties about this node.
  11258. *
  11259. * @param {NodeBuilder} builder - The current node builder.
  11260. * @return {Object} The node properties.
  11261. */
  11262. getProperties( builder ) {
  11263. const properties = builder.getNodeProperties( this );
  11264. if ( properties.stackNode !== undefined ) return properties;
  11265. //
  11266. const inputs = {};
  11267. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  11268. const param = this.params[ i ];
  11269. const name = ( param.isNode !== true && param.name ) || this.getVarName( i );
  11270. const type = ( param.isNode !== true && param.type ) || 'int';
  11271. inputs[ name ] = expression( name, type );
  11272. }
  11273. const stack = builder.addStack(); // TODO: cache() it
  11274. properties.returnsNode = this.params[ this.params.length - 1 ]( inputs, builder );
  11275. properties.stackNode = stack;
  11276. const baseParam = this.params[ 0 ];
  11277. if ( baseParam.isNode !== true && typeof baseParam.update === 'function' ) {
  11278. properties.updateNode = Fn( this.params[ 0 ].update )( inputs );
  11279. }
  11280. builder.removeStack();
  11281. return properties;
  11282. }
  11283. /**
  11284. * This method is overwritten since the node type is inferred based on the loop configuration.
  11285. *
  11286. * @param {NodeBuilder} builder - The current node builder.
  11287. * @return {string} The node type.
  11288. */
  11289. getNodeType( builder ) {
  11290. const { returnsNode } = this.getProperties( builder );
  11291. return returnsNode ? returnsNode.getNodeType( builder ) : 'void';
  11292. }
  11293. setup( builder ) {
  11294. // setup properties
  11295. this.getProperties( builder );
  11296. }
  11297. generate( builder ) {
  11298. const properties = this.getProperties( builder );
  11299. const params = this.params;
  11300. const stackNode = properties.stackNode;
  11301. for ( let i = 0, l = params.length - 1; i < l; i ++ ) {
  11302. const param = params[ i ];
  11303. let isWhile = false, start = null, end = null, name = null, type = null, condition = null, update = null;
  11304. if ( param.isNode ) {
  11305. if ( param.getNodeType( builder ) === 'bool' ) {
  11306. isWhile = true;
  11307. type = 'bool';
  11308. end = param.build( builder, type );
  11309. } else {
  11310. type = 'int';
  11311. name = this.getVarName( i );
  11312. start = '0';
  11313. end = param.build( builder, type );
  11314. condition = '<';
  11315. }
  11316. } else {
  11317. type = param.type || 'int';
  11318. name = param.name || this.getVarName( i );
  11319. start = param.start;
  11320. end = param.end;
  11321. condition = param.condition;
  11322. update = param.update;
  11323. if ( typeof start === 'number' ) start = builder.generateConst( type, start );
  11324. else if ( start && start.isNode ) start = start.build( builder, type );
  11325. if ( typeof end === 'number' ) end = builder.generateConst( type, end );
  11326. else if ( end && end.isNode ) end = end.build( builder, type );
  11327. if ( start !== undefined && end === undefined ) {
  11328. start = start + ' - 1';
  11329. end = '0';
  11330. condition = '>=';
  11331. } else if ( end !== undefined && start === undefined ) {
  11332. start = '0';
  11333. condition = '<';
  11334. }
  11335. if ( condition === undefined ) {
  11336. if ( Number( start ) > Number( end ) ) {
  11337. condition = '>=';
  11338. } else {
  11339. condition = '<';
  11340. }
  11341. }
  11342. }
  11343. let loopSnippet;
  11344. if ( isWhile ) {
  11345. loopSnippet = `while ( ${ end } )`;
  11346. } else {
  11347. const internalParam = { start, end};
  11348. //
  11349. const startSnippet = internalParam.start;
  11350. const endSnippet = internalParam.end;
  11351. let updateSnippet;
  11352. const deltaOperator = () => condition.includes( '<' ) ? '+=' : '-=';
  11353. if ( update !== undefined && update !== null ) {
  11354. switch ( typeof update ) {
  11355. case 'function':
  11356. const flow = builder.flowStagesNode( properties.updateNode, 'void' );
  11357. const snippet = flow.code.replace( /\t|;/g, '' );
  11358. updateSnippet = snippet;
  11359. break;
  11360. case 'number':
  11361. updateSnippet = name + ' ' + deltaOperator() + ' ' + builder.generateConst( type, update );
  11362. break;
  11363. case 'string':
  11364. updateSnippet = name + ' ' + update;
  11365. break;
  11366. default:
  11367. if ( update.isNode ) {
  11368. updateSnippet = name + ' ' + deltaOperator() + ' ' + update.build( builder );
  11369. } else {
  11370. console.error( 'THREE.TSL: \'Loop( { update: ... } )\' is not a function, string or number.' );
  11371. updateSnippet = 'break /* invalid update */';
  11372. }
  11373. }
  11374. } else {
  11375. if ( type === 'int' || type === 'uint' ) {
  11376. update = condition.includes( '<' ) ? '++' : '--';
  11377. } else {
  11378. update = deltaOperator() + ' 1.';
  11379. }
  11380. updateSnippet = name + ' ' + update;
  11381. }
  11382. const declarationSnippet = builder.getVar( type, name ) + ' = ' + startSnippet;
  11383. const conditionalSnippet = name + ' ' + condition + ' ' + endSnippet;
  11384. loopSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`;
  11385. }
  11386. builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + loopSnippet + ' {\n\n' ).addFlowTab();
  11387. }
  11388. const stackSnippet = stackNode.build( builder, 'void' );
  11389. const returnsSnippet = properties.returnsNode ? properties.returnsNode.build( builder ) : '';
  11390. builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet );
  11391. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  11392. builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab();
  11393. }
  11394. builder.addFlowTab();
  11395. return returnsSnippet;
  11396. }
  11397. }
  11398. /**
  11399. * TSL function for creating a loop node.
  11400. *
  11401. * @tsl
  11402. * @function
  11403. * @param {...any} params - A list of parameters.
  11404. * @returns {LoopNode}
  11405. */
  11406. const Loop = ( ...params ) => nodeObject( new LoopNode( nodeArray( params, 'int' ) ) ).toStack();
  11407. /**
  11408. * TSL function for creating a `Continue()` expression.
  11409. *
  11410. * @tsl
  11411. * @function
  11412. * @returns {ExpressionNode}
  11413. */
  11414. const Continue = () => expression( 'continue' ).toStack();
  11415. /**
  11416. * TSL function for creating a `Break()` expression.
  11417. *
  11418. * @tsl
  11419. * @function
  11420. * @returns {ExpressionNode}
  11421. */
  11422. const Break = () => expression( 'break' ).toStack();
  11423. // Deprecated
  11424. /**
  11425. * @tsl
  11426. * @function
  11427. * @deprecated since r168. Use {@link Loop} instead.
  11428. *
  11429. * @param {...any} params
  11430. * @returns {LoopNode}
  11431. */
  11432. const loop = ( ...params ) => { // @deprecated, r168
  11433. console.warn( 'THREE.TSL: loop() has been renamed to Loop().' );
  11434. return Loop( ...params );
  11435. };
  11436. const _morphTextures = /*@__PURE__*/ new WeakMap();
  11437. const _morphVec4 = /*@__PURE__*/ new Vector4();
  11438. const getMorph = /*@__PURE__*/ Fn( ( { bufferMap, influence, stride, width, depth, offset } ) => {
  11439. const texelIndex = int( vertexIndex ).mul( stride ).add( offset );
  11440. const y = texelIndex.div( width );
  11441. const x = texelIndex.sub( y.mul( width ) );
  11442. const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth ).xyz;
  11443. return bufferAttrib.mul( influence );
  11444. } );
  11445. function getEntry( geometry ) {
  11446. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  11447. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  11448. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  11449. // instead of using attributes, the WebGL 2 code path encodes morph targets
  11450. // into an array of data textures. Each layer represents a single morph target.
  11451. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  11452. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  11453. let entry = _morphTextures.get( geometry );
  11454. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  11455. if ( entry !== undefined ) entry.texture.dispose();
  11456. const morphTargets = geometry.morphAttributes.position || [];
  11457. const morphNormals = geometry.morphAttributes.normal || [];
  11458. const morphColors = geometry.morphAttributes.color || [];
  11459. let vertexDataCount = 0;
  11460. if ( hasMorphPosition === true ) vertexDataCount = 1;
  11461. if ( hasMorphNormals === true ) vertexDataCount = 2;
  11462. if ( hasMorphColors === true ) vertexDataCount = 3;
  11463. let width = geometry.attributes.position.count * vertexDataCount;
  11464. let height = 1;
  11465. const maxTextureSize = 4096; // @TODO: Use 'capabilities.maxTextureSize'
  11466. if ( width > maxTextureSize ) {
  11467. height = Math.ceil( width / maxTextureSize );
  11468. width = maxTextureSize;
  11469. }
  11470. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  11471. const bufferTexture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  11472. bufferTexture.type = FloatType;
  11473. bufferTexture.needsUpdate = true;
  11474. // fill buffer
  11475. const vertexDataStride = vertexDataCount * 4;
  11476. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  11477. const morphTarget = morphTargets[ i ];
  11478. const morphNormal = morphNormals[ i ];
  11479. const morphColor = morphColors[ i ];
  11480. const offset = width * height * 4 * i;
  11481. for ( let j = 0; j < morphTarget.count; j ++ ) {
  11482. const stride = j * vertexDataStride;
  11483. if ( hasMorphPosition === true ) {
  11484. _morphVec4.fromBufferAttribute( morphTarget, j );
  11485. buffer[ offset + stride + 0 ] = _morphVec4.x;
  11486. buffer[ offset + stride + 1 ] = _morphVec4.y;
  11487. buffer[ offset + stride + 2 ] = _morphVec4.z;
  11488. buffer[ offset + stride + 3 ] = 0;
  11489. }
  11490. if ( hasMorphNormals === true ) {
  11491. _morphVec4.fromBufferAttribute( morphNormal, j );
  11492. buffer[ offset + stride + 4 ] = _morphVec4.x;
  11493. buffer[ offset + stride + 5 ] = _morphVec4.y;
  11494. buffer[ offset + stride + 6 ] = _morphVec4.z;
  11495. buffer[ offset + stride + 7 ] = 0;
  11496. }
  11497. if ( hasMorphColors === true ) {
  11498. _morphVec4.fromBufferAttribute( morphColor, j );
  11499. buffer[ offset + stride + 8 ] = _morphVec4.x;
  11500. buffer[ offset + stride + 9 ] = _morphVec4.y;
  11501. buffer[ offset + stride + 10 ] = _morphVec4.z;
  11502. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? _morphVec4.w : 1;
  11503. }
  11504. }
  11505. }
  11506. entry = {
  11507. count: morphTargetsCount,
  11508. texture: bufferTexture,
  11509. stride: vertexDataCount,
  11510. size: new Vector2( width, height )
  11511. };
  11512. _morphTextures.set( geometry, entry );
  11513. function disposeTexture() {
  11514. bufferTexture.dispose();
  11515. _morphTextures.delete( geometry );
  11516. geometry.removeEventListener( 'dispose', disposeTexture );
  11517. }
  11518. geometry.addEventListener( 'dispose', disposeTexture );
  11519. }
  11520. return entry;
  11521. }
  11522. /**
  11523. * This node implements the vertex transformation shader logic which is required
  11524. * for morph target animation.
  11525. *
  11526. * @augments Node
  11527. */
  11528. class MorphNode extends Node {
  11529. static get type() {
  11530. return 'MorphNode';
  11531. }
  11532. /**
  11533. * Constructs a new morph node.
  11534. *
  11535. * @param {Mesh} mesh - The mesh holding the morph targets.
  11536. */
  11537. constructor( mesh ) {
  11538. super( 'void' );
  11539. /**
  11540. * The mesh holding the morph targets.
  11541. *
  11542. * @type {Mesh}
  11543. */
  11544. this.mesh = mesh;
  11545. /**
  11546. * A uniform node which represents the morph base influence value.
  11547. *
  11548. * @type {UniformNode<float>}
  11549. */
  11550. this.morphBaseInfluence = uniform( 1 );
  11551. /**
  11552. * The update type overwritten since morph nodes are updated per object.
  11553. *
  11554. * @type {string}
  11555. */
  11556. this.updateType = NodeUpdateType.OBJECT;
  11557. }
  11558. /**
  11559. * Setups the morph node by assigning the transformed vertex data to predefined node variables.
  11560. *
  11561. * @param {NodeBuilder} builder - The current node builder.
  11562. */
  11563. setup( builder ) {
  11564. const { geometry } = builder;
  11565. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  11566. const hasMorphNormals = geometry.hasAttribute( 'normal' ) && geometry.morphAttributes.normal !== undefined;
  11567. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  11568. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  11569. // nodes
  11570. const { texture: bufferMap, stride, size } = getEntry( geometry );
  11571. if ( hasMorphPosition === true ) positionLocal.mulAssign( this.morphBaseInfluence );
  11572. if ( hasMorphNormals === true ) normalLocal.mulAssign( this.morphBaseInfluence );
  11573. const width = int( size.width );
  11574. Loop( morphTargetsCount, ( { i } ) => {
  11575. const influence = float( 0 ).toVar();
  11576. if ( this.mesh.count > 1 && ( this.mesh.morphTexture !== null && this.mesh.morphTexture !== undefined ) ) {
  11577. influence.assign( textureLoad( this.mesh.morphTexture, ivec2( int( i ).add( 1 ), int( instanceIndex ) ) ).r );
  11578. } else {
  11579. influence.assign( reference( 'morphTargetInfluences', 'float' ).element( i ).toVar() );
  11580. }
  11581. If( influence.notEqual( 0 ), () => {
  11582. if ( hasMorphPosition === true ) {
  11583. positionLocal.addAssign( getMorph( {
  11584. bufferMap,
  11585. influence,
  11586. stride,
  11587. width,
  11588. depth: i,
  11589. offset: int( 0 )
  11590. } ) );
  11591. }
  11592. if ( hasMorphNormals === true ) {
  11593. normalLocal.addAssign( getMorph( {
  11594. bufferMap,
  11595. influence,
  11596. stride,
  11597. width,
  11598. depth: i,
  11599. offset: int( 1 )
  11600. } ) );
  11601. }
  11602. } );
  11603. } );
  11604. }
  11605. /**
  11606. * Updates the state of the morphed mesh by updating the base influence.
  11607. *
  11608. * @param {NodeFrame} frame - The current node frame.
  11609. */
  11610. update( /*frame*/ ) {
  11611. const morphBaseInfluence = this.morphBaseInfluence;
  11612. if ( this.mesh.geometry.morphTargetsRelative ) {
  11613. morphBaseInfluence.value = 1;
  11614. } else {
  11615. morphBaseInfluence.value = 1 - this.mesh.morphTargetInfluences.reduce( ( a, b ) => a + b, 0 );
  11616. }
  11617. }
  11618. }
  11619. /**
  11620. * TSL function for creating a morph node.
  11621. *
  11622. * @tsl
  11623. * @function
  11624. * @param {Mesh} mesh - The mesh holding the morph targets.
  11625. * @returns {MorphNode}
  11626. */
  11627. const morphReference = /*@__PURE__*/ nodeProxy( MorphNode ).setParameterLength( 1 );
  11628. /**
  11629. * Base class for lighting nodes.
  11630. *
  11631. * @augments Node
  11632. */
  11633. class LightingNode extends Node {
  11634. static get type() {
  11635. return 'LightingNode';
  11636. }
  11637. /**
  11638. * Constructs a new lighting node.
  11639. */
  11640. constructor() {
  11641. super( 'vec3' );
  11642. /**
  11643. * This flag can be used for type testing.
  11644. *
  11645. * @type {boolean}
  11646. * @readonly
  11647. * @default true
  11648. */
  11649. this.isLightingNode = true;
  11650. }
  11651. }
  11652. /**
  11653. * A generic class that can be used by nodes which contribute
  11654. * ambient occlusion to the scene. E.g. an ambient occlusion map
  11655. * node can be used as input for this module. Used in {@link NodeMaterial}.
  11656. *
  11657. * @augments LightingNode
  11658. */
  11659. class AONode extends LightingNode {
  11660. static get type() {
  11661. return 'AONode';
  11662. }
  11663. /**
  11664. * Constructs a new AO node.
  11665. *
  11666. * @param {?Node<float>} [aoNode=null] - The ambient occlusion node.
  11667. */
  11668. constructor( aoNode = null ) {
  11669. super();
  11670. /**
  11671. * The ambient occlusion node.
  11672. *
  11673. * @type {?Node<float>}
  11674. * @default null
  11675. */
  11676. this.aoNode = aoNode;
  11677. }
  11678. setup( builder ) {
  11679. builder.context.ambientOcclusion.mulAssign( this.aoNode );
  11680. }
  11681. }
  11682. /**
  11683. * `LightingContextNode` represents an extension of the {@link ContextNode} module
  11684. * by adding lighting specific context data. It represents the runtime context of
  11685. * {@link LightsNode}.
  11686. *
  11687. * @augments ContextNode
  11688. */
  11689. class LightingContextNode extends ContextNode {
  11690. static get type() {
  11691. return 'LightingContextNode';
  11692. }
  11693. /**
  11694. * Constructs a new lighting context node.
  11695. *
  11696. * @param {LightsNode} lightsNode - The lights node.
  11697. * @param {?LightingModel} [lightingModel=null] - The current lighting model.
  11698. * @param {?Node<vec3>} [backdropNode=null] - A backdrop node.
  11699. * @param {?Node<float>} [backdropAlphaNode=null] - A backdrop alpha node.
  11700. */
  11701. constructor( lightsNode, lightingModel = null, backdropNode = null, backdropAlphaNode = null ) {
  11702. super( lightsNode );
  11703. /**
  11704. * The current lighting model.
  11705. *
  11706. * @type {?LightingModel}
  11707. * @default null
  11708. */
  11709. this.lightingModel = lightingModel;
  11710. /**
  11711. * A backdrop node.
  11712. *
  11713. * @type {?Node<vec3>}
  11714. * @default null
  11715. */
  11716. this.backdropNode = backdropNode;
  11717. /**
  11718. * A backdrop alpha node.
  11719. *
  11720. * @type {?Node<float>}
  11721. * @default null
  11722. */
  11723. this.backdropAlphaNode = backdropAlphaNode;
  11724. this._value = null;
  11725. }
  11726. /**
  11727. * Returns a lighting context object.
  11728. *
  11729. * @return {{
  11730. * radiance: Node<vec3>,
  11731. * irradiance: Node<vec3>,
  11732. * iblIrradiance: Node<vec3>,
  11733. * ambientOcclusion: Node<float>,
  11734. * reflectedLight: {directDiffuse: Node<vec3>, directSpecular: Node<vec3>, indirectDiffuse: Node<vec3>, indirectSpecular: Node<vec3>},
  11735. * backdrop: Node<vec3>,
  11736. * backdropAlpha: Node<float>
  11737. * }} The lighting context object.
  11738. */
  11739. getContext() {
  11740. const { backdropNode, backdropAlphaNode } = this;
  11741. const directDiffuse = vec3().toVar( 'directDiffuse' ),
  11742. directSpecular = vec3().toVar( 'directSpecular' ),
  11743. indirectDiffuse = vec3().toVar( 'indirectDiffuse' ),
  11744. indirectSpecular = vec3().toVar( 'indirectSpecular' );
  11745. const reflectedLight = {
  11746. directDiffuse,
  11747. directSpecular,
  11748. indirectDiffuse,
  11749. indirectSpecular
  11750. };
  11751. const context = {
  11752. radiance: vec3().toVar( 'radiance' ),
  11753. irradiance: vec3().toVar( 'irradiance' ),
  11754. iblIrradiance: vec3().toVar( 'iblIrradiance' ),
  11755. ambientOcclusion: float( 1 ).toVar( 'ambientOcclusion' ),
  11756. reflectedLight,
  11757. backdrop: backdropNode,
  11758. backdropAlpha: backdropAlphaNode
  11759. };
  11760. return context;
  11761. }
  11762. setup( builder ) {
  11763. this.value = this._value || ( this._value = this.getContext() );
  11764. this.value.lightingModel = this.lightingModel || builder.context.lightingModel;
  11765. return super.setup( builder );
  11766. }
  11767. }
  11768. const lightingContext = /*@__PURE__*/ nodeProxy( LightingContextNode );
  11769. /**
  11770. * A generic class that can be used by nodes which contribute
  11771. * irradiance to the scene. E.g. a light map node can be used
  11772. * as input for this module. Used in {@link NodeMaterial}.
  11773. *
  11774. * @augments LightingNode
  11775. */
  11776. class IrradianceNode extends LightingNode {
  11777. static get type() {
  11778. return 'IrradianceNode';
  11779. }
  11780. /**
  11781. * Constructs a new irradiance node.
  11782. *
  11783. * @param {Node<vec3>} node - A node contributing irradiance.
  11784. */
  11785. constructor( node ) {
  11786. super();
  11787. /**
  11788. * A node contributing irradiance.
  11789. *
  11790. * @type {Node<vec3>}
  11791. */
  11792. this.node = node;
  11793. }
  11794. setup( builder ) {
  11795. builder.context.irradiance.addAssign( this.node );
  11796. }
  11797. }
  11798. let screenSizeVec, viewportVec;
  11799. /**
  11800. * This node provides a collection of screen related metrics.
  11801. * Depending on {@link ScreenNode#scope}, the nodes can represent
  11802. * resolution or viewport data as well as fragment or uv coordinates.
  11803. *
  11804. * @augments Node
  11805. */
  11806. class ScreenNode extends Node {
  11807. static get type() {
  11808. return 'ScreenNode';
  11809. }
  11810. /**
  11811. * Constructs a new screen node.
  11812. *
  11813. * @param {('coordinate'|'viewport'|'size'|'uv')} scope - The node's scope.
  11814. */
  11815. constructor( scope ) {
  11816. super();
  11817. /**
  11818. * The node represents different metric depending on which scope is selected.
  11819. *
  11820. * - `ScreenNode.COORDINATE`: Window-relative coordinates of the current fragment according to WebGPU standards.
  11821. * - `ScreenNode.VIEWPORT`: The current viewport defined as a four-dimensional vector.
  11822. * - `ScreenNode.SIZE`: The dimensions of the current bound framebuffer.
  11823. * - `ScreenNode.UV`: Normalized coordinates.
  11824. *
  11825. * @type {('coordinate'|'viewport'|'size'|'uv')}
  11826. */
  11827. this.scope = scope;
  11828. /**
  11829. * This flag can be used for type testing.
  11830. *
  11831. * @type {boolean}
  11832. * @readonly
  11833. * @default true
  11834. */
  11835. this.isViewportNode = true;
  11836. }
  11837. /**
  11838. * This method is overwritten since the node type depends on the selected scope.
  11839. *
  11840. * @return {('vec2'|'vec4')} The node type.
  11841. */
  11842. getNodeType() {
  11843. if ( this.scope === ScreenNode.VIEWPORT ) return 'vec4';
  11844. else return 'vec2';
  11845. }
  11846. /**
  11847. * This method is overwritten since the node's update type depends on the selected scope.
  11848. *
  11849. * @return {NodeUpdateType} The update type.
  11850. */
  11851. getUpdateType() {
  11852. let updateType = NodeUpdateType.NONE;
  11853. if ( this.scope === ScreenNode.SIZE || this.scope === ScreenNode.VIEWPORT ) {
  11854. updateType = NodeUpdateType.RENDER;
  11855. }
  11856. this.updateType = updateType;
  11857. return updateType;
  11858. }
  11859. /**
  11860. * `ScreenNode` implements {@link Node#update} to retrieve viewport and size information
  11861. * from the current renderer.
  11862. *
  11863. * @param {NodeFrame} frame - A reference to the current node frame.
  11864. */
  11865. update( { renderer } ) {
  11866. const renderTarget = renderer.getRenderTarget();
  11867. if ( this.scope === ScreenNode.VIEWPORT ) {
  11868. if ( renderTarget !== null ) {
  11869. viewportVec.copy( renderTarget.viewport );
  11870. } else {
  11871. renderer.getViewport( viewportVec );
  11872. viewportVec.multiplyScalar( renderer.getPixelRatio() );
  11873. }
  11874. } else {
  11875. if ( renderTarget !== null ) {
  11876. screenSizeVec.width = renderTarget.width;
  11877. screenSizeVec.height = renderTarget.height;
  11878. } else {
  11879. renderer.getDrawingBufferSize( screenSizeVec );
  11880. }
  11881. }
  11882. }
  11883. setup( /*builder*/ ) {
  11884. const scope = this.scope;
  11885. let output = null;
  11886. if ( scope === ScreenNode.SIZE ) {
  11887. output = uniform( screenSizeVec || ( screenSizeVec = new Vector2() ) );
  11888. } else if ( scope === ScreenNode.VIEWPORT ) {
  11889. output = uniform( viewportVec || ( viewportVec = new Vector4() ) );
  11890. } else {
  11891. output = vec2( screenCoordinate.div( screenSize ) );
  11892. }
  11893. return output;
  11894. }
  11895. generate( builder ) {
  11896. if ( this.scope === ScreenNode.COORDINATE ) {
  11897. let coord = builder.getFragCoord();
  11898. if ( builder.isFlipY() ) {
  11899. // follow webgpu standards
  11900. const size = builder.getNodeProperties( screenSize ).outputNode.build( builder );
  11901. coord = `${ builder.getType( 'vec2' ) }( ${ coord }.x, ${ size }.y - ${ coord }.y )`;
  11902. }
  11903. return coord;
  11904. }
  11905. return super.generate( builder );
  11906. }
  11907. }
  11908. ScreenNode.COORDINATE = 'coordinate';
  11909. ScreenNode.VIEWPORT = 'viewport';
  11910. ScreenNode.SIZE = 'size';
  11911. ScreenNode.UV = 'uv';
  11912. // Screen
  11913. /**
  11914. * TSL object that represents normalized screen coordinates, unitless in `[0, 1]`.
  11915. *
  11916. * @tsl
  11917. * @type {ScreenNode<vec2>}
  11918. */
  11919. const screenUV = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.UV );
  11920. /**
  11921. * TSL object that represents the screen resolution in physical pixel units.
  11922. *
  11923. * @tsl
  11924. * @type {ScreenNode<vec2>}
  11925. */
  11926. const screenSize = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.SIZE );
  11927. /**
  11928. * TSL object that represents the current `x`/`y` pixel position on the screen in physical pixel units.
  11929. *
  11930. * @tsl
  11931. * @type {ScreenNode<vec2>}
  11932. */
  11933. const screenCoordinate = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.COORDINATE );
  11934. // Viewport
  11935. /**
  11936. * TSL object that represents the viewport rectangle as `x`, `y`, `width` and `height` in physical pixel units.
  11937. *
  11938. * @tsl
  11939. * @type {ScreenNode<vec4>}
  11940. */
  11941. const viewport = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.VIEWPORT );
  11942. /**
  11943. * TSL object that represents the viewport resolution in physical pixel units.
  11944. *
  11945. * @tsl
  11946. * @type {ScreenNode<vec2>}
  11947. */
  11948. const viewportSize = viewport.zw;
  11949. /**
  11950. * TSL object that represents the current `x`/`y` pixel position on the viewport in physical pixel units.
  11951. *
  11952. * @tsl
  11953. * @type {ScreenNode<vec2>}
  11954. */
  11955. const viewportCoordinate = /*@__PURE__*/ screenCoordinate.sub( viewport.xy );
  11956. /**
  11957. * TSL object that represents normalized viewport coordinates, unitless in `[0, 1]`.
  11958. *
  11959. * @tsl
  11960. * @type {ScreenNode<vec2>}
  11961. */
  11962. const viewportUV = /*@__PURE__*/ viewportCoordinate.div( viewportSize );
  11963. // Deprecated
  11964. /**
  11965. * @deprecated since r169. Use {@link screenSize} instead.
  11966. */
  11967. const viewportResolution = /*@__PURE__*/ ( Fn( () => { // @deprecated, r169
  11968. console.warn( 'THREE.TSL: "viewportResolution" is deprecated. Use "screenSize" instead.' );
  11969. return screenSize;
  11970. }, 'vec2' ).once() )();
  11971. /**
  11972. * @tsl
  11973. * @deprecated since r168. Use {@link screenUV} instead.
  11974. * @type {Node<vec2>}
  11975. */
  11976. const viewportTopLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  11977. console.warn( 'THREE.TSL: "viewportTopLeft" is deprecated. Use "screenUV" instead.' );
  11978. return screenUV;
  11979. }, 'vec2' ).once() )();
  11980. /**
  11981. * @tsl
  11982. * @deprecated since r168. Use `screenUV.flipY()` instead.
  11983. * @type {Node<vec2>}
  11984. */
  11985. const viewportBottomLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  11986. console.warn( 'THREE.TSL: "viewportBottomLeft" is deprecated. Use "screenUV.flipY()" instead.' );
  11987. return screenUV.flipY();
  11988. }, 'vec2' ).once() )();
  11989. const _size$4 = /*@__PURE__*/ new Vector2();
  11990. /**
  11991. * A special type of texture node which represents the data of the current viewport
  11992. * as a texture. The module extracts data from the current bound framebuffer with
  11993. * a copy operation so no extra render pass is required to produce the texture data
  11994. * (which is good for performance). `ViewportTextureNode` can be used as an input for a
  11995. * variety of effects like refractive or transmissive materials.
  11996. *
  11997. * @augments TextureNode
  11998. */
  11999. class ViewportTextureNode extends TextureNode {
  12000. static get type() {
  12001. return 'ViewportTextureNode';
  12002. }
  12003. /**
  12004. * Constructs a new viewport texture node.
  12005. *
  12006. * @param {Node} [uvNode=screenUV] - The uv node.
  12007. * @param {?Node} [levelNode=null] - The level node.
  12008. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  12009. */
  12010. constructor( uvNode = screenUV, levelNode = null, framebufferTexture = null ) {
  12011. if ( framebufferTexture === null ) {
  12012. framebufferTexture = new FramebufferTexture();
  12013. framebufferTexture.minFilter = LinearMipmapLinearFilter;
  12014. }
  12015. super( framebufferTexture, uvNode, levelNode );
  12016. /**
  12017. * Whether to generate mipmaps or not.
  12018. *
  12019. * @type {boolean}
  12020. * @default false
  12021. */
  12022. this.generateMipmaps = false;
  12023. /**
  12024. * This flag can be used for type testing.
  12025. *
  12026. * @type {boolean}
  12027. * @readonly
  12028. * @default true
  12029. */
  12030. this.isOutputTextureNode = true;
  12031. /**
  12032. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  12033. * scene once per frame in its {@link ViewportTextureNode#updateBefore} method.
  12034. *
  12035. * @type {string}
  12036. * @default 'frame'
  12037. */
  12038. this.updateBeforeType = NodeUpdateType.FRAME;
  12039. }
  12040. updateBefore( frame ) {
  12041. const renderer = frame.renderer;
  12042. renderer.getDrawingBufferSize( _size$4 );
  12043. //
  12044. const framebufferTexture = this.value;
  12045. if ( framebufferTexture.image.width !== _size$4.width || framebufferTexture.image.height !== _size$4.height ) {
  12046. framebufferTexture.image.width = _size$4.width;
  12047. framebufferTexture.image.height = _size$4.height;
  12048. framebufferTexture.needsUpdate = true;
  12049. }
  12050. //
  12051. const currentGenerateMipmaps = framebufferTexture.generateMipmaps;
  12052. framebufferTexture.generateMipmaps = this.generateMipmaps;
  12053. renderer.copyFramebufferToTexture( framebufferTexture );
  12054. framebufferTexture.generateMipmaps = currentGenerateMipmaps;
  12055. }
  12056. clone() {
  12057. const viewportTextureNode = new this.constructor( this.uvNode, this.levelNode, this.value );
  12058. viewportTextureNode.generateMipmaps = this.generateMipmaps;
  12059. return viewportTextureNode;
  12060. }
  12061. }
  12062. /**
  12063. * TSL function for creating a viewport texture node.
  12064. *
  12065. * @tsl
  12066. * @function
  12067. * @param {?Node} [uvNode=screenUV] - The uv node.
  12068. * @param {?Node} [levelNode=null] - The level node.
  12069. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  12070. * @returns {ViewportTextureNode}
  12071. */
  12072. const viewportTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode ).setParameterLength( 0, 3 );
  12073. /**
  12074. * TSL function for creating a viewport texture node with enabled mipmap generation.
  12075. *
  12076. * @tsl
  12077. * @function
  12078. * @param {?Node} [uvNode=screenUV] - The uv node.
  12079. * @param {?Node} [levelNode=null] - The level node.
  12080. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  12081. * @returns {ViewportTextureNode}
  12082. */
  12083. const viewportMipTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode, null, null, { generateMipmaps: true } ).setParameterLength( 0, 3 );
  12084. let sharedDepthbuffer = null;
  12085. /**
  12086. * Represents the depth of the current viewport as a texture. This module
  12087. * can be used in combination with viewport texture to achieve effects
  12088. * that require depth evaluation.
  12089. *
  12090. * @augments ViewportTextureNode
  12091. */
  12092. class ViewportDepthTextureNode extends ViewportTextureNode {
  12093. static get type() {
  12094. return 'ViewportDepthTextureNode';
  12095. }
  12096. /**
  12097. * Constructs a new viewport depth texture node.
  12098. *
  12099. * @param {Node} [uvNode=screenUV] - The uv node.
  12100. * @param {?Node} [levelNode=null] - The level node.
  12101. */
  12102. constructor( uvNode = screenUV, levelNode = null ) {
  12103. if ( sharedDepthbuffer === null ) {
  12104. sharedDepthbuffer = new DepthTexture();
  12105. }
  12106. super( uvNode, levelNode, sharedDepthbuffer );
  12107. }
  12108. }
  12109. /**
  12110. * TSL function for a viewport depth texture node.
  12111. *
  12112. * @tsl
  12113. * @function
  12114. * @param {?Node} [uvNode=screenUV] - The uv node.
  12115. * @param {?Node} [levelNode=null] - The level node.
  12116. * @returns {ViewportDepthTextureNode}
  12117. */
  12118. const viewportDepthTexture = /*@__PURE__*/ nodeProxy( ViewportDepthTextureNode ).setParameterLength( 0, 2 );
  12119. /**
  12120. * This node offers a collection of features in context of the depth logic in the fragment shader.
  12121. * Depending on {@link ViewportDepthNode#scope}, it can be used to define a depth value for the current
  12122. * fragment or for depth evaluation purposes.
  12123. *
  12124. * @augments Node
  12125. */
  12126. class ViewportDepthNode extends Node {
  12127. static get type() {
  12128. return 'ViewportDepthNode';
  12129. }
  12130. /**
  12131. * Constructs a new viewport depth node.
  12132. *
  12133. * @param {('depth'|'depthBase'|'linearDepth')} scope - The node's scope.
  12134. * @param {?Node} [valueNode=null] - The value node.
  12135. */
  12136. constructor( scope, valueNode = null ) {
  12137. super( 'float' );
  12138. /**
  12139. * The node behaves differently depending on which scope is selected.
  12140. *
  12141. * - `ViewportDepthNode.DEPTH_BASE`: Allows to define a value for the current fragment's depth.
  12142. * - `ViewportDepthNode.DEPTH`: Represents the depth value for the current fragment (`valueNode` is ignored).
  12143. * - `ViewportDepthNode.LINEAR_DEPTH`: Represents the linear (orthographic) depth value of the current fragment.
  12144. * If a `valueNode` is set, the scope can be used to convert perspective depth data to linear data.
  12145. *
  12146. * @type {('depth'|'depthBase'|'linearDepth')}
  12147. */
  12148. this.scope = scope;
  12149. /**
  12150. * Can be used to define a custom depth value.
  12151. * The property is ignored in the `ViewportDepthNode.DEPTH` scope.
  12152. *
  12153. * @type {?Node}
  12154. * @default null
  12155. */
  12156. this.valueNode = valueNode;
  12157. /**
  12158. * This flag can be used for type testing.
  12159. *
  12160. * @type {boolean}
  12161. * @readonly
  12162. * @default true
  12163. */
  12164. this.isViewportDepthNode = true;
  12165. }
  12166. generate( builder ) {
  12167. const { scope } = this;
  12168. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  12169. return builder.getFragDepth();
  12170. }
  12171. return super.generate( builder );
  12172. }
  12173. setup( { camera } ) {
  12174. const { scope } = this;
  12175. const value = this.valueNode;
  12176. let node = null;
  12177. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  12178. if ( value !== null ) {
  12179. node = depthBase().assign( value );
  12180. }
  12181. } else if ( scope === ViewportDepthNode.DEPTH ) {
  12182. if ( camera.isPerspectiveCamera ) {
  12183. node = viewZToPerspectiveDepth( positionView.z, cameraNear, cameraFar );
  12184. } else {
  12185. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  12186. }
  12187. } else if ( scope === ViewportDepthNode.LINEAR_DEPTH ) {
  12188. if ( value !== null ) {
  12189. if ( camera.isPerspectiveCamera ) {
  12190. const viewZ = perspectiveDepthToViewZ( value, cameraNear, cameraFar );
  12191. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  12192. } else {
  12193. node = value;
  12194. }
  12195. } else {
  12196. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  12197. }
  12198. }
  12199. return node;
  12200. }
  12201. }
  12202. ViewportDepthNode.DEPTH_BASE = 'depthBase';
  12203. ViewportDepthNode.DEPTH = 'depth';
  12204. ViewportDepthNode.LINEAR_DEPTH = 'linearDepth';
  12205. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  12206. /**
  12207. * TSL function for converting a viewZ value to an orthographic depth value.
  12208. *
  12209. * @tsl
  12210. * @function
  12211. * @param {Node<float>} viewZ - The viewZ node.
  12212. * @param {Node<float>} near - The camera's near value.
  12213. * @param {Node<float>} far - The camera's far value.
  12214. * @returns {Node<float>}
  12215. */
  12216. const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  12217. /**
  12218. * TSL function for converting an orthographic depth value to a viewZ value.
  12219. *
  12220. * @tsl
  12221. * @function
  12222. * @param {Node<float>} depth - The orthographic depth.
  12223. * @param {Node<float>} near - The camera's near value.
  12224. * @param {Node<float>} far - The camera's far value.
  12225. * @returns {Node<float>}
  12226. */
  12227. const orthographicDepthToViewZ = ( depth, near, far ) => near.sub( far ).mul( depth ).sub( near );
  12228. /**
  12229. * TSL function for converting a viewZ value to a perspective depth value.
  12230. *
  12231. * Note: {link https://twitter.com/gonnavis/status/1377183786949959682}.
  12232. *
  12233. * @tsl
  12234. * @function
  12235. * @param {Node<float>} viewZ - The viewZ node.
  12236. * @param {Node<float>} near - The camera's near value.
  12237. * @param {Node<float>} far - The camera's far value.
  12238. * @returns {Node<float>}
  12239. */
  12240. const viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( far.sub( near ).mul( viewZ ) );
  12241. /**
  12242. * TSL function for converting a perspective depth value to a viewZ value.
  12243. *
  12244. * @tsl
  12245. * @function
  12246. * @param {Node<float>} depth - The perspective depth.
  12247. * @param {Node<float>} near - The camera's near value.
  12248. * @param {Node<float>} far - The camera's far value.
  12249. * @returns {Node<float>}
  12250. */
  12251. const perspectiveDepthToViewZ = ( depth, near, far ) => near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  12252. /**
  12253. * TSL function for converting a viewZ value to a logarithmic depth value.
  12254. *
  12255. * @tsl
  12256. * @function
  12257. * @param {Node<float>} viewZ - The viewZ node.
  12258. * @param {Node<float>} near - The camera's near value.
  12259. * @param {Node<float>} far - The camera's far value.
  12260. * @returns {Node<float>}
  12261. */
  12262. const viewZToLogarithmicDepth = ( viewZ, near, far ) => {
  12263. // NOTE: viewZ must be negative--see explanation at the end of this comment block.
  12264. // The final logarithmic depth formula used here is adapted from one described in an
  12265. // article by Thatcher Ulrich (see http://tulrich.com/geekstuff/log_depth_buffer.txt),
  12266. // which was an improvement upon an earlier formula one described in an
  12267. // Outerra article (https://outerra.blogspot.com/2009/08/logarithmic-z-buffer.html).
  12268. // Ulrich's formula is the following:
  12269. // z = K * log( w / cameraNear ) / log( cameraFar / cameraNear )
  12270. // where K = 2^k - 1, and k is the number of bits in the depth buffer.
  12271. // The Outerra variant ignored the camera near plane (it assumed it was 0) and instead
  12272. // opted for a "C-constant" for resolution adjustment of objects near the camera.
  12273. // Outerra states: "Notice that the 'C' variant doesn’t use a near plane distance, it has it
  12274. // set at 0" (quote from https://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html).
  12275. // Ulrich's variant has the benefit of constant relative precision over the whole near-far range.
  12276. // It was debated here whether Outerra's "C-constant" or Ulrich's "near plane" variant should
  12277. // be used, and ultimately Ulrich's "near plane" version was chosen.
  12278. // Outerra eventually made another improvement to their original "C-constant" variant,
  12279. // but it still does not incorporate the camera near plane (for this version,
  12280. // see https://outerra.blogspot.com/2013/07/logarithmic-depth-buffer-optimizations.html).
  12281. // Here we make 4 changes to Ulrich's formula:
  12282. // 1. Clamp the camera near plane so we don't divide by 0.
  12283. // 2. Use log2 instead of log to avoid an extra multiply (shaders implement log using log2).
  12284. // 3. Assume K is 1 (K = maximum value in depth buffer; see Ulrich's formula above).
  12285. // 4. To maintain consistency with the functions "viewZToOrthographicDepth" and "viewZToPerspectiveDepth",
  12286. // we modify the formula here to use 'viewZ' instead of 'w'. The other functions expect a negative viewZ,
  12287. // so we do the same here, hence the 'viewZ.negate()' call.
  12288. // For visual representation of this depth curve, see https://www.desmos.com/calculator/uyqk0vex1u
  12289. near = near.max( 1e-6 ).toVar();
  12290. const numerator = log2( viewZ.negate().div( near ) );
  12291. const denominator = log2( far.div( near ) );
  12292. return numerator.div( denominator );
  12293. };
  12294. /**
  12295. * TSL function for converting a logarithmic depth value to a viewZ value.
  12296. *
  12297. * @tsl
  12298. * @function
  12299. * @param {Node<float>} depth - The logarithmic depth.
  12300. * @param {Node<float>} near - The camera's near value.
  12301. * @param {Node<float>} far - The camera's far value.
  12302. * @returns {Node<float>}
  12303. */
  12304. const logarithmicDepthToViewZ = ( depth, near, far ) => {
  12305. // NOTE: we add a 'negate()' call to the return value here to maintain consistency with
  12306. // the functions "orthographicDepthToViewZ" and "perspectiveDepthToViewZ" (they return
  12307. // a negative viewZ).
  12308. const exponent = depth.mul( log( far.div( near ) ) );
  12309. return float( Math.E ).pow( exponent ).mul( near ).negate();
  12310. };
  12311. /**
  12312. * TSL function for defining a value for the current fragment's depth.
  12313. *
  12314. * @tsl
  12315. * @function
  12316. * @param {Node<float>} value - The depth value to set.
  12317. * @returns {ViewportDepthNode<float>}
  12318. */
  12319. const depthBase = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH_BASE );
  12320. /**
  12321. * TSL object that represents the depth value for the current fragment.
  12322. *
  12323. * @tsl
  12324. * @type {ViewportDepthNode}
  12325. */
  12326. const depth = /*@__PURE__*/ nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  12327. /**
  12328. * TSL function for converting a perspective depth value to linear depth.
  12329. *
  12330. * @tsl
  12331. * @function
  12332. * @param {?Node<float>} [value=null] - The perspective depth. If `null` is provided, the current fragment's depth is used.
  12333. * @returns {ViewportDepthNode<float>}
  12334. */
  12335. const linearDepth = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.LINEAR_DEPTH ).setParameterLength( 0, 1 );
  12336. /**
  12337. * TSL object that represents the linear (orthographic) depth value of the current fragment
  12338. *
  12339. * @tsl
  12340. * @type {ViewportDepthNode}
  12341. */
  12342. const viewportLinearDepth = /*@__PURE__*/ linearDepth( viewportDepthTexture() );
  12343. depth.assign = ( value ) => depthBase( value );
  12344. /**
  12345. * This node is used in {@link NodeMaterial} to setup the clipping
  12346. * which can happen hardware-accelerated (if supported) and optionally
  12347. * use alpha-to-coverage for anti-aliasing clipped edges.
  12348. *
  12349. * @augments Node
  12350. */
  12351. class ClippingNode extends Node {
  12352. static get type() {
  12353. return 'ClippingNode';
  12354. }
  12355. /**
  12356. * Constructs a new clipping node.
  12357. *
  12358. * @param {('default'|'hardware'|'alphaToCoverage')} [scope='default'] - The node's scope. Similar to other nodes,
  12359. * the selected scope influences the behavior of the node and what type of code is generated.
  12360. */
  12361. constructor( scope = ClippingNode.DEFAULT ) {
  12362. super();
  12363. /**
  12364. * The node's scope. Similar to other nodes, the selected scope influences
  12365. * the behavior of the node and what type of code is generated.
  12366. *
  12367. * @type {('default'|'hardware'|'alphaToCoverage')}
  12368. */
  12369. this.scope = scope;
  12370. }
  12371. /**
  12372. * Setups the node depending on the selected scope.
  12373. *
  12374. * @param {NodeBuilder} builder - The current node builder.
  12375. * @return {Node} The result node.
  12376. */
  12377. setup( builder ) {
  12378. super.setup( builder );
  12379. const clippingContext = builder.clippingContext;
  12380. const { intersectionPlanes, unionPlanes } = clippingContext;
  12381. this.hardwareClipping = builder.material.hardwareClipping;
  12382. if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) {
  12383. return this.setupAlphaToCoverage( intersectionPlanes, unionPlanes );
  12384. } else if ( this.scope === ClippingNode.HARDWARE ) {
  12385. return this.setupHardwareClipping( unionPlanes, builder );
  12386. } else {
  12387. return this.setupDefault( intersectionPlanes, unionPlanes );
  12388. }
  12389. }
  12390. /**
  12391. * Setups alpha to coverage.
  12392. *
  12393. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  12394. * @param {Array<Vector4>} unionPlanes - The union planes.
  12395. * @return {Node} The result node.
  12396. */
  12397. setupAlphaToCoverage( intersectionPlanes, unionPlanes ) {
  12398. return Fn( () => {
  12399. const distanceToPlane = float().toVar( 'distanceToPlane' );
  12400. const distanceGradient = float().toVar( 'distanceToGradient' );
  12401. const clipOpacity = float( 1 ).toVar( 'clipOpacity' );
  12402. const numUnionPlanes = unionPlanes.length;
  12403. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  12404. const clippingPlanes = uniformArray( unionPlanes );
  12405. Loop( numUnionPlanes, ( { i } ) => {
  12406. const plane = clippingPlanes.element( i );
  12407. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  12408. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  12409. clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) );
  12410. } );
  12411. }
  12412. const numIntersectionPlanes = intersectionPlanes.length;
  12413. if ( numIntersectionPlanes > 0 ) {
  12414. const clippingPlanes = uniformArray( intersectionPlanes );
  12415. const intersectionClipOpacity = float( 1 ).toVar( 'intersectionClipOpacity' );
  12416. Loop( numIntersectionPlanes, ( { i } ) => {
  12417. const plane = clippingPlanes.element( i );
  12418. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  12419. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  12420. intersectionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() );
  12421. } );
  12422. clipOpacity.mulAssign( intersectionClipOpacity.oneMinus() );
  12423. }
  12424. diffuseColor.a.mulAssign( clipOpacity );
  12425. diffuseColor.a.equal( 0.0 ).discard();
  12426. } )();
  12427. }
  12428. /**
  12429. * Setups the default clipping.
  12430. *
  12431. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  12432. * @param {Array<Vector4>} unionPlanes - The union planes.
  12433. * @return {Node} The result node.
  12434. */
  12435. setupDefault( intersectionPlanes, unionPlanes ) {
  12436. return Fn( () => {
  12437. const numUnionPlanes = unionPlanes.length;
  12438. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  12439. const clippingPlanes = uniformArray( unionPlanes );
  12440. Loop( numUnionPlanes, ( { i } ) => {
  12441. const plane = clippingPlanes.element( i );
  12442. positionView.dot( plane.xyz ).greaterThan( plane.w ).discard();
  12443. } );
  12444. }
  12445. const numIntersectionPlanes = intersectionPlanes.length;
  12446. if ( numIntersectionPlanes > 0 ) {
  12447. const clippingPlanes = uniformArray( intersectionPlanes );
  12448. const clipped = bool( true ).toVar( 'clipped' );
  12449. Loop( numIntersectionPlanes, ( { i } ) => {
  12450. const plane = clippingPlanes.element( i );
  12451. clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) );
  12452. } );
  12453. clipped.discard();
  12454. }
  12455. } )();
  12456. }
  12457. /**
  12458. * Setups hardware clipping.
  12459. *
  12460. * @param {Array<Vector4>} unionPlanes - The union planes.
  12461. * @param {NodeBuilder} builder - The current node builder.
  12462. * @return {Node} The result node.
  12463. */
  12464. setupHardwareClipping( unionPlanes, builder ) {
  12465. const numUnionPlanes = unionPlanes.length;
  12466. builder.enableHardwareClipping( numUnionPlanes );
  12467. return Fn( () => {
  12468. const clippingPlanes = uniformArray( unionPlanes );
  12469. const hw_clip_distances = builtin( builder.getClipDistance() );
  12470. Loop( numUnionPlanes, ( { i } ) => {
  12471. const plane = clippingPlanes.element( i );
  12472. const distance = positionView.dot( plane.xyz ).sub( plane.w ).negate();
  12473. hw_clip_distances.element( i ).assign( distance );
  12474. } );
  12475. } )();
  12476. }
  12477. }
  12478. ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage';
  12479. ClippingNode.DEFAULT = 'default';
  12480. ClippingNode.HARDWARE = 'hardware';
  12481. /**
  12482. * TSL function for setting up the default clipping logic.
  12483. *
  12484. * @tsl
  12485. * @function
  12486. * @returns {ClippingNode}
  12487. */
  12488. const clipping = () => nodeObject( new ClippingNode() );
  12489. /**
  12490. * TSL function for setting up alpha to coverage.
  12491. *
  12492. * @tsl
  12493. * @function
  12494. * @returns {ClippingNode}
  12495. */
  12496. const clippingAlpha = () => nodeObject( new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE ) );
  12497. /**
  12498. * TSL function for setting up hardware-based clipping.
  12499. *
  12500. * @tsl
  12501. * @function
  12502. * @returns {ClippingNode}
  12503. */
  12504. const hardwareClipping = () => nodeObject( new ClippingNode( ClippingNode.HARDWARE ) );
  12505. // See: https://casual-effects.com/research/Wyman2017Hashed/index.html
  12506. const ALPHA_HASH_SCALE = 0.05; // Derived from trials only, and may be changed.
  12507. const hash2D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  12508. 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 ) ) ) ) ) );
  12509. } );
  12510. const hash3D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  12511. return hash2D( vec2( hash2D( value.xy ), value.z ) );
  12512. } );
  12513. const getAlphaHashThreshold = /*@__PURE__*/ Fn( ( [ position ] ) => {
  12514. // Find the discretized derivatives of our coordinates
  12515. const maxDeriv = max$1(
  12516. length( dFdx( position.xyz ) ),
  12517. length( dFdy( position.xyz ) )
  12518. );
  12519. const pixScale = float( 1 ).div( float( ALPHA_HASH_SCALE ).mul( maxDeriv ) ).toVar( 'pixScale' );
  12520. // Find two nearest log-discretized noise scales
  12521. const pixScales = vec2(
  12522. exp2( floor( log2( pixScale ) ) ),
  12523. exp2( ceil( log2( pixScale ) ) )
  12524. );
  12525. // Compute alpha thresholds at our two noise scales
  12526. const alpha = vec2(
  12527. hash3D( floor( pixScales.x.mul( position.xyz ) ) ),
  12528. hash3D( floor( pixScales.y.mul( position.xyz ) ) ),
  12529. );
  12530. // Factor to interpolate lerp with
  12531. const lerpFactor = fract( log2( pixScale ) );
  12532. // Interpolate alpha threshold from noise at two scales
  12533. const x = add( mul( lerpFactor.oneMinus(), alpha.x ), mul( lerpFactor, alpha.y ) );
  12534. // Pass into CDF to compute uniformly distrib threshold
  12535. const a = min$1( lerpFactor, lerpFactor.oneMinus() );
  12536. const cases = vec3(
  12537. x.mul( x ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ),
  12538. x.sub( mul( 0.5, a ) ).div( sub( 1.0, a ) ),
  12539. sub( 1.0, sub( 1.0, x ).mul( sub( 1.0, x ) ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ) ) );
  12540. // Find our final, uniformly distributed alpha threshold (ατ)
  12541. const threshold = x.lessThan( a.oneMinus() ).select( x.lessThan( a ).select( cases.x, cases.y ), cases.z );
  12542. // Avoids ατ == 0. Could also do ατ =1-ατ
  12543. return clamp( threshold, 1.0e-6, 1.0 );
  12544. } ).setLayout( {
  12545. name: 'getAlphaHashThreshold',
  12546. type: 'float',
  12547. inputs: [
  12548. { name: 'position', type: 'vec3' }
  12549. ]
  12550. } );
  12551. /**
  12552. * An attribute node for representing vertex colors.
  12553. *
  12554. * @augments AttributeNode
  12555. */
  12556. class VertexColorNode extends AttributeNode {
  12557. static get type() {
  12558. return 'VertexColorNode';
  12559. }
  12560. /**
  12561. * Constructs a new vertex color node.
  12562. *
  12563. * @param {number} index - The attribute index.
  12564. */
  12565. constructor( index ) {
  12566. super( null, 'vec4' );
  12567. /**
  12568. * This flag can be used for type testing.
  12569. *
  12570. * @type {boolean}
  12571. * @readonly
  12572. * @default true
  12573. */
  12574. this.isVertexColorNode = true;
  12575. /**
  12576. * The attribute index to enable more than one sets of vertex colors.
  12577. *
  12578. * @type {number}
  12579. * @default 0
  12580. */
  12581. this.index = index;
  12582. }
  12583. /**
  12584. * Overwrites the default implementation by honoring the attribute index.
  12585. *
  12586. * @param {NodeBuilder} builder - The current node builder.
  12587. * @return {string} The attribute name.
  12588. */
  12589. getAttributeName( /*builder*/ ) {
  12590. const index = this.index;
  12591. return 'color' + ( index > 0 ? index : '' );
  12592. }
  12593. generate( builder ) {
  12594. const attributeName = this.getAttributeName( builder );
  12595. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  12596. let result;
  12597. if ( geometryAttribute === true ) {
  12598. result = super.generate( builder );
  12599. } else {
  12600. // Vertex color fallback should be white
  12601. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  12602. }
  12603. return result;
  12604. }
  12605. serialize( data ) {
  12606. super.serialize( data );
  12607. data.index = this.index;
  12608. }
  12609. deserialize( data ) {
  12610. super.deserialize( data );
  12611. this.index = data.index;
  12612. }
  12613. }
  12614. /**
  12615. * TSL function for creating a reference node.
  12616. *
  12617. * @tsl
  12618. * @function
  12619. * @param {number} [index=0] - The attribute index.
  12620. * @returns {VertexColorNode}
  12621. */
  12622. const vertexColor = ( index = 0 ) => nodeObject( new VertexColorNode( index ) );
  12623. /**
  12624. * Base class for all node materials.
  12625. *
  12626. * @augments Material
  12627. */
  12628. class NodeMaterial extends Material {
  12629. static get type() {
  12630. return 'NodeMaterial';
  12631. }
  12632. /**
  12633. * Represents the type of the node material.
  12634. *
  12635. * @type {string}
  12636. */
  12637. get type() {
  12638. return this.constructor.type;
  12639. }
  12640. set type( _value ) { /* */ }
  12641. /**
  12642. * Constructs a new node material.
  12643. */
  12644. constructor() {
  12645. super();
  12646. /**
  12647. * This flag can be used for type testing.
  12648. *
  12649. * @type {boolean}
  12650. * @readonly
  12651. * @default true
  12652. */
  12653. this.isNodeMaterial = true;
  12654. /**
  12655. * Whether this material is affected by fog or not.
  12656. *
  12657. * @type {boolean}
  12658. * @default true
  12659. */
  12660. this.fog = true;
  12661. /**
  12662. * Whether this material is affected by lights or not.
  12663. *
  12664. * @type {boolean}
  12665. * @default false
  12666. */
  12667. this.lights = false;
  12668. /**
  12669. * Whether this material uses hardware clipping or not.
  12670. * This property is managed by the engine and should not be
  12671. * modified by apps.
  12672. *
  12673. * @type {boolean}
  12674. * @default false
  12675. */
  12676. this.hardwareClipping = false;
  12677. /**
  12678. * Node materials which set their `lights` property to `true`
  12679. * are affected by all lights of the scene. Sometimes selective
  12680. * lighting is wanted which means only _some_ lights in the scene
  12681. * affect a material. This can be achieved by creating an instance
  12682. * of {@link LightsNode} with a list of selective
  12683. * lights and assign the node to this property.
  12684. *
  12685. * ```js
  12686. * const customLightsNode = lights( [ light1, light2 ] );
  12687. * material.lightsNode = customLightsNode;
  12688. * ```
  12689. *
  12690. * @type {?LightsNode}
  12691. * @default null
  12692. */
  12693. this.lightsNode = null;
  12694. /**
  12695. * The environment of node materials can be defined by an environment
  12696. * map assigned to the `envMap` property or by `Scene.environment`
  12697. * if the node material is a PBR material. This node property allows to overwrite
  12698. * the default behavior and define the environment with a custom node.
  12699. *
  12700. * ```js
  12701. * material.envNode = pmremTexture( renderTarget.texture );
  12702. * ```
  12703. *
  12704. * @type {?Node<vec3>}
  12705. * @default null
  12706. */
  12707. this.envNode = null;
  12708. /**
  12709. * The lighting of node materials might be influenced by ambient occlusion.
  12710. * The default AO is inferred from an ambient occlusion map assigned to `aoMap`
  12711. * and the respective `aoMapIntensity`. This node property allows to overwrite
  12712. * the default and define the ambient occlusion with a custom node instead.
  12713. *
  12714. * If you don't want to overwrite the diffuse color but modify the existing
  12715. * values instead, use {@link materialAO}.
  12716. *
  12717. * @type {?Node<float>}
  12718. * @default null
  12719. */
  12720. this.aoNode = null;
  12721. /**
  12722. * The diffuse color of node materials is by default inferred from the
  12723. * `color` and `map` properties. This node property allows to overwrite the default
  12724. * and define the diffuse color with a node instead.
  12725. *
  12726. * ```js
  12727. * material.colorNode = color( 0xff0000 ); // define red color
  12728. * ```
  12729. *
  12730. * If you don't want to overwrite the diffuse color but modify the existing
  12731. * values instead, use {@link materialColor}.
  12732. *
  12733. * ```js
  12734. * material.colorNode = materialColor.mul( color( 0xff0000 ) ); // give diffuse colors a red tint
  12735. * ```
  12736. *
  12737. * @type {?Node<vec3>}
  12738. * @default null
  12739. */
  12740. this.colorNode = null;
  12741. /**
  12742. * The normals of node materials are by default inferred from the `normalMap`/`normalScale`
  12743. * or `bumpMap`/`bumpScale` properties. This node property allows to overwrite the default
  12744. * and define the normals with a node instead.
  12745. *
  12746. * If you don't want to overwrite the normals but modify the existing values instead,
  12747. * use {@link materialNormal}.
  12748. *
  12749. * @type {?Node<vec3>}
  12750. * @default null
  12751. */
  12752. this.normalNode = null;
  12753. /**
  12754. * The opacity of node materials is by default inferred from the `opacity`
  12755. * and `alphaMap` properties. This node property allows to overwrite the default
  12756. * and define the opacity with a node instead.
  12757. *
  12758. * If you don't want to overwrite the normals but modify the existing
  12759. * value instead, use {@link materialOpacity}.
  12760. *
  12761. * @type {?Node<float>}
  12762. * @default null
  12763. */
  12764. this.opacityNode = null;
  12765. /**
  12766. * This node can be used to implement a variety of filter-like effects. The idea is
  12767. * to store the current rendering into a texture e.g. via `viewportSharedTexture()`, use it
  12768. * to create an arbitrary effect and then assign the node composition to this property.
  12769. * Everything behind the object using this material will now be affected by a filter.
  12770. *
  12771. * ```js
  12772. * const material = new NodeMaterial()
  12773. * material.transparent = true;
  12774. *
  12775. * // everything behind the object will be monochromatic
  12776. * material.backdropNode = saturation( viewportSharedTexture().rgb, 0 );
  12777. * ```
  12778. *
  12779. * Backdrop computations are part of the lighting so only lit materials can use this property.
  12780. *
  12781. * @type {?Node<vec3>}
  12782. * @default null
  12783. */
  12784. this.backdropNode = null;
  12785. /**
  12786. * This node allows to modulate the influence of `backdropNode` to the outgoing light.
  12787. *
  12788. * @type {?Node<float>}
  12789. * @default null
  12790. */
  12791. this.backdropAlphaNode = null;
  12792. /**
  12793. * The alpha test of node materials is by default inferred from the `alphaTest`
  12794. * property. This node property allows to overwrite the default and define the
  12795. * alpha test with a node instead.
  12796. *
  12797. * If you don't want to overwrite the alpha test but modify the existing
  12798. * value instead, use {@link materialAlphaTest}.
  12799. *
  12800. * @type {?Node<float>}
  12801. * @default null
  12802. */
  12803. this.alphaTestNode = null;
  12804. /**
  12805. * Discards the fragment if the mask value is `false`.
  12806. *
  12807. * @type {?Node<bool>}
  12808. * @default null
  12809. */
  12810. this.maskNode = null;
  12811. /**
  12812. * The local vertex positions are computed based on multiple factors like the
  12813. * attribute data, morphing or skinning. This node property allows to overwrite
  12814. * the default and define local vertex positions with nodes instead.
  12815. *
  12816. * If you don't want to overwrite the vertex positions but modify the existing
  12817. * values instead, use {@link positionLocal}.
  12818. *
  12819. *```js
  12820. * material.positionNode = positionLocal.add( displace );
  12821. * ```
  12822. *
  12823. * @type {?Node<vec3>}
  12824. * @default null
  12825. */
  12826. this.positionNode = null;
  12827. /**
  12828. * This node property is intended for logic which modifies geometry data once or per animation step.
  12829. * Apps usually place such logic randomly in initialization routines or in the animation loop.
  12830. * `geometryNode` is intended as a dedicated API so there is an intended spot where geometry modifications
  12831. * can be implemented.
  12832. *
  12833. * The idea is to assign a `Fn` definition that holds the geometry modification logic. A typical example
  12834. * would be a GPU based particle system that provides a node material for usage on app level. The particle
  12835. * simulation would be implemented as compute shaders and managed inside a `Fn` function. This function is
  12836. * eventually assigned to `geometryNode`.
  12837. *
  12838. * @type {?Function}
  12839. * @default null
  12840. */
  12841. this.geometryNode = null;
  12842. /**
  12843. * Allows to overwrite depth values in the fragment shader.
  12844. *
  12845. * @type {?Node<float>}
  12846. * @default null
  12847. */
  12848. this.depthNode = null;
  12849. /**
  12850. * Allows to overwrite the position used for shadow map rendering which
  12851. * is by default {@link positionWorld}, the vertex position
  12852. * in world space.
  12853. *
  12854. * @type {?Node<float>}
  12855. * @default null
  12856. */
  12857. this.receivedShadowPositionNode = null;
  12858. /**
  12859. * Allows to overwrite the geometry position used for shadow map projection which
  12860. * is by default {@link positionLocal}, the vertex position in local space.
  12861. *
  12862. * @type {?Node<float>}
  12863. * @default null
  12864. */
  12865. this.castShadowPositionNode = null;
  12866. /**
  12867. * This node can be used to influence how an object using this node material
  12868. * receive shadows.
  12869. *
  12870. * ```js
  12871. * const totalShadows = float( 1 ).toVar();
  12872. * material.receivedShadowNode = Fn( ( [ shadow ] ) => {
  12873. * totalShadows.mulAssign( shadow );
  12874. * //return float( 1 ); // bypass received shadows
  12875. * return shadow.mix( color( 0xff0000 ), 1 ); // modify shadow color
  12876. * } );
  12877. *
  12878. * @type {?(Function|FunctionNode<vec4>)}
  12879. * @default null
  12880. */
  12881. this.receivedShadowNode = null;
  12882. /**
  12883. * This node can be used to influence how an object using this node material
  12884. * casts shadows. To apply a color to shadows, you can simply do:
  12885. *
  12886. * ```js
  12887. * material.castShadowNode = vec4( 1, 0, 0, 1 );
  12888. * ```
  12889. *
  12890. * Which can be nice to fake colored shadows of semi-transparent objects. It
  12891. * is also common to use the property with `Fn` function so checks are performed
  12892. * per fragment.
  12893. *
  12894. * ```js
  12895. * materialCustomShadow.castShadowNode = Fn( () => {
  12896. * hash( vertexIndex ).greaterThan( 0.5 ).discard();
  12897. * return materialColor;
  12898. * } )();
  12899. * ```
  12900. *
  12901. * @type {?Node<vec4>}
  12902. * @default null
  12903. */
  12904. this.castShadowNode = null;
  12905. /**
  12906. * This node can be used to define the final output of the material.
  12907. *
  12908. * TODO: Explain the differences to `fragmentNode`.
  12909. *
  12910. * @type {?Node<vec4>}
  12911. * @default null
  12912. */
  12913. this.outputNode = null;
  12914. /**
  12915. * MRT configuration is done on renderer or pass level. This node allows to
  12916. * overwrite what values are written into MRT targets on material level. This
  12917. * can be useful for implementing selective FX features that should only affect
  12918. * specific objects.
  12919. *
  12920. * @type {?MRTNode}
  12921. * @default null
  12922. */
  12923. this.mrtNode = null;
  12924. /**
  12925. * This node property can be used if you need complete freedom in implementing
  12926. * the fragment shader. Assigning a node will replace the built-in material
  12927. * logic used in the fragment stage.
  12928. *
  12929. * @type {?Node<vec4>}
  12930. * @default null
  12931. */
  12932. this.fragmentNode = null;
  12933. /**
  12934. * This node property can be used if you need complete freedom in implementing
  12935. * the vertex shader. Assigning a node will replace the built-in material logic
  12936. * used in the vertex stage.
  12937. *
  12938. * @type {?Node<vec4>}
  12939. * @default null
  12940. */
  12941. this.vertexNode = null;
  12942. // Deprecated properties
  12943. Object.defineProperty( this, 'shadowPositionNode', { // @deprecated, r176
  12944. get: () => {
  12945. return this.receivedShadowPositionNode;
  12946. },
  12947. set: ( value ) => {
  12948. console.warn( 'THREE.NodeMaterial: ".shadowPositionNode" was renamed to ".receivedShadowPositionNode".' );
  12949. this.receivedShadowPositionNode = value;
  12950. }
  12951. } );
  12952. }
  12953. /**
  12954. * Allows to define a custom cache key that influence the material key computation
  12955. * for render objects.
  12956. *
  12957. * @return {string} The custom cache key.
  12958. */
  12959. customProgramCacheKey() {
  12960. return this.type + getCacheKey$1( this );
  12961. }
  12962. /**
  12963. * Builds this material with the given node builder.
  12964. *
  12965. * @param {NodeBuilder} builder - The current node builder.
  12966. */
  12967. build( builder ) {
  12968. this.setup( builder );
  12969. }
  12970. /**
  12971. * Setups a node material observer with the given builder.
  12972. *
  12973. * @param {NodeBuilder} builder - The current node builder.
  12974. * @return {NodeMaterialObserver} The node material observer.
  12975. */
  12976. setupObserver( builder ) {
  12977. return new NodeMaterialObserver( builder );
  12978. }
  12979. /**
  12980. * Setups the vertex and fragment stage of this node material.
  12981. *
  12982. * @param {NodeBuilder} builder - The current node builder.
  12983. */
  12984. setup( builder ) {
  12985. builder.context.setupNormal = () => this.setupNormal( builder );
  12986. builder.context.setupPositionView = () => this.setupPositionView( builder );
  12987. builder.context.setupModelViewProjection = () => this.setupModelViewProjection( builder );
  12988. const renderer = builder.renderer;
  12989. const renderTarget = renderer.getRenderTarget();
  12990. // < VERTEX STAGE >
  12991. builder.addStack();
  12992. const mvp = this.setupVertex( builder );
  12993. const vertexNode = this.vertexNode || mvp;
  12994. builder.stack.outputNode = vertexNode;
  12995. this.setupHardwareClipping( builder );
  12996. if ( this.geometryNode !== null ) {
  12997. builder.stack.outputNode = builder.stack.outputNode.bypass( this.geometryNode );
  12998. }
  12999. builder.addFlow( 'vertex', builder.removeStack() );
  13000. // < FRAGMENT STAGE >
  13001. builder.addStack();
  13002. let resultNode;
  13003. const clippingNode = this.setupClipping( builder );
  13004. if ( this.depthWrite === true || this.depthTest === true ) {
  13005. // only write depth if depth buffer is configured
  13006. if ( renderTarget !== null ) {
  13007. if ( renderTarget.depthBuffer === true ) this.setupDepth( builder );
  13008. } else {
  13009. if ( renderer.depth === true ) this.setupDepth( builder );
  13010. }
  13011. }
  13012. if ( this.fragmentNode === null ) {
  13013. this.setupDiffuseColor( builder );
  13014. this.setupVariants( builder );
  13015. const outgoingLightNode = this.setupLighting( builder );
  13016. if ( clippingNode !== null ) builder.stack.add( clippingNode );
  13017. // force unsigned floats - useful for RenderTargets
  13018. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  13019. resultNode = this.setupOutput( builder, basicOutput );
  13020. // OUTPUT NODE
  13021. output.assign( resultNode );
  13022. //
  13023. const isCustomOutput = this.outputNode !== null;
  13024. if ( isCustomOutput ) resultNode = this.outputNode;
  13025. // MRT
  13026. if ( renderTarget !== null ) {
  13027. const mrt = renderer.getMRT();
  13028. const materialMRT = this.mrtNode;
  13029. if ( mrt !== null ) {
  13030. if ( isCustomOutput ) output.assign( resultNode );
  13031. resultNode = mrt;
  13032. if ( materialMRT !== null ) {
  13033. resultNode = mrt.merge( materialMRT );
  13034. }
  13035. } else if ( materialMRT !== null ) {
  13036. resultNode = materialMRT;
  13037. }
  13038. }
  13039. } else {
  13040. let fragmentNode = this.fragmentNode;
  13041. if ( fragmentNode.isOutputStructNode !== true ) {
  13042. fragmentNode = vec4( fragmentNode );
  13043. }
  13044. resultNode = this.setupOutput( builder, fragmentNode );
  13045. }
  13046. builder.stack.outputNode = resultNode;
  13047. builder.addFlow( 'fragment', builder.removeStack() );
  13048. // < OBSERVER >
  13049. builder.observer = this.setupObserver( builder );
  13050. }
  13051. /**
  13052. * Setups the clipping node.
  13053. *
  13054. * @param {NodeBuilder} builder - The current node builder.
  13055. * @return {ClippingNode} The clipping node.
  13056. */
  13057. setupClipping( builder ) {
  13058. if ( builder.clippingContext === null ) return null;
  13059. const { unionPlanes, intersectionPlanes } = builder.clippingContext;
  13060. let result = null;
  13061. if ( unionPlanes.length > 0 || intersectionPlanes.length > 0 ) {
  13062. const samples = builder.renderer.samples;
  13063. if ( this.alphaToCoverage && samples > 1 ) {
  13064. // to be added to flow when the color/alpha value has been determined
  13065. result = clippingAlpha();
  13066. } else {
  13067. builder.stack.add( clipping() );
  13068. }
  13069. }
  13070. return result;
  13071. }
  13072. /**
  13073. * Setups the hardware clipping if available on the current device.
  13074. *
  13075. * @param {NodeBuilder} builder - The current node builder.
  13076. */
  13077. setupHardwareClipping( builder ) {
  13078. this.hardwareClipping = false;
  13079. if ( builder.clippingContext === null ) return;
  13080. const candidateCount = builder.clippingContext.unionPlanes.length;
  13081. // 8 planes supported by WebGL ANGLE_clip_cull_distance and WebGPU clip-distances
  13082. if ( candidateCount > 0 && candidateCount <= 8 && builder.isAvailable( 'clipDistance' ) ) {
  13083. builder.stack.add( hardwareClipping() );
  13084. this.hardwareClipping = true;
  13085. }
  13086. return;
  13087. }
  13088. /**
  13089. * Setups the depth of this material.
  13090. *
  13091. * @param {NodeBuilder} builder - The current node builder.
  13092. */
  13093. setupDepth( builder ) {
  13094. const { renderer, camera } = builder;
  13095. // Depth
  13096. let depthNode = this.depthNode;
  13097. if ( depthNode === null ) {
  13098. const mrt = renderer.getMRT();
  13099. if ( mrt && mrt.has( 'depth' ) ) {
  13100. depthNode = mrt.get( 'depth' );
  13101. } else if ( renderer.logarithmicDepthBuffer === true ) {
  13102. if ( camera.isPerspectiveCamera ) {
  13103. depthNode = viewZToLogarithmicDepth( positionView.z, cameraNear, cameraFar );
  13104. } else {
  13105. depthNode = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  13106. }
  13107. }
  13108. }
  13109. if ( depthNode !== null ) {
  13110. depth.assign( depthNode ).toStack();
  13111. }
  13112. }
  13113. /**
  13114. * Setups the position node in view space. This method exists
  13115. * so derived node materials can modify the implementation e.g. sprite materials.
  13116. *
  13117. * @param {NodeBuilder} builder - The current node builder.
  13118. * @return {Node<vec3>} The position in view space.
  13119. */
  13120. setupPositionView( /*builder*/ ) {
  13121. return modelViewMatrix.mul( positionLocal ).xyz;
  13122. }
  13123. /**
  13124. * Setups the position in clip space.
  13125. *
  13126. * @param {NodeBuilder} builder - The current node builder.
  13127. * @return {Node<vec4>} The position in view space.
  13128. */
  13129. setupModelViewProjection( /*builder*/ ) {
  13130. return cameraProjectionMatrix.mul( positionView );
  13131. }
  13132. /**
  13133. * Setups the logic for the vertex stage.
  13134. *
  13135. * @param {NodeBuilder} builder - The current node builder.
  13136. * @return {Node<vec4>} The position in clip space.
  13137. */
  13138. setupVertex( builder ) {
  13139. builder.addStack();
  13140. this.setupPosition( builder );
  13141. builder.context.vertex = builder.removeStack();
  13142. return modelViewProjection;
  13143. }
  13144. /**
  13145. * Setups the computation of the position in local space.
  13146. *
  13147. * @param {NodeBuilder} builder - The current node builder.
  13148. * @return {Node<vec3>} The position in local space.
  13149. */
  13150. setupPosition( builder ) {
  13151. const { object, geometry } = builder;
  13152. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  13153. morphReference( object ).toStack();
  13154. }
  13155. if ( object.isSkinnedMesh === true ) {
  13156. skinning( object ).toStack();
  13157. }
  13158. if ( this.displacementMap ) {
  13159. const displacementMap = materialReference( 'displacementMap', 'texture' );
  13160. const displacementScale = materialReference( 'displacementScale', 'float' );
  13161. const displacementBias = materialReference( 'displacementBias', 'float' );
  13162. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  13163. }
  13164. if ( object.isBatchedMesh ) {
  13165. batch( object ).toStack();
  13166. }
  13167. if ( ( object.isInstancedMesh && object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  13168. instancedMesh( object ).toStack();
  13169. }
  13170. if ( this.positionNode !== null ) {
  13171. positionLocal.assign( namespace( this.positionNode, 'POSITION' ) );
  13172. }
  13173. return positionLocal;
  13174. }
  13175. /**
  13176. * Setups the computation of the material's diffuse color.
  13177. *
  13178. * @param {NodeBuilder} builder - The current node builder.
  13179. * @param {BufferGeometry} geometry - The geometry.
  13180. */
  13181. setupDiffuseColor( { object, geometry } ) {
  13182. // MASK
  13183. if ( this.maskNode !== null ) {
  13184. // Discard if the mask is `false`
  13185. bool( this.maskNode ).not().discard();
  13186. }
  13187. // COLOR
  13188. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  13189. // VERTEX COLORS
  13190. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  13191. colorNode = colorNode.mul( vertexColor() );
  13192. }
  13193. // INSTANCED COLORS
  13194. if ( object.instanceColor ) {
  13195. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  13196. colorNode = instanceColor.mul( colorNode );
  13197. }
  13198. if ( object.isBatchedMesh && object._colorsTexture ) {
  13199. const batchColor = varyingProperty( 'vec3', 'vBatchColor' );
  13200. colorNode = batchColor.mul( colorNode );
  13201. }
  13202. // DIFFUSE COLOR
  13203. diffuseColor.assign( colorNode );
  13204. // OPACITY
  13205. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  13206. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  13207. // ALPHA TEST
  13208. let alphaTestNode = null;
  13209. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  13210. alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  13211. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  13212. }
  13213. // ALPHA HASH
  13214. if ( this.alphaHash === true ) {
  13215. diffuseColor.a.lessThan( getAlphaHashThreshold( positionLocal ) ).discard();
  13216. }
  13217. // OPAQUE
  13218. const isOpaque = this.transparent === false && this.blending === NormalBlending && this.alphaToCoverage === false;
  13219. if ( isOpaque ) {
  13220. diffuseColor.a.assign( 1.0 );
  13221. } else if ( alphaTestNode === null ) {
  13222. diffuseColor.a.lessThanEqual( 0 ).discard();
  13223. }
  13224. }
  13225. /**
  13226. * Abstract interface method that can be implemented by derived materials
  13227. * to setup material-specific node variables.
  13228. *
  13229. * @abstract
  13230. * @param {NodeBuilder} builder - The current node builder.
  13231. */
  13232. setupVariants( /*builder*/ ) {
  13233. // Interface function.
  13234. }
  13235. /**
  13236. * Setups the outgoing light node variable
  13237. *
  13238. * @return {Node<vec3>} The outgoing light node.
  13239. */
  13240. setupOutgoingLight() {
  13241. return ( this.lights === true ) ? vec3( 0 ) : diffuseColor.rgb;
  13242. }
  13243. /**
  13244. * Setups the normal node from the material.
  13245. *
  13246. * @return {Node<vec3>} The normal node.
  13247. */
  13248. setupNormal() {
  13249. return this.normalNode ? vec3( this.normalNode ) : materialNormal;
  13250. }
  13251. /**
  13252. * Setups the environment node from the material.
  13253. *
  13254. * @param {NodeBuilder} builder - The current node builder.
  13255. * @return {Node<vec4>} The environment node.
  13256. */
  13257. setupEnvironment( /*builder*/ ) {
  13258. let node = null;
  13259. if ( this.envNode ) {
  13260. node = this.envNode;
  13261. } else if ( this.envMap ) {
  13262. node = this.envMap.isCubeTexture ? materialReference( 'envMap', 'cubeTexture' ) : materialReference( 'envMap', 'texture' );
  13263. }
  13264. return node;
  13265. }
  13266. /**
  13267. * Setups the light map node from the material.
  13268. *
  13269. * @param {NodeBuilder} builder - The current node builder.
  13270. * @return {Node<vec3>} The light map node.
  13271. */
  13272. setupLightMap( builder ) {
  13273. let node = null;
  13274. if ( builder.material.lightMap ) {
  13275. node = new IrradianceNode( materialLightMap );
  13276. }
  13277. return node;
  13278. }
  13279. /**
  13280. * Setups the lights node based on the scene, environment and material.
  13281. *
  13282. * @param {NodeBuilder} builder - The current node builder.
  13283. * @return {LightsNode} The lights node.
  13284. */
  13285. setupLights( builder ) {
  13286. const materialLightsNode = [];
  13287. //
  13288. const envNode = this.setupEnvironment( builder );
  13289. if ( envNode && envNode.isLightingNode ) {
  13290. materialLightsNode.push( envNode );
  13291. }
  13292. const lightMapNode = this.setupLightMap( builder );
  13293. if ( lightMapNode && lightMapNode.isLightingNode ) {
  13294. materialLightsNode.push( lightMapNode );
  13295. }
  13296. if ( this.aoNode !== null || builder.material.aoMap ) {
  13297. const aoNode = this.aoNode !== null ? this.aoNode : materialAO;
  13298. materialLightsNode.push( new AONode( aoNode ) );
  13299. }
  13300. let lightsN = this.lightsNode || builder.lightsNode;
  13301. if ( materialLightsNode.length > 0 ) {
  13302. lightsN = builder.renderer.lighting.createNode( [ ...lightsN.getLights(), ...materialLightsNode ] );
  13303. }
  13304. return lightsN;
  13305. }
  13306. /**
  13307. * This method should be implemented by most derived materials
  13308. * since it defines the material's lighting model.
  13309. *
  13310. * @abstract
  13311. * @param {NodeBuilder} builder - The current node builder.
  13312. * @return {LightingModel} The lighting model.
  13313. */
  13314. setupLightingModel( /*builder*/ ) {
  13315. // Interface function.
  13316. }
  13317. /**
  13318. * Setups the outgoing light node.
  13319. *
  13320. * @param {NodeBuilder} builder - The current node builder.
  13321. * @return {Node<vec3>} The outgoing light node.
  13322. */
  13323. setupLighting( builder ) {
  13324. const { material } = builder;
  13325. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  13326. // OUTGOING LIGHT
  13327. const lights = this.lights === true || this.lightsNode !== null;
  13328. const lightsNode = lights ? this.setupLights( builder ) : null;
  13329. let outgoingLightNode = this.setupOutgoingLight( builder );
  13330. if ( lightsNode && lightsNode.getScope().hasLights ) {
  13331. const lightingModel = this.setupLightingModel( builder ) || null;
  13332. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  13333. } else if ( backdropNode !== null ) {
  13334. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  13335. }
  13336. // EMISSIVE
  13337. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  13338. emissive.assign( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  13339. outgoingLightNode = outgoingLightNode.add( emissive );
  13340. }
  13341. return outgoingLightNode;
  13342. }
  13343. /**
  13344. * Setup the fog.
  13345. *
  13346. * @param {NodeBuilder} builder - The current node builder.
  13347. * @param {Node<vec4>} outputNode - The existing output node.
  13348. * @return {Node<vec4>} The output node.
  13349. */
  13350. setupFog( builder, outputNode ) {
  13351. const fogNode = builder.fogNode;
  13352. if ( fogNode ) {
  13353. output.assign( outputNode );
  13354. outputNode = vec4( fogNode );
  13355. }
  13356. return outputNode;
  13357. }
  13358. /**
  13359. * Setups the output node.
  13360. *
  13361. * @param {NodeBuilder} builder - The current node builder.
  13362. * @param {Node<vec4>} outputNode - The existing output node.
  13363. * @return {Node<vec4>} The output node.
  13364. */
  13365. setupOutput( builder, outputNode ) {
  13366. // FOG
  13367. if ( this.fog === true ) {
  13368. outputNode = this.setupFog( builder, outputNode );
  13369. }
  13370. return outputNode;
  13371. }
  13372. /**
  13373. * Most classic material types have a node pendant e.g. for `MeshBasicMaterial`
  13374. * there is `MeshBasicNodeMaterial`. This utility method is intended for
  13375. * defining all material properties of the classic type in the node type.
  13376. *
  13377. * @param {Material} material - The material to copy properties with their values to this node material.
  13378. */
  13379. setDefaultValues( material ) {
  13380. // This approach is to reuse the native refreshUniforms*
  13381. // and turn available the use of features like transmission and environment in core
  13382. for ( const property in material ) {
  13383. const value = material[ property ];
  13384. if ( this[ property ] === undefined ) {
  13385. this[ property ] = value;
  13386. if ( value && value.clone ) this[ property ] = value.clone();
  13387. }
  13388. }
  13389. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  13390. for ( const key in descriptors ) {
  13391. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  13392. descriptors[ key ].get !== undefined ) {
  13393. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  13394. }
  13395. }
  13396. }
  13397. /**
  13398. * Serializes this material to JSON.
  13399. *
  13400. * @param {?(Object|string)} meta - The meta information for serialization.
  13401. * @return {Object} The serialized node.
  13402. */
  13403. toJSON( meta ) {
  13404. const isRoot = ( meta === undefined || typeof meta === 'string' );
  13405. if ( isRoot ) {
  13406. meta = {
  13407. textures: {},
  13408. images: {},
  13409. nodes: {}
  13410. };
  13411. }
  13412. const data = Material.prototype.toJSON.call( this, meta );
  13413. const nodeChildren = getNodeChildren( this );
  13414. data.inputNodes = {};
  13415. for ( const { property, childNode } of nodeChildren ) {
  13416. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  13417. }
  13418. // TODO: Copied from Object3D.toJSON
  13419. function extractFromCache( cache ) {
  13420. const values = [];
  13421. for ( const key in cache ) {
  13422. const data = cache[ key ];
  13423. delete data.metadata;
  13424. values.push( data );
  13425. }
  13426. return values;
  13427. }
  13428. if ( isRoot ) {
  13429. const textures = extractFromCache( meta.textures );
  13430. const images = extractFromCache( meta.images );
  13431. const nodes = extractFromCache( meta.nodes );
  13432. if ( textures.length > 0 ) data.textures = textures;
  13433. if ( images.length > 0 ) data.images = images;
  13434. if ( nodes.length > 0 ) data.nodes = nodes;
  13435. }
  13436. return data;
  13437. }
  13438. /**
  13439. * Copies the properties of the given node material to this instance.
  13440. *
  13441. * @param {NodeMaterial} source - The material to copy.
  13442. * @return {NodeMaterial} A reference to this node material.
  13443. */
  13444. copy( source ) {
  13445. this.lightsNode = source.lightsNode;
  13446. this.envNode = source.envNode;
  13447. this.colorNode = source.colorNode;
  13448. this.normalNode = source.normalNode;
  13449. this.opacityNode = source.opacityNode;
  13450. this.backdropNode = source.backdropNode;
  13451. this.backdropAlphaNode = source.backdropAlphaNode;
  13452. this.alphaTestNode = source.alphaTestNode;
  13453. this.maskNode = source.maskNode;
  13454. this.positionNode = source.positionNode;
  13455. this.geometryNode = source.geometryNode;
  13456. this.depthNode = source.depthNode;
  13457. this.receivedShadowPositionNode = source.receivedShadowPositionNode;
  13458. this.castShadowPositionNode = source.castShadowPositionNode;
  13459. this.receivedShadowNode = source.receivedShadowNode;
  13460. this.castShadowNode = source.castShadowNode;
  13461. this.outputNode = source.outputNode;
  13462. this.mrtNode = source.mrtNode;
  13463. this.fragmentNode = source.fragmentNode;
  13464. this.vertexNode = source.vertexNode;
  13465. return super.copy( source );
  13466. }
  13467. }
  13468. const _defaultValues$d = /*@__PURE__*/ new LineBasicMaterial();
  13469. /**
  13470. * Node material version of {@link LineBasicMaterial}.
  13471. *
  13472. * @augments NodeMaterial
  13473. */
  13474. class LineBasicNodeMaterial extends NodeMaterial {
  13475. static get type() {
  13476. return 'LineBasicNodeMaterial';
  13477. }
  13478. /**
  13479. * Constructs a new line basic node material.
  13480. *
  13481. * @param {Object} [parameters] - The configuration parameter.
  13482. */
  13483. constructor( parameters ) {
  13484. super();
  13485. /**
  13486. * This flag can be used for type testing.
  13487. *
  13488. * @type {boolean}
  13489. * @readonly
  13490. * @default true
  13491. */
  13492. this.isLineBasicNodeMaterial = true;
  13493. this.setDefaultValues( _defaultValues$d );
  13494. this.setValues( parameters );
  13495. }
  13496. }
  13497. const _defaultValues$c = /*@__PURE__*/ new LineDashedMaterial();
  13498. /**
  13499. * Node material version of {@link LineDashedMaterial}.
  13500. *
  13501. * @augments NodeMaterial
  13502. */
  13503. class LineDashedNodeMaterial extends NodeMaterial {
  13504. static get type() {
  13505. return 'LineDashedNodeMaterial';
  13506. }
  13507. /**
  13508. * Constructs a new line dashed node material.
  13509. *
  13510. * @param {Object} [parameters] - The configuration parameter.
  13511. */
  13512. constructor( parameters ) {
  13513. super();
  13514. /**
  13515. * This flag can be used for type testing.
  13516. *
  13517. * @type {boolean}
  13518. * @readonly
  13519. * @default true
  13520. */
  13521. this.isLineDashedNodeMaterial = true;
  13522. this.setDefaultValues( _defaultValues$c );
  13523. /**
  13524. * The dash offset.
  13525. *
  13526. * @type {number}
  13527. * @default 0
  13528. */
  13529. this.dashOffset = 0;
  13530. /**
  13531. * The offset of dash materials is by default inferred from the `dashOffset`
  13532. * property. This node property allows to overwrite the default
  13533. * and define the offset with a node instead.
  13534. *
  13535. * If you don't want to overwrite the offset but modify the existing
  13536. * value instead, use {@link materialLineDashOffset}.
  13537. *
  13538. * @type {?Node<float>}
  13539. * @default null
  13540. */
  13541. this.offsetNode = null;
  13542. /**
  13543. * The scale of dash materials is by default inferred from the `scale`
  13544. * property. This node property allows to overwrite the default
  13545. * and define the scale with a node instead.
  13546. *
  13547. * If you don't want to overwrite the scale but modify the existing
  13548. * value instead, use {@link materialLineScale}.
  13549. *
  13550. * @type {?Node<float>}
  13551. * @default null
  13552. */
  13553. this.dashScaleNode = null;
  13554. /**
  13555. * The dash size of dash materials is by default inferred from the `dashSize`
  13556. * property. This node property allows to overwrite the default
  13557. * and define the dash size with a node instead.
  13558. *
  13559. * If you don't want to overwrite the dash size but modify the existing
  13560. * value instead, use {@link materialLineDashSize}.
  13561. *
  13562. * @type {?Node<float>}
  13563. * @default null
  13564. */
  13565. this.dashSizeNode = null;
  13566. /**
  13567. * The gap size of dash materials is by default inferred from the `gapSize`
  13568. * property. This node property allows to overwrite the default
  13569. * and define the gap size with a node instead.
  13570. *
  13571. * If you don't want to overwrite the gap size but modify the existing
  13572. * value instead, use {@link materialLineGapSize}.
  13573. *
  13574. * @type {?Node<float>}
  13575. * @default null
  13576. */
  13577. this.gapSizeNode = null;
  13578. this.setValues( parameters );
  13579. }
  13580. /**
  13581. * Setups the dash specific node variables.
  13582. *
  13583. * @param {NodeBuilder} builder - The current node builder.
  13584. */
  13585. setupVariants( /* builder */ ) {
  13586. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  13587. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  13588. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  13589. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  13590. dashSize.assign( dashSizeNode );
  13591. gapSize.assign( gapSizeNode );
  13592. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  13593. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  13594. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  13595. }
  13596. }
  13597. let _sharedFramebuffer = null;
  13598. /**
  13599. * `ViewportTextureNode` creates an internal texture for each node instance. This module
  13600. * shares a texture across all instances of `ViewportSharedTextureNode`. It should
  13601. * be the first choice when using data of the default/screen framebuffer for performance reasons.
  13602. *
  13603. * @augments ViewportTextureNode
  13604. */
  13605. class ViewportSharedTextureNode extends ViewportTextureNode {
  13606. static get type() {
  13607. return 'ViewportSharedTextureNode';
  13608. }
  13609. /**
  13610. * Constructs a new viewport shared texture node.
  13611. *
  13612. * @param {Node} [uvNode=screenUV] - The uv node.
  13613. * @param {?Node} [levelNode=null] - The level node.
  13614. */
  13615. constructor( uvNode = screenUV, levelNode = null ) {
  13616. if ( _sharedFramebuffer === null ) {
  13617. _sharedFramebuffer = new FramebufferTexture();
  13618. }
  13619. super( uvNode, levelNode, _sharedFramebuffer );
  13620. }
  13621. updateReference() {
  13622. return this;
  13623. }
  13624. }
  13625. /**
  13626. * TSL function for creating a shared viewport texture node.
  13627. *
  13628. * @tsl
  13629. * @function
  13630. * @param {?Node} [uvNode=screenUV] - The uv node.
  13631. * @param {?Node} [levelNode=null] - The level node.
  13632. * @returns {ViewportSharedTextureNode}
  13633. */
  13634. const viewportSharedTexture = /*@__PURE__*/ nodeProxy( ViewportSharedTextureNode ).setParameterLength( 0, 2 );
  13635. const _defaultValues$b = /*@__PURE__*/ new LineDashedMaterial();
  13636. /**
  13637. * This node material can be used to render lines with a size larger than one
  13638. * by representing them as instanced meshes.
  13639. *
  13640. * @augments NodeMaterial
  13641. */
  13642. class Line2NodeMaterial extends NodeMaterial {
  13643. static get type() {
  13644. return 'Line2NodeMaterial';
  13645. }
  13646. /**
  13647. * Constructs a new node material for wide line rendering.
  13648. *
  13649. * @param {Object} [parameters={}] - The configuration parameter.
  13650. */
  13651. constructor( parameters = {} ) {
  13652. super();
  13653. /**
  13654. * This flag can be used for type testing.
  13655. *
  13656. * @type {boolean}
  13657. * @readonly
  13658. * @default true
  13659. */
  13660. this.isLine2NodeMaterial = true;
  13661. this.setDefaultValues( _defaultValues$b );
  13662. /**
  13663. * Whether vertex colors should be used or not.
  13664. *
  13665. * @type {boolean}
  13666. * @default false
  13667. */
  13668. this.useColor = parameters.vertexColors;
  13669. /**
  13670. * The dash offset.
  13671. *
  13672. * @type {number}
  13673. * @default 0
  13674. */
  13675. this.dashOffset = 0;
  13676. /**
  13677. * The line width.
  13678. *
  13679. * @type {number}
  13680. * @default 0
  13681. */
  13682. this.lineWidth = 1;
  13683. /**
  13684. * Defines the lines color.
  13685. *
  13686. * @type {?Node<vec3>}
  13687. * @default null
  13688. */
  13689. this.lineColorNode = null;
  13690. /**
  13691. * Defines the offset.
  13692. *
  13693. * @type {?Node<float>}
  13694. * @default null
  13695. */
  13696. this.offsetNode = null;
  13697. /**
  13698. * Defines the dash scale.
  13699. *
  13700. * @type {?Node<float>}
  13701. * @default null
  13702. */
  13703. this.dashScaleNode = null;
  13704. /**
  13705. * Defines the dash size.
  13706. *
  13707. * @type {?Node<float>}
  13708. * @default null
  13709. */
  13710. this.dashSizeNode = null;
  13711. /**
  13712. * Defines the gap size.
  13713. *
  13714. * @type {?Node<float>}
  13715. * @default null
  13716. */
  13717. this.gapSizeNode = null;
  13718. /**
  13719. * Blending is set to `NoBlending` since transparency
  13720. * is not supported, yet.
  13721. *
  13722. * @type {number}
  13723. * @default 0
  13724. */
  13725. this.blending = NoBlending;
  13726. this._useDash = parameters.dashed;
  13727. this._useAlphaToCoverage = true;
  13728. this._useWorldUnits = false;
  13729. this.setValues( parameters );
  13730. }
  13731. /**
  13732. * Setups the vertex and fragment stage of this node material.
  13733. *
  13734. * @param {NodeBuilder} builder - The current node builder.
  13735. */
  13736. setup( builder ) {
  13737. const { renderer } = builder;
  13738. const useAlphaToCoverage = this._useAlphaToCoverage;
  13739. const useColor = this.useColor;
  13740. const useDash = this._useDash;
  13741. const useWorldUnits = this._useWorldUnits;
  13742. const trimSegment = Fn( ( { start, end } ) => {
  13743. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  13744. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  13745. const nearEstimate = b.mul( -0.5 ).div( a );
  13746. const alpha = nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  13747. return vec4( mix( start.xyz, end.xyz, alpha ), end.w );
  13748. } ).setLayout( {
  13749. name: 'trimSegment',
  13750. type: 'vec4',
  13751. inputs: [
  13752. { name: 'start', type: 'vec4' },
  13753. { name: 'end', type: 'vec4' }
  13754. ]
  13755. } );
  13756. this.vertexNode = Fn( () => {
  13757. const instanceStart = attribute( 'instanceStart' );
  13758. const instanceEnd = attribute( 'instanceEnd' );
  13759. // camera space
  13760. const start = vec4( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ).toVar( 'start' );
  13761. const end = vec4( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) ).toVar( 'end' );
  13762. if ( useDash ) {
  13763. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  13764. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  13765. const instanceDistanceStart = attribute( 'instanceDistanceStart' );
  13766. const instanceDistanceEnd = attribute( 'instanceDistanceEnd' );
  13767. let lineDistance = positionGeometry.y.lessThan( 0.5 ).select( dashScaleNode.mul( instanceDistanceStart ), dashScaleNode.mul( instanceDistanceEnd ) );
  13768. lineDistance = lineDistance.add( offsetNode );
  13769. varyingProperty( 'float', 'lineDistance' ).assign( lineDistance );
  13770. }
  13771. if ( useWorldUnits ) {
  13772. varyingProperty( 'vec3', 'worldStart' ).assign( start.xyz );
  13773. varyingProperty( 'vec3', 'worldEnd' ).assign( end.xyz );
  13774. }
  13775. const aspect = viewport.z.div( viewport.w );
  13776. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  13777. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  13778. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  13779. // perhaps there is a more elegant solution -- WestLangley
  13780. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( -1 ); // 4th entry in the 3rd column
  13781. If( perspective, () => {
  13782. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  13783. end.assign( trimSegment( { start: start, end: end } ) );
  13784. } ).ElseIf( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  13785. start.assign( trimSegment( { start: end, end: start } ) );
  13786. } );
  13787. } );
  13788. // clip space
  13789. const clipStart = cameraProjectionMatrix.mul( start );
  13790. const clipEnd = cameraProjectionMatrix.mul( end );
  13791. // ndc space
  13792. const ndcStart = clipStart.xyz.div( clipStart.w );
  13793. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  13794. // direction
  13795. const dir = ndcEnd.xy.sub( ndcStart.xy ).toVar();
  13796. // account for clip-space aspect ratio
  13797. dir.x.assign( dir.x.mul( aspect ) );
  13798. dir.assign( dir.normalize() );
  13799. const clip = vec4().toVar();
  13800. if ( useWorldUnits ) {
  13801. // get the offset direction as perpendicular to the view vector
  13802. const worldDir = end.xyz.sub( start.xyz ).normalize();
  13803. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  13804. const worldUp = worldDir.cross( tmpFwd ).normalize();
  13805. const worldFwd = worldDir.cross( worldUp );
  13806. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  13807. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).select( start, end ) );
  13808. // height offset
  13809. const hw = materialLineWidth.mul( 0.5 );
  13810. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).select( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  13811. // don't extend the line if we're rendering dashes because we
  13812. // won't be rendering the endcaps
  13813. if ( ! useDash ) {
  13814. // cap extension
  13815. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).select( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  13816. // add width to the box
  13817. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  13818. // endcaps
  13819. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  13820. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  13821. } );
  13822. }
  13823. // project the worldpos
  13824. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  13825. // shift the depth of the projected points so the line
  13826. // segments overlap neatly
  13827. const clipPose = vec3().toVar();
  13828. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).select( ndcStart, ndcEnd ) );
  13829. clip.z.assign( clipPose.z.mul( clip.w ) );
  13830. } else {
  13831. const offset = vec2( dir.y, dir.x.negate() ).toVar( 'offset' );
  13832. // undo aspect ratio adjustment
  13833. dir.x.assign( dir.x.div( aspect ) );
  13834. offset.x.assign( offset.x.div( aspect ) );
  13835. // sign flip
  13836. offset.assign( positionGeometry.x.lessThan( 0.0 ).select( offset.negate(), offset ) );
  13837. // endcaps
  13838. If( positionGeometry.y.lessThan( 0.0 ), () => {
  13839. offset.assign( offset.sub( dir ) );
  13840. } ).ElseIf( positionGeometry.y.greaterThan( 1.0 ), () => {
  13841. offset.assign( offset.add( dir ) );
  13842. } );
  13843. // adjust for linewidth
  13844. offset.assign( offset.mul( materialLineWidth ) );
  13845. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  13846. offset.assign( offset.div( viewport.w ) );
  13847. // select end
  13848. clip.assign( positionGeometry.y.lessThan( 0.5 ).select( clipStart, clipEnd ) );
  13849. // back to clip space
  13850. offset.assign( offset.mul( clip.w ) );
  13851. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  13852. }
  13853. return clip;
  13854. } )();
  13855. const closestLineToLine = Fn( ( { p1, p2, p3, p4 } ) => {
  13856. const p13 = p1.sub( p3 );
  13857. const p43 = p4.sub( p3 );
  13858. const p21 = p2.sub( p1 );
  13859. const d1343 = p13.dot( p43 );
  13860. const d4321 = p43.dot( p21 );
  13861. const d1321 = p13.dot( p21 );
  13862. const d4343 = p43.dot( p43 );
  13863. const d2121 = p21.dot( p21 );
  13864. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  13865. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  13866. const mua = numer.div( denom ).clamp();
  13867. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  13868. return vec2( mua, mub );
  13869. } );
  13870. this.colorNode = Fn( () => {
  13871. const vUv = uv();
  13872. if ( useDash ) {
  13873. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  13874. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  13875. dashSize.assign( dashSizeNode );
  13876. gapSize.assign( gapSizeNode );
  13877. const vLineDistance = varyingProperty( 'float', 'lineDistance' );
  13878. vUv.y.lessThan( -1 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  13879. vLineDistance.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  13880. }
  13881. const alpha = float( 1 ).toVar( 'alpha' );
  13882. if ( useWorldUnits ) {
  13883. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  13884. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  13885. // Find the closest points on the view ray and the line segment
  13886. const rayEnd = varyingProperty( 'vec4', 'worldPos' ).xyz.normalize().mul( 1e5 );
  13887. const lineDir = worldEnd.sub( worldStart );
  13888. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  13889. const p1 = worldStart.add( lineDir.mul( params.x ) );
  13890. const p2 = rayEnd.mul( params.y );
  13891. const delta = p1.sub( p2 );
  13892. const len = delta.length();
  13893. const norm = len.div( materialLineWidth );
  13894. if ( ! useDash ) {
  13895. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  13896. const dnorm = norm.fwidth();
  13897. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  13898. } else {
  13899. norm.greaterThan( 0.5 ).discard();
  13900. }
  13901. }
  13902. } else {
  13903. // round endcaps
  13904. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  13905. const a = vUv.x;
  13906. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  13907. const len2 = a.mul( a ).add( b.mul( b ) );
  13908. const dlen = float( len2.fwidth() ).toVar( 'dlen' );
  13909. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  13910. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  13911. } );
  13912. } else {
  13913. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  13914. const a = vUv.x;
  13915. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  13916. const len2 = a.mul( a ).add( b.mul( b ) );
  13917. len2.greaterThan( 1.0 ).discard();
  13918. } );
  13919. }
  13920. }
  13921. let lineColorNode;
  13922. if ( this.lineColorNode ) {
  13923. lineColorNode = this.lineColorNode;
  13924. } else {
  13925. if ( useColor ) {
  13926. const instanceColorStart = attribute( 'instanceColorStart' );
  13927. const instanceColorEnd = attribute( 'instanceColorEnd' );
  13928. const instanceColor = positionGeometry.y.lessThan( 0.5 ).select( instanceColorStart, instanceColorEnd );
  13929. lineColorNode = instanceColor.mul( materialColor );
  13930. } else {
  13931. lineColorNode = materialColor;
  13932. }
  13933. }
  13934. return vec4( lineColorNode, alpha );
  13935. } )();
  13936. if ( this.transparent ) {
  13937. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  13938. this.outputNode = vec4( this.colorNode.rgb.mul( opacityNode ).add( viewportSharedTexture().rgb.mul( opacityNode.oneMinus() ) ), this.colorNode.a );
  13939. }
  13940. super.setup( builder );
  13941. }
  13942. /**
  13943. * Whether the lines should sized in world units or not.
  13944. * When set to `false` the unit is pixel.
  13945. *
  13946. * @type {boolean}
  13947. * @default false
  13948. */
  13949. get worldUnits() {
  13950. return this._useWorldUnits;
  13951. }
  13952. set worldUnits( value ) {
  13953. if ( this._useWorldUnits !== value ) {
  13954. this._useWorldUnits = value;
  13955. this.needsUpdate = true;
  13956. }
  13957. }
  13958. /**
  13959. * Whether the lines should be dashed or not.
  13960. *
  13961. * @type {boolean}
  13962. * @default false
  13963. */
  13964. get dashed() {
  13965. return this._useDash;
  13966. }
  13967. set dashed( value ) {
  13968. if ( this._useDash !== value ) {
  13969. this._useDash = value;
  13970. this.needsUpdate = true;
  13971. }
  13972. }
  13973. /**
  13974. * Whether alpha to coverage should be used or not.
  13975. *
  13976. * @type {boolean}
  13977. * @default true
  13978. */
  13979. get alphaToCoverage() {
  13980. return this._useAlphaToCoverage;
  13981. }
  13982. set alphaToCoverage( value ) {
  13983. if ( this._useAlphaToCoverage !== value ) {
  13984. this._useAlphaToCoverage = value;
  13985. this.needsUpdate = true;
  13986. }
  13987. }
  13988. }
  13989. /**
  13990. * Packs a direction vector into a color value.
  13991. *
  13992. * @tsl
  13993. * @function
  13994. * @param {Node<vec3>} node - The direction to pack.
  13995. * @return {Node<vec3>} The color.
  13996. */
  13997. const directionToColor = ( node ) => nodeObject( node ).mul( 0.5 ).add( 0.5 );
  13998. /**
  13999. * Unpacks a color value into a direction vector.
  14000. *
  14001. * @tsl
  14002. * @function
  14003. * @param {Node<vec3>} node - The color to unpack.
  14004. * @return {Node<vec3>} The direction.
  14005. */
  14006. const colorToDirection = ( node ) => nodeObject( node ).mul( 2.0 ).sub( 1 );
  14007. const _defaultValues$a = /*@__PURE__*/ new MeshNormalMaterial();
  14008. /**
  14009. * Node material version of {@link MeshNormalMaterial}.
  14010. *
  14011. * @augments NodeMaterial
  14012. */
  14013. class MeshNormalNodeMaterial extends NodeMaterial {
  14014. static get type() {
  14015. return 'MeshNormalNodeMaterial';
  14016. }
  14017. /**
  14018. * Constructs a new mesh normal node material.
  14019. *
  14020. * @param {Object} [parameters] - The configuration parameter.
  14021. */
  14022. constructor( parameters ) {
  14023. super();
  14024. /**
  14025. * This flag can be used for type testing.
  14026. *
  14027. * @type {boolean}
  14028. * @readonly
  14029. * @default true
  14030. */
  14031. this.isMeshNormalNodeMaterial = true;
  14032. this.setDefaultValues( _defaultValues$a );
  14033. this.setValues( parameters );
  14034. }
  14035. /**
  14036. * Overwrites the default implementation by computing the diffuse color
  14037. * based on the normal data.
  14038. */
  14039. setupDiffuseColor() {
  14040. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  14041. // By convention, a normal packed to RGB is in sRGB color space. Convert it to working color space.
  14042. diffuseColor.assign( colorSpaceToWorking( vec4( directionToColor( transformedNormalView ), opacityNode ), SRGBColorSpace ) );
  14043. }
  14044. }
  14045. /**
  14046. * Can be used to compute texture coordinates for projecting an
  14047. * equirectangular texture onto a mesh for using it as the scene's
  14048. * background.
  14049. *
  14050. * ```js
  14051. * scene.backgroundNode = texture( equirectTexture, equirectUV() );
  14052. * ```
  14053. *
  14054. * @augments TempNode
  14055. */
  14056. class EquirectUVNode extends TempNode {
  14057. static get type() {
  14058. return 'EquirectUVNode';
  14059. }
  14060. /**
  14061. * Constructs a new equirect uv node.
  14062. *
  14063. * @param {Node<vec3>} [dirNode=positionWorldDirection] - A direction vector for sampling which is by default `positionWorldDirection`.
  14064. */
  14065. constructor( dirNode = positionWorldDirection ) {
  14066. super( 'vec2' );
  14067. /**
  14068. * A direction vector for sampling why is by default `positionWorldDirection`.
  14069. *
  14070. * @type {Node<vec3>}
  14071. */
  14072. this.dirNode = dirNode;
  14073. }
  14074. setup() {
  14075. const dir = this.dirNode;
  14076. const u = dir.z.atan( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  14077. const v = dir.y.clamp( -1, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  14078. return vec2( u, v );
  14079. }
  14080. }
  14081. /**
  14082. * TSL function for creating an equirect uv node.
  14083. *
  14084. * @tsl
  14085. * @function
  14086. * @param {?Node<vec3>} [dirNode=positionWorldDirection] - A direction vector for sampling which is by default `positionWorldDirection`.
  14087. * @returns {EquirectUVNode}
  14088. */
  14089. const equirectUV = /*@__PURE__*/ nodeProxy( EquirectUVNode ).setParameterLength( 0, 1 );
  14090. // @TODO: Consider rename WebGLCubeRenderTarget to just CubeRenderTarget
  14091. /**
  14092. * This class represents a cube render target. It is a special version
  14093. * of `WebGLCubeRenderTarget` which is compatible with `WebGPURenderer`.
  14094. *
  14095. * @augments WebGLCubeRenderTarget
  14096. */
  14097. class CubeRenderTarget extends WebGLCubeRenderTarget {
  14098. /**
  14099. * Constructs a new cube render target.
  14100. *
  14101. * @param {number} [size=1] - The size of the render target.
  14102. * @param {RenderTarget~Options} [options] - The configuration object.
  14103. */
  14104. constructor( size = 1, options = {} ) {
  14105. super( size, options );
  14106. /**
  14107. * This flag can be used for type testing.
  14108. *
  14109. * @type {boolean}
  14110. * @readonly
  14111. * @default true
  14112. */
  14113. this.isCubeRenderTarget = true;
  14114. }
  14115. /**
  14116. * Converts the given equirectangular texture to a cube map.
  14117. *
  14118. * @param {Renderer} renderer - The renderer.
  14119. * @param {Texture} texture - The equirectangular texture.
  14120. * @return {CubeRenderTarget} A reference to this cube render target.
  14121. */
  14122. fromEquirectangularTexture( renderer, texture$1 ) {
  14123. const currentMinFilter = texture$1.minFilter;
  14124. const currentGenerateMipmaps = texture$1.generateMipmaps;
  14125. texture$1.generateMipmaps = true;
  14126. this.texture.type = texture$1.type;
  14127. this.texture.colorSpace = texture$1.colorSpace;
  14128. this.texture.generateMipmaps = texture$1.generateMipmaps;
  14129. this.texture.minFilter = texture$1.minFilter;
  14130. this.texture.magFilter = texture$1.magFilter;
  14131. const geometry = new BoxGeometry( 5, 5, 5 );
  14132. const uvNode = equirectUV( positionWorldDirection );
  14133. const material = new NodeMaterial();
  14134. material.colorNode = texture( texture$1, uvNode, 0 );
  14135. material.side = BackSide;
  14136. material.blending = NoBlending;
  14137. const mesh = new Mesh( geometry, material );
  14138. const scene = new Scene();
  14139. scene.add( mesh );
  14140. // Avoid blurred poles
  14141. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  14142. const camera = new CubeCamera( 1, 10, this );
  14143. const currentMRT = renderer.getMRT();
  14144. renderer.setMRT( null );
  14145. camera.update( renderer, scene );
  14146. renderer.setMRT( currentMRT );
  14147. texture$1.minFilter = currentMinFilter;
  14148. texture$1.currentGenerateMipmaps = currentGenerateMipmaps;
  14149. mesh.geometry.dispose();
  14150. mesh.material.dispose();
  14151. return this;
  14152. }
  14153. }
  14154. const _cache$1 = new WeakMap();
  14155. /**
  14156. * This node can be used to automatically convert environment maps in the
  14157. * equirectangular format into the cube map format.
  14158. *
  14159. * @augments TempNode
  14160. */
  14161. class CubeMapNode extends TempNode {
  14162. static get type() {
  14163. return 'CubeMapNode';
  14164. }
  14165. /**
  14166. * Constructs a new cube map node.
  14167. *
  14168. * @param {Node} envNode - The node representing the environment map.
  14169. */
  14170. constructor( envNode ) {
  14171. super( 'vec3' );
  14172. /**
  14173. * The node representing the environment map.
  14174. *
  14175. * @type {Node}
  14176. */
  14177. this.envNode = envNode;
  14178. /**
  14179. * A reference to the internal cube texture.
  14180. *
  14181. * @private
  14182. * @type {?CubeTexture}
  14183. * @default null
  14184. */
  14185. this._cubeTexture = null;
  14186. /**
  14187. * A reference to the internal cube texture node.
  14188. *
  14189. * @private
  14190. * @type {CubeTextureNode}
  14191. */
  14192. this._cubeTextureNode = cubeTexture( null );
  14193. const defaultTexture = new CubeTexture();
  14194. defaultTexture.isRenderTargetTexture = true;
  14195. /**
  14196. * A default cube texture that acts as a placeholder.
  14197. * It is used when the conversion from equirectangular to cube
  14198. * map has not finished yet for a given texture.
  14199. *
  14200. * @private
  14201. * @type {CubeTexture}
  14202. */
  14203. this._defaultTexture = defaultTexture;
  14204. /**
  14205. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  14206. * the texture once per render in its {@link CubeMapNode#updateBefore} method.
  14207. *
  14208. * @type {string}
  14209. * @default 'render'
  14210. */
  14211. this.updateBeforeType = NodeUpdateType.RENDER;
  14212. }
  14213. updateBefore( frame ) {
  14214. const { renderer, material } = frame;
  14215. const envNode = this.envNode;
  14216. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  14217. const texture = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  14218. if ( texture && texture.isTexture ) {
  14219. const mapping = texture.mapping;
  14220. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  14221. // check for converted cubemap map
  14222. if ( _cache$1.has( texture ) ) {
  14223. const cubeMap = _cache$1.get( texture );
  14224. mapTextureMapping( cubeMap, texture.mapping );
  14225. this._cubeTexture = cubeMap;
  14226. } else {
  14227. // create cube map from equirectangular map
  14228. const image = texture.image;
  14229. if ( isEquirectangularMapReady$1( image ) ) {
  14230. const renderTarget = new CubeRenderTarget( image.height );
  14231. renderTarget.fromEquirectangularTexture( renderer, texture );
  14232. mapTextureMapping( renderTarget.texture, texture.mapping );
  14233. this._cubeTexture = renderTarget.texture;
  14234. _cache$1.set( texture, renderTarget.texture );
  14235. texture.addEventListener( 'dispose', onTextureDispose );
  14236. } else {
  14237. // default cube texture as fallback when equirectangular texture is not yet loaded
  14238. this._cubeTexture = this._defaultTexture;
  14239. }
  14240. }
  14241. //
  14242. this._cubeTextureNode.value = this._cubeTexture;
  14243. } else {
  14244. // envNode already refers to a cube map
  14245. this._cubeTextureNode = this.envNode;
  14246. }
  14247. }
  14248. }
  14249. }
  14250. setup( builder ) {
  14251. this.updateBefore( builder );
  14252. return this._cubeTextureNode;
  14253. }
  14254. }
  14255. /**
  14256. * Returns true if the given equirectangular image has been fully loaded
  14257. * and is ready for further processing.
  14258. *
  14259. * @private
  14260. * @param {Image} image - The equirectangular image to check.
  14261. * @return {boolean} Whether the image is ready or not.
  14262. */
  14263. function isEquirectangularMapReady$1( image ) {
  14264. if ( image === null || image === undefined ) return false;
  14265. return image.height > 0;
  14266. }
  14267. /**
  14268. * This function is executed when `dispose()` is called on the equirectangular
  14269. * texture. In this case, the generated cube map with its render target
  14270. * is deleted as well.
  14271. *
  14272. * @private
  14273. * @param {Object} event - The event object.
  14274. */
  14275. function onTextureDispose( event ) {
  14276. const texture = event.target;
  14277. texture.removeEventListener( 'dispose', onTextureDispose );
  14278. const renderTarget = _cache$1.get( texture );
  14279. if ( renderTarget !== undefined ) {
  14280. _cache$1.delete( texture );
  14281. renderTarget.dispose();
  14282. }
  14283. }
  14284. /**
  14285. * This function makes sure the generated cube map uses the correct
  14286. * texture mapping that corresponds to the equirectangular original.
  14287. *
  14288. * @private
  14289. * @param {Texture} texture - The cube texture.
  14290. * @param {number} mapping - The original texture mapping.
  14291. */
  14292. function mapTextureMapping( texture, mapping ) {
  14293. if ( mapping === EquirectangularReflectionMapping ) {
  14294. texture.mapping = CubeReflectionMapping;
  14295. } else if ( mapping === EquirectangularRefractionMapping ) {
  14296. texture.mapping = CubeRefractionMapping;
  14297. }
  14298. }
  14299. /**
  14300. * TSL function for creating a cube map node.
  14301. *
  14302. * @tsl
  14303. * @function
  14304. * @param {Node} envNode - The node representing the environment map.
  14305. * @returns {CubeMapNode}
  14306. */
  14307. const cubeMapNode = /*@__PURE__*/ nodeProxy( CubeMapNode ).setParameterLength( 1 );
  14308. /**
  14309. * Represents a basic model for Image-based lighting (IBL). The environment
  14310. * is defined via environment maps in the equirectangular or cube map format.
  14311. * `BasicEnvironmentNode` is intended for non-PBR materials like {@link MeshBasicNodeMaterial}
  14312. * or {@link MeshPhongNodeMaterial}.
  14313. *
  14314. * @augments LightingNode
  14315. */
  14316. class BasicEnvironmentNode extends LightingNode {
  14317. static get type() {
  14318. return 'BasicEnvironmentNode';
  14319. }
  14320. /**
  14321. * Constructs a new basic environment node.
  14322. *
  14323. * @param {Node} [envNode=null] - A node representing the environment.
  14324. */
  14325. constructor( envNode = null ) {
  14326. super();
  14327. /**
  14328. * A node representing the environment.
  14329. *
  14330. * @type {Node}
  14331. * @default null
  14332. */
  14333. this.envNode = envNode;
  14334. }
  14335. setup( builder ) {
  14336. // environment property is used in the finish() method of BasicLightingModel
  14337. builder.context.environment = cubeMapNode( this.envNode );
  14338. }
  14339. }
  14340. /**
  14341. * A specific version of {@link IrradianceNode} that is only relevant
  14342. * for {@link MeshBasicNodeMaterial}. Since the material is unlit, it
  14343. * requires a special scaling factor for the light map.
  14344. *
  14345. * @augments LightingNode
  14346. */
  14347. class BasicLightMapNode extends LightingNode {
  14348. static get type() {
  14349. return 'BasicLightMapNode';
  14350. }
  14351. /**
  14352. * Constructs a new basic light map node.
  14353. *
  14354. * @param {?Node<vec3>} [lightMapNode=null] - The light map node.
  14355. */
  14356. constructor( lightMapNode = null ) {
  14357. super();
  14358. /**
  14359. * The light map node.
  14360. *
  14361. * @type {?Node<vec3>}
  14362. */
  14363. this.lightMapNode = lightMapNode;
  14364. }
  14365. setup( builder ) {
  14366. // irradianceLightMap property is used in the indirectDiffuse() method of BasicLightingModel
  14367. const RECIPROCAL_PI = float( 1 / Math.PI );
  14368. builder.context.irradianceLightMap = this.lightMapNode.mul( RECIPROCAL_PI );
  14369. }
  14370. }
  14371. /**
  14372. * Abstract class for implementing lighting models. The module defines
  14373. * multiple methods that concrete lighting models can implement. These
  14374. * methods are executed at different points during the light evaluation
  14375. * process.
  14376. */
  14377. class LightingModel {
  14378. /**
  14379. * This method is intended for setting up lighting model and context data
  14380. * which are later used in the evaluation process.
  14381. *
  14382. * @abstract
  14383. * @param {NodeBuilder} builder - The current node builder.
  14384. */
  14385. start( builder ) {
  14386. // lights ( direct )
  14387. builder.lightsNode.setupLights( builder, builder.lightsNode.getLightNodes( builder ) );
  14388. // indirect
  14389. this.indirect( builder );
  14390. }
  14391. /**
  14392. * This method is intended for executing final tasks like final updates
  14393. * to the outgoing light.
  14394. *
  14395. * @abstract
  14396. * @param {NodeBuilder} builder - The current node builder.
  14397. */
  14398. finish( /*builder*/ ) { }
  14399. /**
  14400. * This method is intended for implementing the direct light term and
  14401. * executed during the build process of directional, point and spot light nodes.
  14402. *
  14403. * @abstract
  14404. * @param {Object} lightData - The light data.
  14405. * @param {NodeBuilder} builder - The current node builder.
  14406. */
  14407. direct( /*lightData, builder*/ ) { }
  14408. /**
  14409. * This method is intended for implementing the direct light term for
  14410. * rect area light nodes.
  14411. *
  14412. * @abstract
  14413. * @param {Object} lightData - The light data.
  14414. * @param {NodeBuilder} builder - The current node builder.
  14415. */
  14416. directRectArea( /*lightData, builder*/ ) {}
  14417. /**
  14418. * This method is intended for implementing the indirect light term.
  14419. *
  14420. * @abstract
  14421. * @param {NodeBuilder} builder - The current node builder.
  14422. */
  14423. indirect( /*builder*/ ) { }
  14424. /**
  14425. * This method is intended for implementing the ambient occlusion term.
  14426. * Unlike other methods, this method must be called manually by the lighting
  14427. * model in its indirect term.
  14428. *
  14429. * @abstract
  14430. * @param {NodeBuilder} builder - The current node builder.
  14431. */
  14432. ambientOcclusion( /*input, stack, builder*/ ) { }
  14433. }
  14434. /**
  14435. * Represents the lighting model for unlit materials. The only light contribution
  14436. * is baked indirect lighting modulated with ambient occlusion and the material's
  14437. * diffuse color. Environment mapping is supported. Used in {@link MeshBasicNodeMaterial}.
  14438. *
  14439. * @augments LightingModel
  14440. */
  14441. class BasicLightingModel extends LightingModel {
  14442. /**
  14443. * Constructs a new basic lighting model.
  14444. */
  14445. constructor() {
  14446. super();
  14447. }
  14448. /**
  14449. * Implements the baked indirect lighting with its modulation.
  14450. *
  14451. * @param {NodeBuilder} builder - The current node builder.
  14452. */
  14453. indirect( { context } ) {
  14454. const ambientOcclusion = context.ambientOcclusion;
  14455. const reflectedLight = context.reflectedLight;
  14456. const irradianceLightMap = context.irradianceLightMap;
  14457. reflectedLight.indirectDiffuse.assign( vec4( 0.0 ) );
  14458. // accumulation (baked indirect lighting only)
  14459. if ( irradianceLightMap ) {
  14460. reflectedLight.indirectDiffuse.addAssign( irradianceLightMap );
  14461. } else {
  14462. reflectedLight.indirectDiffuse.addAssign( vec4( 1.0, 1.0, 1.0, 0.0 ) );
  14463. }
  14464. // modulation
  14465. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  14466. reflectedLight.indirectDiffuse.mulAssign( diffuseColor.rgb );
  14467. }
  14468. /**
  14469. * Implements the environment mapping.
  14470. *
  14471. * @param {NodeBuilder} builder - The current node builder.
  14472. */
  14473. finish( builder ) {
  14474. const { material, context } = builder;
  14475. const outgoingLight = context.outgoingLight;
  14476. const envNode = builder.context.environment;
  14477. if ( envNode ) {
  14478. switch ( material.combine ) {
  14479. case MultiplyOperation:
  14480. outgoingLight.rgb.assign( mix( outgoingLight.rgb, outgoingLight.rgb.mul( envNode.rgb ), materialSpecularStrength.mul( materialReflectivity ) ) );
  14481. break;
  14482. case MixOperation:
  14483. outgoingLight.rgb.assign( mix( outgoingLight.rgb, envNode.rgb, materialSpecularStrength.mul( materialReflectivity ) ) );
  14484. break;
  14485. case AddOperation:
  14486. outgoingLight.rgb.addAssign( envNode.rgb.mul( materialSpecularStrength.mul( materialReflectivity ) ) );
  14487. break;
  14488. default:
  14489. console.warn( 'THREE.BasicLightingModel: Unsupported .combine value:', material.combine );
  14490. break;
  14491. }
  14492. }
  14493. }
  14494. }
  14495. const _defaultValues$9 = /*@__PURE__*/ new MeshBasicMaterial();
  14496. /**
  14497. * Node material version of {@link MeshBasicMaterial}.
  14498. *
  14499. * @augments NodeMaterial
  14500. */
  14501. class MeshBasicNodeMaterial extends NodeMaterial {
  14502. static get type() {
  14503. return 'MeshBasicNodeMaterial';
  14504. }
  14505. /**
  14506. * Constructs a new mesh basic node material.
  14507. *
  14508. * @param {Object} [parameters] - The configuration parameter.
  14509. */
  14510. constructor( parameters ) {
  14511. super();
  14512. /**
  14513. * This flag can be used for type testing.
  14514. *
  14515. * @type {boolean}
  14516. * @readonly
  14517. * @default true
  14518. */
  14519. this.isMeshBasicNodeMaterial = true;
  14520. /**
  14521. * Although the basic material is by definition unlit, we set
  14522. * this property to `true` since we use a lighting model to compute
  14523. * the outgoing light of the fragment shader.
  14524. *
  14525. * @type {boolean}
  14526. * @default true
  14527. */
  14528. this.lights = true;
  14529. this.setDefaultValues( _defaultValues$9 );
  14530. this.setValues( parameters );
  14531. }
  14532. /**
  14533. * Basic materials are not affected by normal and bump maps so we
  14534. * return by default {@link normalView}.
  14535. *
  14536. * @return {Node<vec3>} The normal node.
  14537. */
  14538. setupNormal() {
  14539. return normalView; // see #28839
  14540. }
  14541. /**
  14542. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  14543. * to implement the default environment mapping.
  14544. *
  14545. * @param {NodeBuilder} builder - The current node builder.
  14546. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  14547. */
  14548. setupEnvironment( builder ) {
  14549. const envNode = super.setupEnvironment( builder );
  14550. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  14551. }
  14552. /**
  14553. * This method must be overwritten since light maps are evaluated
  14554. * with a special scaling factor for basic materials.
  14555. *
  14556. * @param {NodeBuilder} builder - The current node builder.
  14557. * @return {?BasicLightMapNode<vec3>} The light map node.
  14558. */
  14559. setupLightMap( builder ) {
  14560. let node = null;
  14561. if ( builder.material.lightMap ) {
  14562. node = new BasicLightMapNode( materialLightMap );
  14563. }
  14564. return node;
  14565. }
  14566. /**
  14567. * The material overwrites this method because `lights` is set to `true` but
  14568. * we still want to return the diffuse color as the outgoing light.
  14569. *
  14570. * @return {Node<vec3>} The outgoing light node.
  14571. */
  14572. setupOutgoingLight() {
  14573. return diffuseColor.rgb;
  14574. }
  14575. /**
  14576. * Setups the lighting model.
  14577. *
  14578. * @return {BasicLightingModel} The lighting model.
  14579. */
  14580. setupLightingModel() {
  14581. return new BasicLightingModel();
  14582. }
  14583. }
  14584. const F_Schlick = /*@__PURE__*/ Fn( ( { f0, f90, dotVH } ) => {
  14585. // Original approximation by Christophe Schlick '94
  14586. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  14587. // Optimized variant (presented by Epic at SIGGRAPH '13)
  14588. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  14589. const fresnel = dotVH.mul( -5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  14590. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  14591. } ); // validated
  14592. const BRDF_Lambert = /*@__PURE__*/ Fn( ( inputs ) => {
  14593. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  14594. } ); // validated
  14595. const G_BlinnPhong_Implicit = () => float( 0.25 );
  14596. const D_BlinnPhong = /*@__PURE__*/ Fn( ( { dotNH } ) => {
  14597. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  14598. } );
  14599. const BRDF_BlinnPhong = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  14600. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  14601. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  14602. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  14603. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  14604. const G = G_BlinnPhong_Implicit();
  14605. const D = D_BlinnPhong( { dotNH } );
  14606. return F.mul( G ).mul( D );
  14607. } );
  14608. /**
  14609. * Represents the lighting model for a phong material. Used in {@link MeshPhongNodeMaterial}.
  14610. *
  14611. * @augments BasicLightingModel
  14612. */
  14613. class PhongLightingModel extends BasicLightingModel {
  14614. /**
  14615. * Constructs a new phong lighting model.
  14616. *
  14617. * @param {boolean} [specular=true] - Whether specular is supported or not.
  14618. */
  14619. constructor( specular = true ) {
  14620. super();
  14621. /**
  14622. * Whether specular is supported or not. Set this to `false` if you are
  14623. * looking for a Lambert-like material meaning a material for non-shiny
  14624. * surfaces, without specular highlights.
  14625. *
  14626. * @type {boolean}
  14627. * @default true
  14628. */
  14629. this.specular = specular;
  14630. }
  14631. /**
  14632. * Implements the direct lighting. The specular portion is optional an can be controlled
  14633. * with the {@link PhongLightingModel#specular} flag.
  14634. *
  14635. * @param {Object} lightData - The light data.
  14636. */
  14637. direct( { lightDirection, lightColor, reflectedLight } ) {
  14638. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  14639. const irradiance = dotNL.mul( lightColor );
  14640. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  14641. if ( this.specular === true ) {
  14642. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  14643. }
  14644. }
  14645. /**
  14646. * Implements the indirect lighting.
  14647. *
  14648. * @param {NodeBuilder} builder - The current node builder.
  14649. */
  14650. indirect( builder ) {
  14651. const { ambientOcclusion, irradiance, reflectedLight } = builder.context;
  14652. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  14653. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  14654. }
  14655. }
  14656. const _defaultValues$8 = /*@__PURE__*/ new MeshLambertMaterial();
  14657. /**
  14658. * Node material version of {@link MeshLambertMaterial}.
  14659. *
  14660. * @augments NodeMaterial
  14661. */
  14662. class MeshLambertNodeMaterial extends NodeMaterial {
  14663. static get type() {
  14664. return 'MeshLambertNodeMaterial';
  14665. }
  14666. /**
  14667. * Constructs a new mesh lambert node material.
  14668. *
  14669. * @param {Object} [parameters] - The configuration parameter.
  14670. */
  14671. constructor( parameters ) {
  14672. super();
  14673. /**
  14674. * This flag can be used for type testing.
  14675. *
  14676. * @type {boolean}
  14677. * @readonly
  14678. * @default true
  14679. */
  14680. this.isMeshLambertNodeMaterial = true;
  14681. /**
  14682. * Set to `true` because lambert materials react on lights.
  14683. *
  14684. * @type {boolean}
  14685. * @default true
  14686. */
  14687. this.lights = true;
  14688. this.setDefaultValues( _defaultValues$8 );
  14689. this.setValues( parameters );
  14690. }
  14691. /**
  14692. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  14693. * to implement the default environment mapping.
  14694. *
  14695. * @param {NodeBuilder} builder - The current node builder.
  14696. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  14697. */
  14698. setupEnvironment( builder ) {
  14699. const envNode = super.setupEnvironment( builder );
  14700. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  14701. }
  14702. /**
  14703. * Setups the lighting model.
  14704. *
  14705. * @return {PhongLightingModel} The lighting model.
  14706. */
  14707. setupLightingModel( /*builder*/ ) {
  14708. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  14709. }
  14710. }
  14711. const _defaultValues$7 = /*@__PURE__*/ new MeshPhongMaterial();
  14712. /**
  14713. * Node material version of {@link MeshPhongMaterial}.
  14714. *
  14715. * @augments NodeMaterial
  14716. */
  14717. class MeshPhongNodeMaterial extends NodeMaterial {
  14718. static get type() {
  14719. return 'MeshPhongNodeMaterial';
  14720. }
  14721. /**
  14722. * Constructs a new mesh lambert node material.
  14723. *
  14724. * @param {Object} [parameters] - The configuration parameter.
  14725. */
  14726. constructor( parameters ) {
  14727. super();
  14728. /**
  14729. * This flag can be used for type testing.
  14730. *
  14731. * @type {boolean}
  14732. * @readonly
  14733. * @default true
  14734. */
  14735. this.isMeshPhongNodeMaterial = true;
  14736. /**
  14737. * Set to `true` because phong materials react on lights.
  14738. *
  14739. * @type {boolean}
  14740. * @default true
  14741. */
  14742. this.lights = true;
  14743. /**
  14744. * The shininess of phong materials is by default inferred from the `shininess`
  14745. * property. This node property allows to overwrite the default
  14746. * and define the shininess with a node instead.
  14747. *
  14748. * If you don't want to overwrite the shininess but modify the existing
  14749. * value instead, use {@link materialShininess}.
  14750. *
  14751. * @type {?Node<float>}
  14752. * @default null
  14753. */
  14754. this.shininessNode = null;
  14755. /**
  14756. * The specular color of phong materials is by default inferred from the
  14757. * `specular` property. This node property allows to overwrite the default
  14758. * and define the specular color with a node instead.
  14759. *
  14760. * If you don't want to overwrite the specular color but modify the existing
  14761. * value instead, use {@link materialSpecular}.
  14762. *
  14763. * @type {?Node<vec3>}
  14764. * @default null
  14765. */
  14766. this.specularNode = null;
  14767. this.setDefaultValues( _defaultValues$7 );
  14768. this.setValues( parameters );
  14769. }
  14770. /**
  14771. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  14772. * to implement the default environment mapping.
  14773. *
  14774. * @param {NodeBuilder} builder - The current node builder.
  14775. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  14776. */
  14777. setupEnvironment( builder ) {
  14778. const envNode = super.setupEnvironment( builder );
  14779. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  14780. }
  14781. /**
  14782. * Setups the lighting model.
  14783. *
  14784. * @return {PhongLightingModel} The lighting model.
  14785. */
  14786. setupLightingModel( /*builder*/ ) {
  14787. return new PhongLightingModel();
  14788. }
  14789. /**
  14790. * Setups the phong specific node variables.
  14791. *
  14792. * @param {NodeBuilder} builder - The current node builder.
  14793. */
  14794. setupVariants( /*builder*/ ) {
  14795. // SHININESS
  14796. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  14797. shininess.assign( shininessNode );
  14798. // SPECULAR COLOR
  14799. const specularNode = this.specularNode || materialSpecular;
  14800. specularColor.assign( specularNode );
  14801. }
  14802. copy( source ) {
  14803. this.shininessNode = source.shininessNode;
  14804. this.specularNode = source.specularNode;
  14805. return super.copy( source );
  14806. }
  14807. }
  14808. const getGeometryRoughness = /*@__PURE__*/ Fn( ( builder ) => {
  14809. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  14810. return float( 0 );
  14811. }
  14812. const dxy = normalView.dFdx().abs().max( normalView.dFdy().abs() );
  14813. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  14814. return geometryRoughness;
  14815. } );
  14816. const getRoughness = /*@__PURE__*/ Fn( ( inputs ) => {
  14817. const { roughness } = inputs;
  14818. const geometryRoughness = getGeometryRoughness();
  14819. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  14820. roughnessFactor = roughnessFactor.add( geometryRoughness );
  14821. roughnessFactor = roughnessFactor.min( 1.0 );
  14822. return roughnessFactor;
  14823. } );
  14824. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  14825. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  14826. const V_GGX_SmithCorrelated = /*@__PURE__*/ Fn( ( { alpha, dotNL, dotNV } ) => {
  14827. const a2 = alpha.pow2();
  14828. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  14829. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  14830. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  14831. } ).setLayout( {
  14832. name: 'V_GGX_SmithCorrelated',
  14833. type: 'float',
  14834. inputs: [
  14835. { name: 'alpha', type: 'float' },
  14836. { name: 'dotNL', type: 'float' },
  14837. { name: 'dotNV', type: 'float' }
  14838. ]
  14839. } ); // validated
  14840. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  14841. const V_GGX_SmithCorrelated_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  14842. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  14843. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  14844. const v = div( 0.5, gv.add( gl ) );
  14845. return v.saturate();
  14846. } ).setLayout( {
  14847. name: 'V_GGX_SmithCorrelated_Anisotropic',
  14848. type: 'float',
  14849. inputs: [
  14850. { name: 'alphaT', type: 'float', qualifier: 'in' },
  14851. { name: 'alphaB', type: 'float', qualifier: 'in' },
  14852. { name: 'dotTV', type: 'float', qualifier: 'in' },
  14853. { name: 'dotBV', type: 'float', qualifier: 'in' },
  14854. { name: 'dotTL', type: 'float', qualifier: 'in' },
  14855. { name: 'dotBL', type: 'float', qualifier: 'in' },
  14856. { name: 'dotNV', type: 'float', qualifier: 'in' },
  14857. { name: 'dotNL', type: 'float', qualifier: 'in' }
  14858. ]
  14859. } );
  14860. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  14861. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  14862. // alpha is "roughness squared" in Disney’s reparameterization
  14863. const D_GGX = /*@__PURE__*/ Fn( ( { alpha, dotNH } ) => {
  14864. const a2 = alpha.pow2();
  14865. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  14866. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  14867. } ).setLayout( {
  14868. name: 'D_GGX',
  14869. type: 'float',
  14870. inputs: [
  14871. { name: 'alpha', type: 'float' },
  14872. { name: 'dotNH', type: 'float' }
  14873. ]
  14874. } ); // validated
  14875. const RECIPROCAL_PI = /*@__PURE__*/ float( 1 / Math.PI );
  14876. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  14877. const D_GGX_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  14878. const a2 = alphaT.mul( alphaB );
  14879. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  14880. const v2 = v.dot( v );
  14881. const w2 = a2.div( v2 );
  14882. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  14883. } ).setLayout( {
  14884. name: 'D_GGX_Anisotropic',
  14885. type: 'float',
  14886. inputs: [
  14887. { name: 'alphaT', type: 'float', qualifier: 'in' },
  14888. { name: 'alphaB', type: 'float', qualifier: 'in' },
  14889. { name: 'dotNH', type: 'float', qualifier: 'in' },
  14890. { name: 'dotTH', type: 'float', qualifier: 'in' },
  14891. { name: 'dotBH', type: 'float', qualifier: 'in' }
  14892. ]
  14893. } );
  14894. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  14895. const BRDF_GGX = /*@__PURE__*/ Fn( ( inputs ) => {
  14896. const { lightDirection, f0, f90, roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } = inputs;
  14897. const normalView = inputs.normalView || transformedNormalView;
  14898. const alpha = roughness.pow2(); // UE4's roughness
  14899. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  14900. const dotNL = normalView.dot( lightDirection ).clamp();
  14901. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  14902. const dotNH = normalView.dot( halfDir ).clamp();
  14903. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  14904. let F = F_Schlick( { f0, f90, dotVH } );
  14905. let V, D;
  14906. if ( defined( USE_IRIDESCENCE ) ) {
  14907. F = iridescence.mix( F, f );
  14908. }
  14909. if ( defined( USE_ANISOTROPY ) ) {
  14910. const dotTL = anisotropyT.dot( lightDirection );
  14911. const dotTV = anisotropyT.dot( positionViewDirection );
  14912. const dotTH = anisotropyT.dot( halfDir );
  14913. const dotBL = anisotropyB.dot( lightDirection );
  14914. const dotBV = anisotropyB.dot( positionViewDirection );
  14915. const dotBH = anisotropyB.dot( halfDir );
  14916. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  14917. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  14918. } else {
  14919. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  14920. D = D_GGX( { alpha, dotNH } );
  14921. }
  14922. return F.mul( V ).mul( D );
  14923. } ); // validated
  14924. // Analytical approximation of the DFG LUT, one half of the
  14925. // split-sum approximation used in indirect specular lighting.
  14926. // via 'environmentBRDF' from "Physically Based Shading on Mobile"
  14927. // https://www.unrealengine.com/blog/physically-based-shading-on-mobile
  14928. const DFGApprox = /*@__PURE__*/ Fn( ( { roughness, dotNV } ) => {
  14929. const c0 = vec4( -1, -0.0275, -0.572, 0.022 );
  14930. const c1 = vec4( 1, 0.0425, 1.04, -0.04 );
  14931. const r = roughness.mul( c0 ).add( c1 );
  14932. const a004 = r.x.mul( r.x ).min( dotNV.mul( -9.28 ).exp2() ).mul( r.x ).add( r.y );
  14933. const fab = vec2( -1.04, 1.04 ).mul( a004 ).add( r.zw );
  14934. return fab;
  14935. } ).setLayout( {
  14936. name: 'DFGApprox',
  14937. type: 'vec2',
  14938. inputs: [
  14939. { name: 'roughness', type: 'float' },
  14940. { name: 'dotNV', type: 'vec3' }
  14941. ]
  14942. } );
  14943. const EnvironmentBRDF = /*@__PURE__*/ Fn( ( inputs ) => {
  14944. const { dotNV, specularColor, specularF90, roughness } = inputs;
  14945. const fab = DFGApprox( { dotNV, roughness } );
  14946. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  14947. } );
  14948. const Schlick_to_F0 = /*@__PURE__*/ Fn( ( { f, f90, dotVH } ) => {
  14949. const x = dotVH.oneMinus().saturate();
  14950. const x2 = x.mul( x );
  14951. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  14952. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  14953. } ).setLayout( {
  14954. name: 'Schlick_to_F0',
  14955. type: 'vec3',
  14956. inputs: [
  14957. { name: 'f', type: 'vec3' },
  14958. { name: 'f90', type: 'float' },
  14959. { name: 'dotVH', type: 'float' }
  14960. ]
  14961. } );
  14962. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  14963. const D_Charlie = /*@__PURE__*/ Fn( ( { roughness, dotNH } ) => {
  14964. const alpha = roughness.pow2();
  14965. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  14966. const invAlpha = float( 1.0 ).div( alpha );
  14967. const cos2h = dotNH.pow2();
  14968. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  14969. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  14970. } ).setLayout( {
  14971. name: 'D_Charlie',
  14972. type: 'float',
  14973. inputs: [
  14974. { name: 'roughness', type: 'float' },
  14975. { name: 'dotNH', type: 'float' }
  14976. ]
  14977. } );
  14978. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  14979. const V_Neubelt = /*@__PURE__*/ Fn( ( { dotNV, dotNL } ) => {
  14980. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  14981. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  14982. } ).setLayout( {
  14983. name: 'V_Neubelt',
  14984. type: 'float',
  14985. inputs: [
  14986. { name: 'dotNV', type: 'float' },
  14987. { name: 'dotNL', type: 'float' }
  14988. ]
  14989. } );
  14990. const BRDF_Sheen = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  14991. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  14992. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  14993. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp();
  14994. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  14995. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  14996. const V = V_Neubelt( { dotNV, dotNL } );
  14997. return sheen.mul( D ).mul( V );
  14998. } );
  14999. // Rect Area Light
  15000. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  15001. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  15002. // code: https://github.com/selfshadow/ltc_code/
  15003. const LTC_Uv = /*@__PURE__*/ Fn( ( { N, V, roughness } ) => {
  15004. const LUT_SIZE = 64.0;
  15005. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  15006. const LUT_BIAS = 0.5 / LUT_SIZE;
  15007. const dotNV = N.dot( V ).saturate();
  15008. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  15009. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  15010. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  15011. return uv;
  15012. } ).setLayout( {
  15013. name: 'LTC_Uv',
  15014. type: 'vec2',
  15015. inputs: [
  15016. { name: 'N', type: 'vec3' },
  15017. { name: 'V', type: 'vec3' },
  15018. { name: 'roughness', type: 'float' }
  15019. ]
  15020. } );
  15021. const LTC_ClippedSphereFormFactor = /*@__PURE__*/ Fn( ( { f } ) => {
  15022. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  15023. // An approximation of the form factor of a horizon-clipped rectangle.
  15024. const l = f.length();
  15025. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  15026. } ).setLayout( {
  15027. name: 'LTC_ClippedSphereFormFactor',
  15028. type: 'float',
  15029. inputs: [
  15030. { name: 'f', type: 'vec3' }
  15031. ]
  15032. } );
  15033. const LTC_EdgeVectorFormFactor = /*@__PURE__*/ Fn( ( { v1, v2 } ) => {
  15034. const x = v1.dot( v2 );
  15035. const y = x.abs().toVar();
  15036. // rational polynomial approximation to theta / sin( theta ) / 2PI
  15037. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  15038. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  15039. const v = a.div( b );
  15040. const theta_sintheta = x.greaterThan( 0.0 ).select( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  15041. return v1.cross( v2 ).mul( theta_sintheta );
  15042. } ).setLayout( {
  15043. name: 'LTC_EdgeVectorFormFactor',
  15044. type: 'vec3',
  15045. inputs: [
  15046. { name: 'v1', type: 'vec3' },
  15047. { name: 'v2', type: 'vec3' }
  15048. ]
  15049. } );
  15050. const LTC_Evaluate = /*@__PURE__*/ Fn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  15051. // bail if point is on back side of plane of light
  15052. // assumes ccw winding order of light vertices
  15053. const v1 = p1.sub( p0 ).toVar();
  15054. const v2 = p3.sub( p0 ).toVar();
  15055. const lightNormal = v1.cross( v2 );
  15056. const result = vec3().toVar();
  15057. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  15058. // construct orthonormal basis around N
  15059. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  15060. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  15061. // compute transform
  15062. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  15063. // transform rect
  15064. // & project rect onto sphere
  15065. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  15066. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  15067. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  15068. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  15069. // calculate vector form factor
  15070. const vectorFormFactor = vec3( 0 ).toVar();
  15071. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  15072. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  15073. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  15074. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  15075. // adjust for horizon clipping
  15076. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  15077. } );
  15078. return result;
  15079. } ).setLayout( {
  15080. name: 'LTC_Evaluate',
  15081. type: 'vec3',
  15082. inputs: [
  15083. { name: 'N', type: 'vec3' },
  15084. { name: 'V', type: 'vec3' },
  15085. { name: 'P', type: 'vec3' },
  15086. { name: 'mInv', type: 'mat3' },
  15087. { name: 'p0', type: 'vec3' },
  15088. { name: 'p1', type: 'vec3' },
  15089. { name: 'p2', type: 'vec3' },
  15090. { name: 'p3', type: 'vec3' }
  15091. ]
  15092. } );
  15093. const LTC_Evaluate_Volume = /*@__PURE__*/ Fn( ( { P, p0, p1, p2, p3 } ) => {
  15094. // bail if point is on back side of plane of light
  15095. // assumes ccw winding order of light vertices
  15096. const v1 = p1.sub( p0 ).toVar();
  15097. const v2 = p3.sub( p0 ).toVar();
  15098. const lightNormal = v1.cross( v2 );
  15099. const result = vec3().toVar();
  15100. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  15101. // transform rect
  15102. // & project rect onto sphere
  15103. const coords0 = p0.sub( P ).normalize().toVar();
  15104. const coords1 = p1.sub( P ).normalize().toVar();
  15105. const coords2 = p2.sub( P ).normalize().toVar();
  15106. const coords3 = p3.sub( P ).normalize().toVar();
  15107. // calculate vector form factor
  15108. const vectorFormFactor = vec3( 0 ).toVar();
  15109. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  15110. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  15111. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  15112. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  15113. // adjust for horizon clipping
  15114. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor.abs() } ) ) );
  15115. } );
  15116. return result;
  15117. } ).setLayout( {
  15118. name: 'LTC_Evaluate',
  15119. type: 'vec3',
  15120. inputs: [
  15121. { name: 'P', type: 'vec3' },
  15122. { name: 'p0', type: 'vec3' },
  15123. { name: 'p1', type: 'vec3' },
  15124. { name: 'p2', type: 'vec3' },
  15125. { name: 'p3', type: 'vec3' }
  15126. ]
  15127. } );
  15128. // Mipped Bicubic Texture Filtering by N8
  15129. // https://www.shadertoy.com/view/Dl2SDW
  15130. const bC = 1.0 / 6.0;
  15131. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  15132. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  15133. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( -3, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  15134. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  15135. const g0 = ( a ) => w0( a ).add( w1( a ) );
  15136. const g1 = ( a ) => w2( a ).add( w3( a ) );
  15137. // h0 and h1 are the two offset functions
  15138. const h0 = ( a ) => add( -1, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  15139. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  15140. const bicubic = ( textureNode, texelSize, lod ) => {
  15141. const uv = textureNode.uvNode;
  15142. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  15143. const iuv = floor( uvScaled );
  15144. const fuv = fract( uvScaled );
  15145. const g0x = g0( fuv.x );
  15146. const g1x = g1( fuv.x );
  15147. const h0x = h0( fuv.x );
  15148. const h1x = h1( fuv.x );
  15149. const h0y = h0( fuv.y );
  15150. const h1y = h1( fuv.y );
  15151. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  15152. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  15153. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  15154. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  15155. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.sample( p0 ).level( lod ) ), g1x.mul( textureNode.sample( p1 ).level( lod ) ) ) );
  15156. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.sample( p2 ).level( lod ) ), g1x.mul( textureNode.sample( p3 ).level( lod ) ) ) );
  15157. return a.add( b );
  15158. };
  15159. /**
  15160. * Applies mipped bicubic texture filtering to the given texture node.
  15161. *
  15162. * @tsl
  15163. * @function
  15164. * @param {TextureNode} textureNode - The texture node that should be filtered.
  15165. * @param {Node<float>} [lodNode=float(3)] - Defines the LOD to sample from.
  15166. * @return {Node} The filtered texture sample.
  15167. */
  15168. const textureBicubic = /*@__PURE__*/ Fn( ( [ textureNode, lodNode = float( 3 ) ] ) => {
  15169. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  15170. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  15171. const fLodSizeInv = div( 1.0, fLodSize );
  15172. const cLodSizeInv = div( 1.0, cLodSize );
  15173. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  15174. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  15175. return fract( lodNode ).mix( fSample, cSample );
  15176. } );
  15177. //
  15178. // Transmission
  15179. //
  15180. const getVolumeTransmissionRay = /*@__PURE__*/ Fn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  15181. // Direction of refracted light.
  15182. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  15183. // Compute rotation-independent scaling of the model matrix.
  15184. const modelScale = vec3(
  15185. length( modelMatrix[ 0 ].xyz ),
  15186. length( modelMatrix[ 1 ].xyz ),
  15187. length( modelMatrix[ 2 ].xyz )
  15188. );
  15189. // The thickness is specified in local space.
  15190. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  15191. } ).setLayout( {
  15192. name: 'getVolumeTransmissionRay',
  15193. type: 'vec3',
  15194. inputs: [
  15195. { name: 'n', type: 'vec3' },
  15196. { name: 'v', type: 'vec3' },
  15197. { name: 'thickness', type: 'float' },
  15198. { name: 'ior', type: 'float' },
  15199. { name: 'modelMatrix', type: 'mat4' }
  15200. ]
  15201. } );
  15202. const applyIorToRoughness = /*@__PURE__*/ Fn( ( [ roughness, ior ] ) => {
  15203. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  15204. // an IOR of 1.5 results in the default amount of microfacet refraction.
  15205. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  15206. } ).setLayout( {
  15207. name: 'applyIorToRoughness',
  15208. type: 'float',
  15209. inputs: [
  15210. { name: 'roughness', type: 'float' },
  15211. { name: 'ior', type: 'float' }
  15212. ]
  15213. } );
  15214. const viewportBackSideTexture = /*@__PURE__*/ viewportMipTexture();
  15215. const viewportFrontSideTexture = /*@__PURE__*/ viewportMipTexture();
  15216. const getTransmissionSample = /*@__PURE__*/ Fn( ( [ fragCoord, roughness, ior ], { material } ) => {
  15217. const vTexture = material.side === BackSide ? viewportBackSideTexture : viewportFrontSideTexture;
  15218. const transmissionSample = vTexture.sample( fragCoord );
  15219. //const transmissionSample = viewportMipTexture( fragCoord );
  15220. const lod = log2( screenSize.x ).mul( applyIorToRoughness( roughness, ior ) );
  15221. return textureBicubic( transmissionSample, lod );
  15222. } );
  15223. const volumeAttenuation = /*@__PURE__*/ Fn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  15224. If( attenuationDistance.notEqual( 0 ), () => {
  15225. // Compute light attenuation using Beer's law.
  15226. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  15227. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  15228. return transmittance;
  15229. } );
  15230. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  15231. return vec3( 1.0 );
  15232. } ).setLayout( {
  15233. name: 'volumeAttenuation',
  15234. type: 'vec3',
  15235. inputs: [
  15236. { name: 'transmissionDistance', type: 'float' },
  15237. { name: 'attenuationColor', type: 'vec3' },
  15238. { name: 'attenuationDistance', type: 'float' }
  15239. ]
  15240. } );
  15241. const getIBLVolumeRefraction = /*@__PURE__*/ Fn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  15242. let transmittedLight, transmittance;
  15243. if ( dispersion ) {
  15244. transmittedLight = vec4().toVar();
  15245. transmittance = vec3().toVar();
  15246. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  15247. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  15248. Loop( { start: 0, end: 3 }, ( { i } ) => {
  15249. const ior = iors.element( i );
  15250. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  15251. const refractedRayExit = position.add( transmissionRay );
  15252. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  15253. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  15254. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  15255. refractionCoords.addAssign( 1.0 );
  15256. refractionCoords.divAssign( 2.0 );
  15257. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  15258. // Sample framebuffer to get pixel the refracted ray hits.
  15259. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  15260. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  15261. transmittedLight.a.addAssign( transmissionSample.a );
  15262. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  15263. } );
  15264. transmittedLight.a.divAssign( 3.0 );
  15265. } else {
  15266. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  15267. const refractedRayExit = position.add( transmissionRay );
  15268. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  15269. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  15270. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  15271. refractionCoords.addAssign( 1.0 );
  15272. refractionCoords.divAssign( 2.0 );
  15273. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  15274. // Sample framebuffer to get pixel the refracted ray hits.
  15275. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  15276. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  15277. }
  15278. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  15279. const dotNV = n.dot( v ).clamp();
  15280. // Get the specular component.
  15281. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  15282. dotNV,
  15283. specularColor,
  15284. specularF90,
  15285. roughness
  15286. } ) );
  15287. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  15288. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  15289. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  15290. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  15291. } );
  15292. //
  15293. // Iridescence
  15294. //
  15295. // XYZ to linear-sRGB color space
  15296. const XYZ_TO_REC709 = /*@__PURE__*/ mat3(
  15297. 3.2404542, -0.969266, 0.0556434,
  15298. -1.5371385, 1.8760108, -0.2040259,
  15299. -0.4985314, 0.0415560, 1.0572252
  15300. );
  15301. // Assume air interface for top
  15302. // Note: We don't handle the case fresnel0 == 1
  15303. const Fresnel0ToIor = ( fresnel0 ) => {
  15304. const sqrtF0 = fresnel0.sqrt();
  15305. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  15306. };
  15307. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  15308. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  15309. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  15310. };
  15311. // Fresnel equations for dielectric/dielectric interfaces.
  15312. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  15313. // Evaluation XYZ sensitivity curves in Fourier space
  15314. const evalSensitivity = ( OPD, shift ) => {
  15315. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  15316. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  15317. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  15318. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  15319. 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() );
  15320. 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() );
  15321. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  15322. const rgb = XYZ_TO_REC709.mul( xyz );
  15323. return rgb;
  15324. };
  15325. const evalIridescence = /*@__PURE__*/ Fn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  15326. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  15327. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  15328. // Evaluate the cosTheta on the base layer (Snell law)
  15329. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( cosTheta1.pow2().oneMinus() );
  15330. // Handle TIR:
  15331. const cosTheta2Sq = sinTheta2Sq.oneMinus();
  15332. If( cosTheta2Sq.lessThan( 0 ), () => {
  15333. return vec3( 1.0 );
  15334. } );
  15335. const cosTheta2 = cosTheta2Sq.sqrt();
  15336. // First interface
  15337. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  15338. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  15339. //const R21 = R12;
  15340. const T121 = R12.oneMinus();
  15341. const phi12 = iridescenceIOR.lessThan( outsideIOR ).select( Math.PI, 0.0 );
  15342. const phi21 = float( Math.PI ).sub( phi12 );
  15343. // Second interface
  15344. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  15345. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  15346. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  15347. const phi23 = vec3(
  15348. baseIOR.x.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  15349. baseIOR.y.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  15350. baseIOR.z.lessThan( iridescenceIOR ).select( Math.PI, 0.0 )
  15351. );
  15352. // Phase shift
  15353. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  15354. const phi = vec3( phi21 ).add( phi23 );
  15355. // Compound terms
  15356. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  15357. const r123 = R123.sqrt();
  15358. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  15359. // Reflectance term for m = 0 (DC term amplitude)
  15360. const C0 = R12.add( Rs );
  15361. const I = C0.toVar();
  15362. // Reflectance term for m > 0 (pairs of diracs)
  15363. const Cm = Rs.sub( T121 ).toVar();
  15364. Loop( { start: 1, end: 2, condition: '<=', name: 'm' }, ( { m } ) => {
  15365. Cm.mulAssign( r123 );
  15366. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  15367. I.addAssign( Cm.mul( Sm ) );
  15368. } );
  15369. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  15370. return I.max( vec3( 0.0 ) );
  15371. } ).setLayout( {
  15372. name: 'evalIridescence',
  15373. type: 'vec3',
  15374. inputs: [
  15375. { name: 'outsideIOR', type: 'float' },
  15376. { name: 'eta2', type: 'float' },
  15377. { name: 'cosTheta1', type: 'float' },
  15378. { name: 'thinFilmThickness', type: 'float' },
  15379. { name: 'baseF0', type: 'vec3' }
  15380. ]
  15381. } );
  15382. //
  15383. // Sheen
  15384. //
  15385. // This is a curve-fit approximation to the "Charlie sheen" BRDF integrated over the hemisphere from
  15386. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF". The analysis can be found
  15387. // in the Sheen section of https://drive.google.com/file/d/1T0D1VSyR4AllqIJTQAraEIzjlb5h4FKH/view?usp=sharing
  15388. const IBLSheenBRDF = /*@__PURE__*/ Fn( ( { normal, viewDir, roughness } ) => {
  15389. const dotNV = normal.dot( viewDir ).saturate();
  15390. const r2 = roughness.pow2();
  15391. const a = select(
  15392. roughness.lessThan( 0.25 ),
  15393. float( -339.2 ).mul( r2 ).add( float( 161.4 ).mul( roughness ) ).sub( 25.9 ),
  15394. float( -8.48 ).mul( r2 ).add( float( 14.3 ).mul( roughness ) ).sub( 9.95 )
  15395. );
  15396. const b = select(
  15397. roughness.lessThan( 0.25 ),
  15398. float( 44.0 ).mul( r2 ).sub( float( 23.7 ).mul( roughness ) ).add( 3.26 ),
  15399. float( 1.97 ).mul( r2 ).sub( float( 3.27 ).mul( roughness ) ).add( 0.72 )
  15400. );
  15401. const DG = select( roughness.lessThan( 0.25 ), 0.0, float( 0.1 ).mul( roughness ).sub( 0.025 ) ).add( a.mul( dotNV ).add( b ).exp() );
  15402. return DG.mul( 1.0 / Math.PI ).saturate();
  15403. } );
  15404. const clearcoatF0 = vec3( 0.04 );
  15405. const clearcoatF90 = float( 1 );
  15406. /**
  15407. * Represents the lighting model for a PBR material.
  15408. *
  15409. * @augments LightingModel
  15410. */
  15411. class PhysicalLightingModel extends LightingModel {
  15412. /**
  15413. * Constructs a new physical lighting model.
  15414. *
  15415. * @param {boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  15416. * @param {boolean} [sheen=false] - Whether sheen is supported or not.
  15417. * @param {boolean} [iridescence=false] - Whether iridescence is supported or not.
  15418. * @param {boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  15419. * @param {boolean} [transmission=false] - Whether transmission is supported or not.
  15420. * @param {boolean} [dispersion=false] - Whether dispersion is supported or not.
  15421. */
  15422. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  15423. super();
  15424. /**
  15425. * Whether clearcoat is supported or not.
  15426. *
  15427. * @type {boolean}
  15428. * @default false
  15429. */
  15430. this.clearcoat = clearcoat;
  15431. /**
  15432. * Whether sheen is supported or not.
  15433. *
  15434. * @type {boolean}
  15435. * @default false
  15436. */
  15437. this.sheen = sheen;
  15438. /**
  15439. * Whether iridescence is supported or not.
  15440. *
  15441. * @type {boolean}
  15442. * @default false
  15443. */
  15444. this.iridescence = iridescence;
  15445. /**
  15446. * Whether anisotropy is supported or not.
  15447. *
  15448. * @type {boolean}
  15449. * @default false
  15450. */
  15451. this.anisotropy = anisotropy;
  15452. /**
  15453. * Whether transmission is supported or not.
  15454. *
  15455. * @type {boolean}
  15456. * @default false
  15457. */
  15458. this.transmission = transmission;
  15459. /**
  15460. * Whether dispersion is supported or not.
  15461. *
  15462. * @type {boolean}
  15463. * @default false
  15464. */
  15465. this.dispersion = dispersion;
  15466. /**
  15467. * The clear coat radiance.
  15468. *
  15469. * @type {?Node}
  15470. * @default null
  15471. */
  15472. this.clearcoatRadiance = null;
  15473. /**
  15474. * The clear coat specular direct.
  15475. *
  15476. * @type {?Node}
  15477. * @default null
  15478. */
  15479. this.clearcoatSpecularDirect = null;
  15480. /**
  15481. * The clear coat specular indirect.
  15482. *
  15483. * @type {?Node}
  15484. * @default null
  15485. */
  15486. this.clearcoatSpecularIndirect = null;
  15487. /**
  15488. * The sheen specular direct.
  15489. *
  15490. * @type {?Node}
  15491. * @default null
  15492. */
  15493. this.sheenSpecularDirect = null;
  15494. /**
  15495. * The sheen specular indirect.
  15496. *
  15497. * @type {?Node}
  15498. * @default null
  15499. */
  15500. this.sheenSpecularIndirect = null;
  15501. /**
  15502. * The iridescence Fresnel.
  15503. *
  15504. * @type {?Node}
  15505. * @default null
  15506. */
  15507. this.iridescenceFresnel = null;
  15508. /**
  15509. * The iridescence F0.
  15510. *
  15511. * @type {?Node}
  15512. * @default null
  15513. */
  15514. this.iridescenceF0 = null;
  15515. }
  15516. /**
  15517. * Depending on what features are requested, the method prepares certain node variables
  15518. * which are later used for lighting computations.
  15519. *
  15520. * @param {NodeBuilder} builder - The current node builder.
  15521. */
  15522. start( builder ) {
  15523. if ( this.clearcoat === true ) {
  15524. this.clearcoatRadiance = vec3().toVar( 'clearcoatRadiance' );
  15525. this.clearcoatSpecularDirect = vec3().toVar( 'clearcoatSpecularDirect' );
  15526. this.clearcoatSpecularIndirect = vec3().toVar( 'clearcoatSpecularIndirect' );
  15527. }
  15528. if ( this.sheen === true ) {
  15529. this.sheenSpecularDirect = vec3().toVar( 'sheenSpecularDirect' );
  15530. this.sheenSpecularIndirect = vec3().toVar( 'sheenSpecularIndirect' );
  15531. }
  15532. if ( this.iridescence === true ) {
  15533. const dotNVi = transformedNormalView.dot( positionViewDirection ).clamp();
  15534. this.iridescenceFresnel = evalIridescence( {
  15535. outsideIOR: float( 1.0 ),
  15536. eta2: iridescenceIOR,
  15537. cosTheta1: dotNVi,
  15538. thinFilmThickness: iridescenceThickness,
  15539. baseF0: specularColor
  15540. } );
  15541. this.iridescenceF0 = Schlick_to_F0( { f: this.iridescenceFresnel, f90: 1.0, dotVH: dotNVi } );
  15542. }
  15543. if ( this.transmission === true ) {
  15544. const position = positionWorld;
  15545. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  15546. const n = transformedNormalWorld;
  15547. const context = builder.context;
  15548. context.backdrop = getIBLVolumeRefraction(
  15549. n,
  15550. v,
  15551. roughness,
  15552. diffuseColor,
  15553. specularColor,
  15554. specularF90, // specularF90
  15555. position, // positionWorld
  15556. modelWorldMatrix, // modelMatrix
  15557. cameraViewMatrix, // viewMatrix
  15558. cameraProjectionMatrix, // projMatrix
  15559. ior,
  15560. thickness,
  15561. attenuationColor,
  15562. attenuationDistance,
  15563. this.dispersion ? dispersion : null
  15564. );
  15565. context.backdropAlpha = transmission;
  15566. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  15567. }
  15568. super.start( builder );
  15569. }
  15570. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  15571. // Approximates multi-scattering in order to preserve energy.
  15572. // http://www.jcgt.org/published/0008/01/03/
  15573. computeMultiscattering( singleScatter, multiScatter, specularF90 ) {
  15574. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  15575. const fab = DFGApprox( { roughness, dotNV } );
  15576. const Fr = this.iridescenceF0 ? iridescence.mix( specularColor, this.iridescenceF0 ) : specularColor;
  15577. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  15578. const Ess = fab.x.add( fab.y );
  15579. const Ems = Ess.oneMinus();
  15580. const Favg = specularColor.add( specularColor.oneMinus().mul( 0.047619 ) ); // 1/21
  15581. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  15582. singleScatter.addAssign( FssEss );
  15583. multiScatter.addAssign( Fms.mul( Ems ) );
  15584. }
  15585. /**
  15586. * Implements the direct light.
  15587. *
  15588. * @param {Object} lightData - The light data.
  15589. * @param {NodeBuilder} builder - The current node builder.
  15590. */
  15591. direct( { lightDirection, lightColor, reflectedLight } ) {
  15592. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  15593. const irradiance = dotNL.mul( lightColor );
  15594. if ( this.sheen === true ) {
  15595. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  15596. }
  15597. if ( this.clearcoat === true ) {
  15598. const dotNLcc = transformedClearcoatNormalView.dot( lightDirection ).clamp();
  15599. const ccIrradiance = dotNLcc.mul( lightColor );
  15600. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: transformedClearcoatNormalView } ) ) );
  15601. }
  15602. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  15603. 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 } ) ) );
  15604. }
  15605. /**
  15606. * This method is intended for implementing the direct light term for
  15607. * rect area light nodes.
  15608. *
  15609. * @param {Object} input - The input data.
  15610. * @param {NodeBuilder} builder - The current node builder.
  15611. */
  15612. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 } ) {
  15613. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  15614. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  15615. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  15616. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  15617. const N = transformedNormalView;
  15618. const V = positionViewDirection;
  15619. const P = positionView.toVar();
  15620. const uv = LTC_Uv( { N, V, roughness } );
  15621. const t1 = ltc_1.sample( uv ).toVar();
  15622. const t2 = ltc_2.sample( uv ).toVar();
  15623. const mInv = mat3(
  15624. vec3( t1.x, 0, t1.y ),
  15625. vec3( 0, 1, 0 ),
  15626. vec3( t1.z, 0, t1.w )
  15627. ).toVar();
  15628. // LTC Fresnel Approximation by Stephen Hill
  15629. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  15630. const fresnel = specularColor.mul( t2.x ).add( specularColor.oneMinus().mul( t2.y ) ).toVar();
  15631. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  15632. 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 } ) ) );
  15633. }
  15634. /**
  15635. * Implements the indirect lighting.
  15636. *
  15637. * @param {NodeBuilder} builder - The current node builder.
  15638. */
  15639. indirect( builder ) {
  15640. this.indirectDiffuse( builder );
  15641. this.indirectSpecular( builder );
  15642. this.ambientOcclusion( builder );
  15643. }
  15644. /**
  15645. * Implements the indirect diffuse term.
  15646. *
  15647. * @param {NodeBuilder} builder - The current node builder.
  15648. */
  15649. indirectDiffuse( builder ) {
  15650. const { irradiance, reflectedLight } = builder.context;
  15651. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  15652. }
  15653. /**
  15654. * Implements the indirect specular term.
  15655. *
  15656. * @param {NodeBuilder} builder - The current node builder.
  15657. */
  15658. indirectSpecular( builder ) {
  15659. const { radiance, iblIrradiance, reflectedLight } = builder.context;
  15660. if ( this.sheen === true ) {
  15661. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  15662. sheen,
  15663. IBLSheenBRDF( {
  15664. normal: transformedNormalView,
  15665. viewDir: positionViewDirection,
  15666. roughness: sheenRoughness
  15667. } )
  15668. ) );
  15669. }
  15670. if ( this.clearcoat === true ) {
  15671. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  15672. const clearcoatEnv = EnvironmentBRDF( {
  15673. dotNV: dotNVcc,
  15674. specularColor: clearcoatF0,
  15675. specularF90: clearcoatF90,
  15676. roughness: clearcoatRoughness
  15677. } );
  15678. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  15679. }
  15680. // Both indirect specular and indirect diffuse light accumulate here
  15681. const singleScattering = vec3().toVar( 'singleScattering' );
  15682. const multiScattering = vec3().toVar( 'multiScattering' );
  15683. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  15684. this.computeMultiscattering( singleScattering, multiScattering, specularF90 );
  15685. const totalScattering = singleScattering.add( multiScattering );
  15686. const diffuse = diffuseColor.mul( totalScattering.r.max( totalScattering.g ).max( totalScattering.b ).oneMinus() );
  15687. reflectedLight.indirectSpecular.addAssign( radiance.mul( singleScattering ) );
  15688. reflectedLight.indirectSpecular.addAssign( multiScattering.mul( cosineWeightedIrradiance ) );
  15689. reflectedLight.indirectDiffuse.addAssign( diffuse.mul( cosineWeightedIrradiance ) );
  15690. }
  15691. /**
  15692. * Implements the ambient occlusion term.
  15693. *
  15694. * @param {NodeBuilder} builder - The current node builder.
  15695. */
  15696. ambientOcclusion( builder ) {
  15697. const { ambientOcclusion, reflectedLight } = builder.context;
  15698. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  15699. const aoNV = dotNV.add( ambientOcclusion );
  15700. const aoExp = roughness.mul( -16 ).oneMinus().negate().exp2();
  15701. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  15702. if ( this.clearcoat === true ) {
  15703. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  15704. }
  15705. if ( this.sheen === true ) {
  15706. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  15707. }
  15708. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  15709. reflectedLight.indirectSpecular.mulAssign( aoNode );
  15710. }
  15711. /**
  15712. * Used for final lighting accumulations depending on the requested features.
  15713. *
  15714. * @param {NodeBuilder} builder - The current node builder.
  15715. */
  15716. finish( { context } ) {
  15717. const { outgoingLight } = context;
  15718. if ( this.clearcoat === true ) {
  15719. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  15720. const Fcc = F_Schlick( {
  15721. dotVH: dotNVcc,
  15722. f0: clearcoatF0,
  15723. f90: clearcoatF90
  15724. } );
  15725. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  15726. outgoingLight.assign( clearcoatLight );
  15727. }
  15728. if ( this.sheen === true ) {
  15729. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( 0.157 ).oneMinus();
  15730. const sheenLight = outgoingLight.mul( sheenEnergyComp ).add( this.sheenSpecularDirect, this.sheenSpecularIndirect );
  15731. outgoingLight.assign( sheenLight );
  15732. }
  15733. }
  15734. }
  15735. // These defines must match with PMREMGenerator
  15736. const cubeUV_r0 = /*@__PURE__*/ float( 1.0 );
  15737. const cubeUV_m0 = /*@__PURE__*/ float( -2 );
  15738. const cubeUV_r1 = /*@__PURE__*/ float( 0.8 );
  15739. const cubeUV_m1 = /*@__PURE__*/ float( -1 );
  15740. const cubeUV_r4 = /*@__PURE__*/ float( 0.4 );
  15741. const cubeUV_m4 = /*@__PURE__*/ float( 2.0 );
  15742. const cubeUV_r5 = /*@__PURE__*/ float( 0.305 );
  15743. const cubeUV_m5 = /*@__PURE__*/ float( 3.0 );
  15744. const cubeUV_r6 = /*@__PURE__*/ float( 0.21 );
  15745. const cubeUV_m6 = /*@__PURE__*/ float( 4.0 );
  15746. const cubeUV_minMipLevel = /*@__PURE__*/ float( 4.0 );
  15747. const cubeUV_minTileSize = /*@__PURE__*/ float( 16.0 );
  15748. // These shader functions convert between the UV coordinates of a single face of
  15749. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  15750. // sampling a textureCube (not generally normalized ).
  15751. const getFace = /*@__PURE__*/ Fn( ( [ direction ] ) => {
  15752. const absDirection = vec3( abs( direction ) ).toVar();
  15753. const face = float( -1 ).toVar();
  15754. If( absDirection.x.greaterThan( absDirection.z ), () => {
  15755. If( absDirection.x.greaterThan( absDirection.y ), () => {
  15756. face.assign( select( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  15757. } ).Else( () => {
  15758. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  15759. } );
  15760. } ).Else( () => {
  15761. If( absDirection.z.greaterThan( absDirection.y ), () => {
  15762. face.assign( select( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  15763. } ).Else( () => {
  15764. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  15765. } );
  15766. } );
  15767. return face;
  15768. } ).setLayout( {
  15769. name: 'getFace',
  15770. type: 'float',
  15771. inputs: [
  15772. { name: 'direction', type: 'vec3' }
  15773. ]
  15774. } );
  15775. // RH coordinate system; PMREM face-indexing convention
  15776. const getUV = /*@__PURE__*/ Fn( ( [ direction, face ] ) => {
  15777. const uv = vec2().toVar();
  15778. If( face.equal( 0.0 ), () => {
  15779. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  15780. } ).ElseIf( face.equal( 1.0 ), () => {
  15781. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  15782. } ).ElseIf( face.equal( 2.0 ), () => {
  15783. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  15784. } ).ElseIf( face.equal( 3.0 ), () => {
  15785. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  15786. } ).ElseIf( face.equal( 4.0 ), () => {
  15787. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  15788. } ).Else( () => {
  15789. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  15790. } );
  15791. return mul( 0.5, uv.add( 1.0 ) );
  15792. } ).setLayout( {
  15793. name: 'getUV',
  15794. type: 'vec2',
  15795. inputs: [
  15796. { name: 'direction', type: 'vec3' },
  15797. { name: 'face', type: 'float' }
  15798. ]
  15799. } );
  15800. const roughnessToMip = /*@__PURE__*/ Fn( ( [ roughness ] ) => {
  15801. const mip = float( 0.0 ).toVar();
  15802. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  15803. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  15804. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  15805. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  15806. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  15807. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  15808. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  15809. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  15810. } ).Else( () => {
  15811. mip.assign( float( -2 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  15812. } );
  15813. return mip;
  15814. } ).setLayout( {
  15815. name: 'roughnessToMip',
  15816. type: 'float',
  15817. inputs: [
  15818. { name: 'roughness', type: 'float' }
  15819. ]
  15820. } );
  15821. // RH coordinate system; PMREM face-indexing convention
  15822. const getDirection = /*@__PURE__*/ Fn( ( [ uv_immutable, face ] ) => {
  15823. const uv = uv_immutable.toVar();
  15824. uv.assign( mul( 2.0, uv ).sub( 1.0 ) );
  15825. const direction = vec3( uv, 1.0 ).toVar();
  15826. If( face.equal( 0.0 ), () => {
  15827. direction.assign( direction.zyx ); // ( 1, v, u ) pos x
  15828. } ).ElseIf( face.equal( 1.0 ), () => {
  15829. direction.assign( direction.xzy );
  15830. direction.xz.mulAssign( -1 ); // ( -u, 1, -v ) pos y
  15831. } ).ElseIf( face.equal( 2.0 ), () => {
  15832. direction.x.mulAssign( -1 ); // ( -u, v, 1 ) pos z
  15833. } ).ElseIf( face.equal( 3.0 ), () => {
  15834. direction.assign( direction.zyx );
  15835. direction.xz.mulAssign( -1 ); // ( -1, v, -u ) neg x
  15836. } ).ElseIf( face.equal( 4.0 ), () => {
  15837. direction.assign( direction.xzy );
  15838. direction.xy.mulAssign( -1 ); // ( -u, -1, v ) neg y
  15839. } ).ElseIf( face.equal( 5.0 ), () => {
  15840. direction.z.mulAssign( -1 ); // ( u, v, -1 ) neg zS
  15841. } );
  15842. return direction;
  15843. } ).setLayout( {
  15844. name: 'getDirection',
  15845. type: 'vec3',
  15846. inputs: [
  15847. { name: 'uv', type: 'vec2' },
  15848. { name: 'face', type: 'float' }
  15849. ]
  15850. } );
  15851. //
  15852. const textureCubeUV = /*@__PURE__*/ Fn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  15853. const roughness = float( roughness_immutable );
  15854. const sampleDir = vec3( sampleDir_immutable );
  15855. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  15856. const mipF = fract( mip );
  15857. const mipInt = floor( mip );
  15858. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  15859. If( mipF.notEqual( 0.0 ), () => {
  15860. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  15861. color0.assign( mix( color0, color1, mipF ) );
  15862. } );
  15863. return color0;
  15864. } );
  15865. const bilinearCubeUV = /*@__PURE__*/ Fn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  15866. const mipInt = float( mipInt_immutable ).toVar();
  15867. const direction = vec3( direction_immutable );
  15868. const face = float( getFace( direction ) ).toVar();
  15869. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  15870. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  15871. const faceSize = float( exp2( mipInt ) ).toVar();
  15872. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  15873. If( face.greaterThan( 2.0 ), () => {
  15874. uv.y.addAssign( faceSize );
  15875. face.subAssign( 3.0 );
  15876. } );
  15877. uv.x.addAssign( face.mul( faceSize ) );
  15878. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  15879. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  15880. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  15881. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  15882. return envMap.sample( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  15883. } );
  15884. const getSample = /*@__PURE__*/ Fn( ( { envMap, mipInt, outputDirection, theta, axis, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  15885. const cosTheta = cos( theta );
  15886. // Rodrigues' axis-angle rotation
  15887. const sampleDirection = outputDirection.mul( cosTheta )
  15888. .add( axis.cross( outputDirection ).mul( sin( theta ) ) )
  15889. .add( axis.mul( axis.dot( outputDirection ).mul( cosTheta.oneMinus() ) ) );
  15890. return bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  15891. } );
  15892. const blur = /*@__PURE__*/ Fn( ( { n, latitudinal, poleAxis, outputDirection, weights, samples, dTheta, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  15893. const axis = vec3( select( latitudinal, poleAxis, cross( poleAxis, outputDirection ) ) ).toVar();
  15894. If( axis.equal( vec3( 0.0 ) ), () => {
  15895. axis.assign( vec3( outputDirection.z, 0.0, outputDirection.x.negate() ) );
  15896. } );
  15897. axis.assign( normalize( axis ) );
  15898. const gl_FragColor = vec3().toVar();
  15899. gl_FragColor.addAssign( weights.element( 0 ).mul( getSample( { theta: 0.0, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  15900. Loop( { start: int( 1 ), end: n }, ( { i } ) => {
  15901. If( i.greaterThanEqual( samples ), () => {
  15902. Break();
  15903. } );
  15904. const theta = float( dTheta.mul( float( i ) ) ).toVar();
  15905. 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 } ) ) );
  15906. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  15907. } );
  15908. return vec4( gl_FragColor, 1 );
  15909. } );
  15910. const LOD_MIN = 4;
  15911. // The standard deviations (radians) associated with the extra mips. These are
  15912. // chosen to approximate a Trowbridge-Reitz distribution function times the
  15913. // geometric shadowing function. These sigma values squared must match the
  15914. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  15915. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  15916. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  15917. // samples and exit early, but not recompile the shader.
  15918. const MAX_SAMPLES = 20;
  15919. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  15920. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  15921. const _clearColor$2 = /*@__PURE__*/ new Color();
  15922. let _oldTarget = null;
  15923. let _oldActiveCubeFace = 0;
  15924. let _oldActiveMipmapLevel = 0;
  15925. // Golden Ratio
  15926. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  15927. const INV_PHI = 1 / PHI;
  15928. // Vertices of a dodecahedron (except the opposites, which represent the
  15929. // same axis), used as axis directions evenly spread on a sphere.
  15930. const _axisDirections = [
  15931. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  15932. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  15933. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  15934. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  15935. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  15936. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  15937. /*@__PURE__*/ new Vector3( -1, 1, -1 ),
  15938. /*@__PURE__*/ new Vector3( 1, 1, -1 ),
  15939. /*@__PURE__*/ new Vector3( -1, 1, 1 ),
  15940. /*@__PURE__*/ new Vector3( 1, 1, 1 )
  15941. ];
  15942. const _origin = /*@__PURE__*/ new Vector3();
  15943. // maps blur materials to their uniforms dictionary
  15944. const _uniformsMap = new WeakMap();
  15945. // WebGPU Face indices
  15946. const _faceLib = [
  15947. 3, 1, 5,
  15948. 0, 4, 2
  15949. ];
  15950. const _direction = /*@__PURE__*/ getDirection( uv(), attribute( 'faceIndex' ) ).normalize();
  15951. const _outputDirection = /*@__PURE__*/ vec3( _direction.x, _direction.y, _direction.z );
  15952. /**
  15953. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  15954. * (PMREM) from a cubeMap environment texture. This allows different levels of
  15955. * blur to be quickly accessed based on material roughness. It is packed into a
  15956. * special CubeUV format that allows us to perform custom interpolation so that
  15957. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  15958. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  15959. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  15960. * higher roughness levels. In this way we maintain resolution to smoothly
  15961. * interpolate diffuse lighting while limiting sampling computation.
  15962. *
  15963. * Paper: Fast, Accurate Image-Based Lighting:
  15964. * {@link https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view}
  15965. */
  15966. class PMREMGenerator {
  15967. /**
  15968. * Constructs a new PMREM generator.
  15969. *
  15970. * @param {Renderer} renderer - The renderer.
  15971. */
  15972. constructor( renderer ) {
  15973. this._renderer = renderer;
  15974. this._pingPongRenderTarget = null;
  15975. this._lodMax = 0;
  15976. this._cubeSize = 0;
  15977. this._lodPlanes = [];
  15978. this._sizeLods = [];
  15979. this._sigmas = [];
  15980. this._lodMeshes = [];
  15981. this._blurMaterial = null;
  15982. this._cubemapMaterial = null;
  15983. this._equirectMaterial = null;
  15984. this._backgroundBox = null;
  15985. }
  15986. get _hasInitialized() {
  15987. return this._renderer.hasInitialized();
  15988. }
  15989. /**
  15990. * Generates a PMREM from a supplied Scene, which can be faster than using an
  15991. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  15992. * in radians to be applied to the scene before PMREM generation. Optional near
  15993. * and far planes ensure the scene is rendered in its entirety.
  15994. *
  15995. * @param {Scene} scene - The scene to be captured.
  15996. * @param {number} [sigma=0] - The blur radius in radians.
  15997. * @param {number} [near=0.1] - The near plane distance.
  15998. * @param {number} [far=100] - The far plane distance.
  15999. * @param {Object} [options={}] - The configuration options.
  16000. * @param {number} [options.size=256] - The texture size of the PMREM.
  16001. * @param {Vector3} [options.renderTarget=origin] - The position of the internal cube camera that renders the scene.
  16002. * @param {?RenderTarget} [options.renderTarget=null] - The render target to use.
  16003. * @return {RenderTarget} The resulting PMREM.
  16004. * @see {@link PMREMGenerator#fromSceneAsync}
  16005. */
  16006. fromScene( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  16007. const {
  16008. size = 256,
  16009. position = _origin,
  16010. renderTarget = null,
  16011. } = options;
  16012. this._setSize( size );
  16013. if ( this._hasInitialized === false ) {
  16014. console.warn( 'THREE.PMREMGenerator: .fromScene() called before the backend is initialized. Try using .fromSceneAsync() instead.' );
  16015. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  16016. options.renderTarget = cubeUVRenderTarget;
  16017. this.fromSceneAsync( scene, sigma, near, far, options );
  16018. return cubeUVRenderTarget;
  16019. }
  16020. _oldTarget = this._renderer.getRenderTarget();
  16021. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  16022. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  16023. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  16024. cubeUVRenderTarget.depthBuffer = true;
  16025. this._init( cubeUVRenderTarget );
  16026. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position );
  16027. if ( sigma > 0 ) {
  16028. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  16029. }
  16030. this._applyPMREM( cubeUVRenderTarget );
  16031. this._cleanup( cubeUVRenderTarget );
  16032. return cubeUVRenderTarget;
  16033. }
  16034. /**
  16035. * Generates a PMREM from a supplied Scene, which can be faster than using an
  16036. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  16037. * in radians to be applied to the scene before PMREM generation. Optional near
  16038. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  16039. * is placed at the origin).
  16040. *
  16041. * @param {Scene} scene - The scene to be captured.
  16042. * @param {number} [sigma=0] - The blur radius in radians.
  16043. * @param {number} [near=0.1] - The near plane distance.
  16044. * @param {number} [far=100] - The far plane distance.
  16045. * @param {Object} [options={}] - The configuration options.
  16046. * @param {number} [options.size=256] - The texture size of the PMREM.
  16047. * @param {Vector3} [options.position=origin] - The position of the internal cube camera that renders the scene.
  16048. * @param {?RenderTarget} [options.renderTarget=null] - The render target to use.
  16049. * @return {Promise<RenderTarget>} A Promise that resolve with the PMREM when the generation has been finished.
  16050. * @see {@link PMREMGenerator#fromScene}
  16051. */
  16052. async fromSceneAsync( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  16053. if ( this._hasInitialized === false ) await this._renderer.init();
  16054. return this.fromScene( scene, sigma, near, far, options );
  16055. }
  16056. /**
  16057. * Generates a PMREM from an equirectangular texture, which can be either LDR
  16058. * or HDR. The ideal input image size is 1k (1024 x 512),
  16059. * as this matches best with the 256 x 256 cubemap output.
  16060. *
  16061. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  16062. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  16063. * @return {RenderTarget} The resulting PMREM.
  16064. * @see {@link PMREMGenerator#fromEquirectangularAsync}
  16065. */
  16066. fromEquirectangular( equirectangular, renderTarget = null ) {
  16067. if ( this._hasInitialized === false ) {
  16068. console.warn( 'THREE.PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using .fromEquirectangularAsync() instead.' );
  16069. this._setSizeFromTexture( equirectangular );
  16070. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  16071. this.fromEquirectangularAsync( equirectangular, cubeUVRenderTarget );
  16072. return cubeUVRenderTarget;
  16073. }
  16074. return this._fromTexture( equirectangular, renderTarget );
  16075. }
  16076. /**
  16077. * Generates a PMREM from an equirectangular texture, which can be either LDR
  16078. * or HDR. The ideal input image size is 1k (1024 x 512),
  16079. * as this matches best with the 256 x 256 cubemap output.
  16080. *
  16081. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  16082. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  16083. * @return {Promise<RenderTarget>} The resulting PMREM.
  16084. * @see {@link PMREMGenerator#fromEquirectangular}
  16085. */
  16086. async fromEquirectangularAsync( equirectangular, renderTarget = null ) {
  16087. if ( this._hasInitialized === false ) await this._renderer.init();
  16088. return this._fromTexture( equirectangular, renderTarget );
  16089. }
  16090. /**
  16091. * Generates a PMREM from an cubemap texture, which can be either LDR
  16092. * or HDR. The ideal input cube size is 256 x 256,
  16093. * as this matches best with the 256 x 256 cubemap output.
  16094. *
  16095. * @param {Texture} cubemap - The cubemap texture to be converted.
  16096. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  16097. * @return {RenderTarget} The resulting PMREM.
  16098. * @see {@link PMREMGenerator#fromCubemapAsync}
  16099. */
  16100. fromCubemap( cubemap, renderTarget = null ) {
  16101. if ( this._hasInitialized === false ) {
  16102. console.warn( 'THREE.PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead.' );
  16103. this._setSizeFromTexture( cubemap );
  16104. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  16105. this.fromCubemapAsync( cubemap, renderTarget );
  16106. return cubeUVRenderTarget;
  16107. }
  16108. return this._fromTexture( cubemap, renderTarget );
  16109. }
  16110. /**
  16111. * Generates a PMREM from an cubemap texture, which can be either LDR
  16112. * or HDR. The ideal input cube size is 256 x 256,
  16113. * with the 256 x 256 cubemap output.
  16114. *
  16115. * @param {Texture} cubemap - The cubemap texture to be converted.
  16116. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  16117. * @return {Promise<RenderTarget>} The resulting PMREM.
  16118. * @see {@link PMREMGenerator#fromCubemap}
  16119. */
  16120. async fromCubemapAsync( cubemap, renderTarget = null ) {
  16121. if ( this._hasInitialized === false ) await this._renderer.init();
  16122. return this._fromTexture( cubemap, renderTarget );
  16123. }
  16124. /**
  16125. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  16126. * your texture's network fetch for increased concurrency.
  16127. *
  16128. * @returns {Promise}
  16129. */
  16130. async compileCubemapShader() {
  16131. if ( this._cubemapMaterial === null ) {
  16132. this._cubemapMaterial = _getCubemapMaterial();
  16133. await this._compileMaterial( this._cubemapMaterial );
  16134. }
  16135. }
  16136. /**
  16137. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  16138. * your texture's network fetch for increased concurrency.
  16139. *
  16140. * @returns {Promise}
  16141. */
  16142. async compileEquirectangularShader() {
  16143. if ( this._equirectMaterial === null ) {
  16144. this._equirectMaterial = _getEquirectMaterial();
  16145. await this._compileMaterial( this._equirectMaterial );
  16146. }
  16147. }
  16148. /**
  16149. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  16150. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  16151. * one of them will cause any others to also become unusable.
  16152. */
  16153. dispose() {
  16154. this._dispose();
  16155. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  16156. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  16157. if ( this._backgroundBox !== null ) {
  16158. this._backgroundBox.geometry.dispose();
  16159. this._backgroundBox.material.dispose();
  16160. }
  16161. }
  16162. // private interface
  16163. _setSizeFromTexture( texture ) {
  16164. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  16165. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  16166. } else { // Equirectangular
  16167. this._setSize( texture.image.width / 4 );
  16168. }
  16169. }
  16170. _setSize( cubeSize ) {
  16171. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  16172. this._cubeSize = Math.pow( 2, this._lodMax );
  16173. }
  16174. _dispose() {
  16175. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  16176. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  16177. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  16178. this._lodPlanes[ i ].dispose();
  16179. }
  16180. }
  16181. _cleanup( outputTarget ) {
  16182. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  16183. outputTarget.scissorTest = false;
  16184. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  16185. }
  16186. _fromTexture( texture, renderTarget ) {
  16187. this._setSizeFromTexture( texture );
  16188. _oldTarget = this._renderer.getRenderTarget();
  16189. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  16190. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  16191. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  16192. this._init( cubeUVRenderTarget );
  16193. this._textureToCubeUV( texture, cubeUVRenderTarget );
  16194. this._applyPMREM( cubeUVRenderTarget );
  16195. this._cleanup( cubeUVRenderTarget );
  16196. return cubeUVRenderTarget;
  16197. }
  16198. _allocateTarget() {
  16199. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  16200. const height = 4 * this._cubeSize;
  16201. const cubeUVRenderTarget = _createRenderTarget( width, height );
  16202. return cubeUVRenderTarget;
  16203. }
  16204. _init( renderTarget ) {
  16205. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== renderTarget.width || this._pingPongRenderTarget.height !== renderTarget.height ) {
  16206. if ( this._pingPongRenderTarget !== null ) {
  16207. this._dispose();
  16208. }
  16209. this._pingPongRenderTarget = _createRenderTarget( renderTarget.width, renderTarget.height );
  16210. const { _lodMax } = this;
  16211. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas, lodMeshes: this._lodMeshes } = _createPlanes( _lodMax ) );
  16212. this._blurMaterial = _getBlurShader( _lodMax, renderTarget.width, renderTarget.height );
  16213. }
  16214. }
  16215. async _compileMaterial( material ) {
  16216. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  16217. await this._renderer.compile( tmpMesh, _flatCamera );
  16218. }
  16219. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position ) {
  16220. const cubeCamera = _cubeCamera;
  16221. cubeCamera.near = near;
  16222. cubeCamera.far = far;
  16223. // px, py, pz, nx, ny, nz
  16224. const upSign = [ 1, 1, 1, 1, -1, 1 ];
  16225. const forwardSign = [ 1, -1, 1, -1, 1, -1 ];
  16226. const renderer = this._renderer;
  16227. const originalAutoClear = renderer.autoClear;
  16228. renderer.getClearColor( _clearColor$2 );
  16229. renderer.autoClear = false;
  16230. let backgroundBox = this._backgroundBox;
  16231. if ( backgroundBox === null ) {
  16232. const backgroundMaterial = new MeshBasicMaterial( {
  16233. name: 'PMREM.Background',
  16234. side: BackSide,
  16235. depthWrite: false,
  16236. depthTest: false
  16237. } );
  16238. backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  16239. }
  16240. let useSolidColor = false;
  16241. const background = scene.background;
  16242. if ( background ) {
  16243. if ( background.isColor ) {
  16244. backgroundBox.material.color.copy( background );
  16245. scene.background = null;
  16246. useSolidColor = true;
  16247. }
  16248. } else {
  16249. backgroundBox.material.color.copy( _clearColor$2 );
  16250. useSolidColor = true;
  16251. }
  16252. renderer.setRenderTarget( cubeUVRenderTarget );
  16253. renderer.clear();
  16254. if ( useSolidColor ) {
  16255. renderer.render( backgroundBox, cubeCamera );
  16256. }
  16257. for ( let i = 0; i < 6; i ++ ) {
  16258. const col = i % 3;
  16259. if ( col === 0 ) {
  16260. cubeCamera.up.set( 0, upSign[ i ], 0 );
  16261. cubeCamera.position.set( position.x, position.y, position.z );
  16262. cubeCamera.lookAt( position.x + forwardSign[ i ], position.y, position.z );
  16263. } else if ( col === 1 ) {
  16264. cubeCamera.up.set( 0, 0, upSign[ i ] );
  16265. cubeCamera.position.set( position.x, position.y, position.z );
  16266. cubeCamera.lookAt( position.x, position.y + forwardSign[ i ], position.z );
  16267. } else {
  16268. cubeCamera.up.set( 0, upSign[ i ], 0 );
  16269. cubeCamera.position.set( position.x, position.y, position.z );
  16270. cubeCamera.lookAt( position.x, position.y, position.z + forwardSign[ i ] );
  16271. }
  16272. const size = this._cubeSize;
  16273. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  16274. renderer.render( scene, cubeCamera );
  16275. }
  16276. renderer.autoClear = originalAutoClear;
  16277. scene.background = background;
  16278. }
  16279. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  16280. const renderer = this._renderer;
  16281. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  16282. if ( isCubeTexture ) {
  16283. if ( this._cubemapMaterial === null ) {
  16284. this._cubemapMaterial = _getCubemapMaterial( texture );
  16285. }
  16286. } else {
  16287. if ( this._equirectMaterial === null ) {
  16288. this._equirectMaterial = _getEquirectMaterial( texture );
  16289. }
  16290. }
  16291. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  16292. material.fragmentNode.value = texture;
  16293. const mesh = this._lodMeshes[ 0 ];
  16294. mesh.material = material;
  16295. const size = this._cubeSize;
  16296. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  16297. renderer.setRenderTarget( cubeUVRenderTarget );
  16298. renderer.render( mesh, _flatCamera );
  16299. }
  16300. _applyPMREM( cubeUVRenderTarget ) {
  16301. const renderer = this._renderer;
  16302. const autoClear = renderer.autoClear;
  16303. renderer.autoClear = false;
  16304. const n = this._lodPlanes.length;
  16305. for ( let i = 1; i < n; i ++ ) {
  16306. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  16307. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  16308. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  16309. }
  16310. renderer.autoClear = autoClear;
  16311. }
  16312. /**
  16313. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  16314. * vertically and horizontally, but this breaks down on a cube. Here we apply
  16315. * the blur latitudinally (around the poles), and then longitudinally (towards
  16316. * the poles) to approximate the orthogonally-separable blur. It is least
  16317. * accurate at the poles, but still does a decent job.
  16318. *
  16319. * @private
  16320. * @param {RenderTarget} cubeUVRenderTarget - The cubemap render target.
  16321. * @param {number} lodIn - The input level-of-detail.
  16322. * @param {number} lodOut - The output level-of-detail.
  16323. * @param {number} sigma - The blur radius in radians.
  16324. * @param {Vector3} [poleAxis] - The pole axis.
  16325. */
  16326. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  16327. const pingPongRenderTarget = this._pingPongRenderTarget;
  16328. this._halfBlur(
  16329. cubeUVRenderTarget,
  16330. pingPongRenderTarget,
  16331. lodIn,
  16332. lodOut,
  16333. sigma,
  16334. 'latitudinal',
  16335. poleAxis );
  16336. this._halfBlur(
  16337. pingPongRenderTarget,
  16338. cubeUVRenderTarget,
  16339. lodOut,
  16340. lodOut,
  16341. sigma,
  16342. 'longitudinal',
  16343. poleAxis );
  16344. }
  16345. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  16346. const renderer = this._renderer;
  16347. const blurMaterial = this._blurMaterial;
  16348. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  16349. console.error( 'blur direction must be either latitudinal or longitudinal!' );
  16350. }
  16351. // Number of standard deviations at which to cut off the discrete approximation.
  16352. const STANDARD_DEVIATIONS = 3;
  16353. const blurMesh = this._lodMeshes[ lodOut ];
  16354. blurMesh.material = blurMaterial;
  16355. const blurUniforms = _uniformsMap.get( blurMaterial );
  16356. const pixels = this._sizeLods[ lodIn ] - 1;
  16357. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  16358. const sigmaPixels = sigmaRadians / radiansPerPixel;
  16359. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  16360. if ( samples > MAX_SAMPLES ) {
  16361. console.warn( `sigmaRadians, ${
  16362. sigmaRadians}, is too large and will clip, as it requested ${
  16363. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  16364. }
  16365. const weights = [];
  16366. let sum = 0;
  16367. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  16368. const x = i / sigmaPixels;
  16369. const weight = Math.exp( - x * x / 2 );
  16370. weights.push( weight );
  16371. if ( i === 0 ) {
  16372. sum += weight;
  16373. } else if ( i < samples ) {
  16374. sum += 2 * weight;
  16375. }
  16376. }
  16377. for ( let i = 0; i < weights.length; i ++ ) {
  16378. weights[ i ] = weights[ i ] / sum;
  16379. }
  16380. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  16381. blurUniforms.envMap.value = targetIn.texture;
  16382. blurUniforms.samples.value = samples;
  16383. blurUniforms.weights.array = weights;
  16384. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  16385. if ( poleAxis ) {
  16386. blurUniforms.poleAxis.value = poleAxis;
  16387. }
  16388. const { _lodMax } = this;
  16389. blurUniforms.dTheta.value = radiansPerPixel;
  16390. blurUniforms.mipInt.value = _lodMax - lodIn;
  16391. const outputSize = this._sizeLods[ lodOut ];
  16392. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  16393. const y = 4 * ( this._cubeSize - outputSize );
  16394. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  16395. renderer.setRenderTarget( targetOut );
  16396. renderer.render( blurMesh, _flatCamera );
  16397. }
  16398. }
  16399. function _createPlanes( lodMax ) {
  16400. const lodPlanes = [];
  16401. const sizeLods = [];
  16402. const sigmas = [];
  16403. const lodMeshes = [];
  16404. let lod = lodMax;
  16405. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  16406. for ( let i = 0; i < totalLods; i ++ ) {
  16407. const sizeLod = Math.pow( 2, lod );
  16408. sizeLods.push( sizeLod );
  16409. let sigma = 1.0 / sizeLod;
  16410. if ( i > lodMax - LOD_MIN ) {
  16411. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  16412. } else if ( i === 0 ) {
  16413. sigma = 0;
  16414. }
  16415. sigmas.push( sigma );
  16416. const texelSize = 1.0 / ( sizeLod - 2 );
  16417. const min = - texelSize;
  16418. const max = 1 + texelSize;
  16419. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  16420. const cubeFaces = 6;
  16421. const vertices = 6;
  16422. const positionSize = 3;
  16423. const uvSize = 2;
  16424. const faceIndexSize = 1;
  16425. const position = new Float32Array( positionSize * vertices * cubeFaces );
  16426. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  16427. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  16428. for ( let face = 0; face < cubeFaces; face ++ ) {
  16429. const x = ( face % 3 ) * 2 / 3 - 1;
  16430. const y = face > 2 ? 0 : -1;
  16431. const coordinates = [
  16432. x, y, 0,
  16433. x + 2 / 3, y, 0,
  16434. x + 2 / 3, y + 1, 0,
  16435. x, y, 0,
  16436. x + 2 / 3, y + 1, 0,
  16437. x, y + 1, 0
  16438. ];
  16439. const faceIdx = _faceLib[ face ];
  16440. position.set( coordinates, positionSize * vertices * faceIdx );
  16441. uv.set( uv1, uvSize * vertices * faceIdx );
  16442. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  16443. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  16444. }
  16445. const planes = new BufferGeometry();
  16446. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  16447. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  16448. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  16449. lodPlanes.push( planes );
  16450. lodMeshes.push( new Mesh( planes, null ) );
  16451. if ( lod > LOD_MIN ) {
  16452. lod --;
  16453. }
  16454. }
  16455. return { lodPlanes, sizeLods, sigmas, lodMeshes };
  16456. }
  16457. function _createRenderTarget( width, height ) {
  16458. const params = {
  16459. magFilter: LinearFilter,
  16460. minFilter: LinearFilter,
  16461. generateMipmaps: false,
  16462. type: HalfFloatType,
  16463. format: RGBAFormat,
  16464. colorSpace: LinearSRGBColorSpace,
  16465. //depthBuffer: false
  16466. };
  16467. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  16468. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  16469. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  16470. cubeUVRenderTarget.texture.isPMREMTexture = true;
  16471. cubeUVRenderTarget.scissorTest = true;
  16472. return cubeUVRenderTarget;
  16473. }
  16474. function _setViewport( target, x, y, width, height ) {
  16475. target.viewport.set( x, y, width, height );
  16476. target.scissor.set( x, y, width, height );
  16477. }
  16478. function _getMaterial( type ) {
  16479. const material = new NodeMaterial();
  16480. material.depthTest = false;
  16481. material.depthWrite = false;
  16482. material.blending = NoBlending;
  16483. material.name = `PMREM_${ type }`;
  16484. return material;
  16485. }
  16486. function _getBlurShader( lodMax, width, height ) {
  16487. const weights = uniformArray( new Array( MAX_SAMPLES ).fill( 0 ) );
  16488. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  16489. const dTheta = uniform( 0 );
  16490. const n = float( MAX_SAMPLES );
  16491. const latitudinal = uniform( 0 ); // false, bool
  16492. const samples = uniform( 1 ); // int
  16493. const envMap = texture( null );
  16494. const mipInt = uniform( 0 ); // int
  16495. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  16496. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  16497. const CUBEUV_MAX_MIP = float( lodMax );
  16498. const materialUniforms = {
  16499. n,
  16500. latitudinal,
  16501. weights,
  16502. poleAxis,
  16503. outputDirection: _outputDirection,
  16504. dTheta,
  16505. samples,
  16506. envMap,
  16507. mipInt,
  16508. CUBEUV_TEXEL_WIDTH,
  16509. CUBEUV_TEXEL_HEIGHT,
  16510. CUBEUV_MAX_MIP
  16511. };
  16512. const material = _getMaterial( 'blur' );
  16513. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  16514. _uniformsMap.set( material, materialUniforms );
  16515. return material;
  16516. }
  16517. function _getCubemapMaterial( envTexture ) {
  16518. const material = _getMaterial( 'cubemap' );
  16519. material.fragmentNode = cubeTexture( envTexture, _outputDirection );
  16520. return material;
  16521. }
  16522. function _getEquirectMaterial( envTexture ) {
  16523. const material = _getMaterial( 'equirect' );
  16524. material.fragmentNode = texture( envTexture, equirectUV( _outputDirection ), 0 );
  16525. return material;
  16526. }
  16527. const _cache = new WeakMap();
  16528. /**
  16529. * Generates the cubeUV size based on the given image height.
  16530. *
  16531. * @private
  16532. * @param {number} imageHeight - The image height.
  16533. * @return {{texelWidth: number,texelHeight: number, maxMip: number}} The result object.
  16534. */
  16535. function _generateCubeUVSize( imageHeight ) {
  16536. const maxMip = Math.log2( imageHeight ) - 2;
  16537. const texelHeight = 1.0 / imageHeight;
  16538. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  16539. return { texelWidth, texelHeight, maxMip };
  16540. }
  16541. /**
  16542. * Generates a PMREM from the given texture.
  16543. *
  16544. * @private
  16545. * @param {Texture} texture - The texture to create the PMREM for.
  16546. * @param {Renderer} renderer - The renderer.
  16547. * @param {PMREMGenerator} generator - The PMREM generator.
  16548. * @return {?Texture} The PMREM.
  16549. */
  16550. function _getPMREMFromTexture( texture, renderer, generator ) {
  16551. const cache = _getCache( renderer );
  16552. let cacheTexture = cache.get( texture );
  16553. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : -1;
  16554. if ( pmremVersion !== texture.pmremVersion ) {
  16555. const image = texture.image;
  16556. if ( texture.isCubeTexture ) {
  16557. if ( isCubeMapReady( image ) ) {
  16558. cacheTexture = generator.fromCubemap( texture, cacheTexture );
  16559. } else {
  16560. return null;
  16561. }
  16562. } else {
  16563. if ( isEquirectangularMapReady( image ) ) {
  16564. cacheTexture = generator.fromEquirectangular( texture, cacheTexture );
  16565. } else {
  16566. return null;
  16567. }
  16568. }
  16569. cacheTexture.pmremVersion = texture.pmremVersion;
  16570. cache.set( texture, cacheTexture );
  16571. }
  16572. return cacheTexture.texture;
  16573. }
  16574. /**
  16575. * Returns a cache that stores generated PMREMs for the respective textures.
  16576. * A cache must be maintained per renderer since PMREMs are render target textures
  16577. * which can't be shared across render contexts.
  16578. *
  16579. * @private
  16580. * @param {Renderer} renderer - The renderer.
  16581. * @return {WeakMap<Texture, Texture>} The PMREM cache.
  16582. */
  16583. function _getCache( renderer ) {
  16584. let rendererCache = _cache.get( renderer );
  16585. if ( rendererCache === undefined ) {
  16586. rendererCache = new WeakMap();
  16587. _cache.set( renderer, rendererCache );
  16588. }
  16589. return rendererCache;
  16590. }
  16591. /**
  16592. * This node represents a PMREM which is a special type of preprocessed
  16593. * environment map intended for PBR materials.
  16594. *
  16595. * ```js
  16596. * const material = new MeshStandardNodeMaterial();
  16597. * material.envNode = pmremTexture( envMap );
  16598. * ```
  16599. *
  16600. * @augments TempNode
  16601. */
  16602. class PMREMNode extends TempNode {
  16603. static get type() {
  16604. return 'PMREMNode';
  16605. }
  16606. /**
  16607. * Constructs a new function overloading node.
  16608. *
  16609. * @param {Texture} value - The input texture.
  16610. * @param {Node<vec2>} [uvNode=null] - The uv node.
  16611. * @param {Node<float>} [levelNode=null] - The level node.
  16612. */
  16613. constructor( value, uvNode = null, levelNode = null ) {
  16614. super( 'vec3' );
  16615. /**
  16616. * Reference to the input texture.
  16617. *
  16618. * @private
  16619. * @type {Texture}
  16620. */
  16621. this._value = value;
  16622. /**
  16623. * Reference to the generated PMREM.
  16624. *
  16625. * @private
  16626. * @type {Texture | null}
  16627. * @default null
  16628. */
  16629. this._pmrem = null;
  16630. /**
  16631. * The uv node.
  16632. *
  16633. * @type {Node<vec2>}
  16634. */
  16635. this.uvNode = uvNode;
  16636. /**
  16637. * The level node.
  16638. *
  16639. * @type {Node<float>}
  16640. */
  16641. this.levelNode = levelNode;
  16642. /**
  16643. * Reference to a PMREM generator.
  16644. *
  16645. * @private
  16646. * @type {?PMREMGenerator}
  16647. * @default null
  16648. */
  16649. this._generator = null;
  16650. const defaultTexture = new Texture();
  16651. defaultTexture.isRenderTargetTexture = true;
  16652. /**
  16653. * The texture node holding the generated PMREM.
  16654. *
  16655. * @private
  16656. * @type {TextureNode}
  16657. */
  16658. this._texture = texture( defaultTexture );
  16659. /**
  16660. * A uniform representing the PMREM's width.
  16661. *
  16662. * @private
  16663. * @type {UniformNode<float>}
  16664. */
  16665. this._width = uniform( 0 );
  16666. /**
  16667. * A uniform representing the PMREM's height.
  16668. *
  16669. * @private
  16670. * @type {UniformNode<float>}
  16671. */
  16672. this._height = uniform( 0 );
  16673. /**
  16674. * A uniform representing the PMREM's max Mip.
  16675. *
  16676. * @private
  16677. * @type {UniformNode<float>}
  16678. */
  16679. this._maxMip = uniform( 0 );
  16680. /**
  16681. * The `updateBeforeType` is set to `NodeUpdateType.RENDER`.
  16682. *
  16683. * @type {string}
  16684. * @default 'render'
  16685. */
  16686. this.updateBeforeType = NodeUpdateType.RENDER;
  16687. }
  16688. set value( value ) {
  16689. this._value = value;
  16690. this._pmrem = null;
  16691. }
  16692. /**
  16693. * The node's texture value.
  16694. *
  16695. * @type {Texture}
  16696. */
  16697. get value() {
  16698. return this._value;
  16699. }
  16700. /**
  16701. * Uses the given PMREM texture to update internal values.
  16702. *
  16703. * @param {Texture} texture - The PMREM texture.
  16704. */
  16705. updateFromTexture( texture ) {
  16706. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  16707. this._texture.value = texture;
  16708. this._width.value = cubeUVSize.texelWidth;
  16709. this._height.value = cubeUVSize.texelHeight;
  16710. this._maxMip.value = cubeUVSize.maxMip;
  16711. }
  16712. updateBefore( frame ) {
  16713. let pmrem = this._pmrem;
  16714. const pmremVersion = pmrem ? pmrem.pmremVersion : -1;
  16715. const texture = this._value;
  16716. if ( pmremVersion !== texture.pmremVersion ) {
  16717. if ( texture.isPMREMTexture === true ) {
  16718. pmrem = texture;
  16719. } else {
  16720. pmrem = _getPMREMFromTexture( texture, frame.renderer, this._generator );
  16721. }
  16722. if ( pmrem !== null ) {
  16723. this._pmrem = pmrem;
  16724. this.updateFromTexture( pmrem );
  16725. }
  16726. }
  16727. }
  16728. setup( builder ) {
  16729. if ( this._generator === null ) {
  16730. this._generator = new PMREMGenerator( builder.renderer );
  16731. }
  16732. this.updateBefore( builder );
  16733. //
  16734. let uvNode = this.uvNode;
  16735. if ( uvNode === null && builder.context.getUV ) {
  16736. uvNode = builder.context.getUV( this );
  16737. }
  16738. //
  16739. uvNode = materialEnvRotation.mul( vec3( uvNode.x, uvNode.y.negate(), uvNode.z ) );
  16740. //
  16741. let levelNode = this.levelNode;
  16742. if ( levelNode === null && builder.context.getTextureLevel ) {
  16743. levelNode = builder.context.getTextureLevel( this );
  16744. }
  16745. //
  16746. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  16747. }
  16748. dispose() {
  16749. super.dispose();
  16750. if ( this._generator !== null ) this._generator.dispose();
  16751. }
  16752. }
  16753. /**
  16754. * Returns `true` if the given cube map image has been fully loaded.
  16755. *
  16756. * @private
  16757. * @param {?Array<(Image|Object)>} [image] - The cube map image.
  16758. * @return {boolean} Whether the given cube map is ready or not.
  16759. */
  16760. function isCubeMapReady( image ) {
  16761. if ( image === null || image === undefined ) return false;
  16762. let count = 0;
  16763. const length = 6;
  16764. for ( let i = 0; i < length; i ++ ) {
  16765. if ( image[ i ] !== undefined ) count ++;
  16766. }
  16767. return count === length;
  16768. }
  16769. /**
  16770. * Returns `true` if the given equirectangular image has been fully loaded.
  16771. *
  16772. * @private
  16773. * @param {(Image|Object)} image - The equirectangular image.
  16774. * @return {boolean} Whether the given cube map is ready or not.
  16775. */
  16776. function isEquirectangularMapReady( image ) {
  16777. if ( image === null || image === undefined ) return false;
  16778. return image.height > 0;
  16779. }
  16780. /**
  16781. * TSL function for creating a PMREM node.
  16782. *
  16783. * @tsl
  16784. * @function
  16785. * @param {Texture} value - The input texture.
  16786. * @param {?Node<vec2>} [uvNode=null] - The uv node.
  16787. * @param {?Node<float>} [levelNode=null] - The level node.
  16788. * @returns {PMREMNode}
  16789. */
  16790. const pmremTexture = /*@__PURE__*/ nodeProxy( PMREMNode ).setParameterLength( 1, 3 );
  16791. const _envNodeCache = new WeakMap();
  16792. /**
  16793. * Represents a physical model for Image-based lighting (IBL). The environment
  16794. * is defined via environment maps in the equirectangular, cube map or cubeUV (PMREM) format.
  16795. * `EnvironmentNode` is intended for PBR materials like {@link MeshStandardNodeMaterial}.
  16796. *
  16797. * @augments LightingNode
  16798. */
  16799. class EnvironmentNode extends LightingNode {
  16800. static get type() {
  16801. return 'EnvironmentNode';
  16802. }
  16803. /**
  16804. * Constructs a new environment node.
  16805. *
  16806. * @param {Node} [envNode=null] - A node representing the environment.
  16807. */
  16808. constructor( envNode = null ) {
  16809. super();
  16810. /**
  16811. * A node representing the environment.
  16812. *
  16813. * @type {?Node}
  16814. * @default null
  16815. */
  16816. this.envNode = envNode;
  16817. }
  16818. setup( builder ) {
  16819. const { material } = builder;
  16820. let envNode = this.envNode;
  16821. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  16822. const value = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  16823. let cacheEnvNode = _envNodeCache.get( value );
  16824. if ( cacheEnvNode === undefined ) {
  16825. cacheEnvNode = pmremTexture( value );
  16826. _envNodeCache.set( value, cacheEnvNode );
  16827. }
  16828. envNode = cacheEnvNode;
  16829. }
  16830. //
  16831. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  16832. const radianceNormalView = useAnisotropy ? transformedBentNormalView : transformedNormalView;
  16833. const radiance = envNode.context( createRadianceContext( roughness, radianceNormalView ) ).mul( materialEnvIntensity );
  16834. const irradiance = envNode.context( createIrradianceContext( transformedNormalWorld ) ).mul( Math.PI ).mul( materialEnvIntensity );
  16835. const isolateRadiance = cache( radiance );
  16836. const isolateIrradiance = cache( irradiance );
  16837. //
  16838. builder.context.radiance.addAssign( isolateRadiance );
  16839. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  16840. //
  16841. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  16842. if ( clearcoatRadiance ) {
  16843. const clearcoatRadianceContext = envNode.context( createRadianceContext( clearcoatRoughness, transformedClearcoatNormalView ) ).mul( materialEnvIntensity );
  16844. const isolateClearcoatRadiance = cache( clearcoatRadianceContext );
  16845. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  16846. }
  16847. }
  16848. }
  16849. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  16850. let reflectVec = null;
  16851. return {
  16852. getUV: () => {
  16853. if ( reflectVec === null ) {
  16854. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  16855. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  16856. reflectVec = roughnessNode.mul( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  16857. reflectVec = reflectVec.transformDirection( cameraViewMatrix );
  16858. }
  16859. return reflectVec;
  16860. },
  16861. getTextureLevel: () => {
  16862. return roughnessNode;
  16863. }
  16864. };
  16865. };
  16866. const createIrradianceContext = ( normalWorldNode ) => {
  16867. return {
  16868. getUV: () => {
  16869. return normalWorldNode;
  16870. },
  16871. getTextureLevel: () => {
  16872. return float( 1.0 );
  16873. }
  16874. };
  16875. };
  16876. const _defaultValues$6 = /*@__PURE__*/ new MeshStandardMaterial();
  16877. /**
  16878. * Node material version of {@link MeshStandardMaterial}.
  16879. *
  16880. * @augments NodeMaterial
  16881. */
  16882. class MeshStandardNodeMaterial extends NodeMaterial {
  16883. static get type() {
  16884. return 'MeshStandardNodeMaterial';
  16885. }
  16886. /**
  16887. * Constructs a new mesh standard node material.
  16888. *
  16889. * @param {Object} [parameters] - The configuration parameter.
  16890. */
  16891. constructor( parameters ) {
  16892. super();
  16893. /**
  16894. * This flag can be used for type testing.
  16895. *
  16896. * @type {boolean}
  16897. * @readonly
  16898. * @default true
  16899. */
  16900. this.isMeshStandardNodeMaterial = true;
  16901. /**
  16902. * Set to `true` because standard materials react on lights.
  16903. *
  16904. * @type {boolean}
  16905. * @default true
  16906. */
  16907. this.lights = true;
  16908. /**
  16909. * The emissive color of standard materials is by default inferred from the `emissive`,
  16910. * `emissiveIntensity` and `emissiveMap` properties. This node property allows to
  16911. * overwrite the default and define the emissive color with a node instead.
  16912. *
  16913. * If you don't want to overwrite the emissive color but modify the existing
  16914. * value instead, use {@link materialEmissive}.
  16915. *
  16916. * @type {?Node<vec3>}
  16917. * @default null
  16918. */
  16919. this.emissiveNode = null;
  16920. /**
  16921. * The metalness of standard materials is by default inferred from the `metalness`,
  16922. * and `metalnessMap` properties. This node property allows to
  16923. * overwrite the default and define the metalness with a node instead.
  16924. *
  16925. * If you don't want to overwrite the metalness but modify the existing
  16926. * value instead, use {@link materialMetalness}.
  16927. *
  16928. * @type {?Node<float>}
  16929. * @default null
  16930. */
  16931. this.metalnessNode = null;
  16932. /**
  16933. * The roughness of standard materials is by default inferred from the `roughness`,
  16934. * and `roughnessMap` properties. This node property allows to
  16935. * overwrite the default and define the roughness with a node instead.
  16936. *
  16937. * If you don't want to overwrite the roughness but modify the existing
  16938. * value instead, use {@link materialRoughness}.
  16939. *
  16940. * @type {?Node<float>}
  16941. * @default null
  16942. */
  16943. this.roughnessNode = null;
  16944. this.setDefaultValues( _defaultValues$6 );
  16945. this.setValues( parameters );
  16946. }
  16947. /**
  16948. * Overwritten since this type of material uses {@link EnvironmentNode}
  16949. * to implement the PBR (PMREM based) environment mapping. Besides, the
  16950. * method honors `Scene.environment`.
  16951. *
  16952. * @param {NodeBuilder} builder - The current node builder.
  16953. * @return {?EnvironmentNode<vec3>} The environment node.
  16954. */
  16955. setupEnvironment( builder ) {
  16956. let envNode = super.setupEnvironment( builder );
  16957. if ( envNode === null && builder.environmentNode ) {
  16958. envNode = builder.environmentNode;
  16959. }
  16960. return envNode ? new EnvironmentNode( envNode ) : null;
  16961. }
  16962. /**
  16963. * Setups the lighting model.
  16964. *
  16965. * @return {PhysicalLightingModel} The lighting model.
  16966. */
  16967. setupLightingModel( /*builder*/ ) {
  16968. return new PhysicalLightingModel();
  16969. }
  16970. /**
  16971. * Setups the specular related node variables.
  16972. */
  16973. setupSpecular() {
  16974. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  16975. specularColor.assign( specularColorNode );
  16976. specularF90.assign( 1.0 );
  16977. }
  16978. /**
  16979. * Setups the standard specific node variables.
  16980. *
  16981. * @param {NodeBuilder} builder - The current node builder.
  16982. */
  16983. setupVariants() {
  16984. // METALNESS
  16985. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  16986. metalness.assign( metalnessNode );
  16987. // ROUGHNESS
  16988. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  16989. roughnessNode = getRoughness( { roughness: roughnessNode } );
  16990. roughness.assign( roughnessNode );
  16991. // SPECULAR COLOR
  16992. this.setupSpecular();
  16993. // DIFFUSE COLOR
  16994. diffuseColor.assign( vec4( diffuseColor.rgb.mul( metalnessNode.oneMinus() ), diffuseColor.a ) );
  16995. }
  16996. copy( source ) {
  16997. this.emissiveNode = source.emissiveNode;
  16998. this.metalnessNode = source.metalnessNode;
  16999. this.roughnessNode = source.roughnessNode;
  17000. return super.copy( source );
  17001. }
  17002. }
  17003. const _defaultValues$5 = /*@__PURE__*/ new MeshPhysicalMaterial();
  17004. /**
  17005. * Node material version of {@link MeshPhysicalMaterial}.
  17006. *
  17007. * @augments MeshStandardNodeMaterial
  17008. */
  17009. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  17010. static get type() {
  17011. return 'MeshPhysicalNodeMaterial';
  17012. }
  17013. /**
  17014. * Constructs a new mesh physical node material.
  17015. *
  17016. * @param {Object} [parameters] - The configuration parameter.
  17017. */
  17018. constructor( parameters ) {
  17019. super();
  17020. /**
  17021. * This flag can be used for type testing.
  17022. *
  17023. * @type {boolean}
  17024. * @readonly
  17025. * @default true
  17026. */
  17027. this.isMeshPhysicalNodeMaterial = true;
  17028. /**
  17029. * The clearcoat of physical materials is by default inferred from the `clearcoat`
  17030. * and `clearcoatMap` properties. This node property allows to overwrite the default
  17031. * and define the clearcoat with a node instead.
  17032. *
  17033. * If you don't want to overwrite the clearcoat but modify the existing
  17034. * value instead, use {@link materialClearcoat}.
  17035. *
  17036. * @type {?Node<float>}
  17037. * @default null
  17038. */
  17039. this.clearcoatNode = null;
  17040. /**
  17041. * The clearcoat roughness of physical materials is by default inferred from the `clearcoatRoughness`
  17042. * and `clearcoatRoughnessMap` properties. This node property allows to overwrite the default
  17043. * and define the clearcoat roughness with a node instead.
  17044. *
  17045. * If you don't want to overwrite the clearcoat roughness but modify the existing
  17046. * value instead, use {@link materialClearcoatRoughness}.
  17047. *
  17048. * @type {?Node<float>}
  17049. * @default null
  17050. */
  17051. this.clearcoatRoughnessNode = null;
  17052. /**
  17053. * The clearcoat normal of physical materials is by default inferred from the `clearcoatNormalMap`
  17054. * property. This node property allows to overwrite the default
  17055. * and define the clearcoat normal with a node instead.
  17056. *
  17057. * If you don't want to overwrite the clearcoat normal but modify the existing
  17058. * value instead, use {@link materialClearcoatNormal}.
  17059. *
  17060. * @type {?Node<vec3>}
  17061. * @default null
  17062. */
  17063. this.clearcoatNormalNode = null;
  17064. /**
  17065. * The sheen of physical materials is by default inferred from the `sheen`, `sheenColor`
  17066. * and `sheenColorMap` properties. This node property allows to overwrite the default
  17067. * and define the sheen with a node instead.
  17068. *
  17069. * If you don't want to overwrite the sheen but modify the existing
  17070. * value instead, use {@link materialSheen}.
  17071. *
  17072. * @type {?Node<vec3>}
  17073. * @default null
  17074. */
  17075. this.sheenNode = null;
  17076. /**
  17077. * The sheen roughness of physical materials is by default inferred from the `sheenRoughness` and
  17078. * `sheenRoughnessMap` properties. This node property allows to overwrite the default
  17079. * and define the sheen roughness with a node instead.
  17080. *
  17081. * If you don't want to overwrite the sheen roughness but modify the existing
  17082. * value instead, use {@link materialSheenRoughness}.
  17083. *
  17084. * @type {?Node<float>}
  17085. * @default null
  17086. */
  17087. this.sheenRoughnessNode = null;
  17088. /**
  17089. * The iridescence of physical materials is by default inferred from the `iridescence`
  17090. * property. This node property allows to overwrite the default
  17091. * and define the iridescence with a node instead.
  17092. *
  17093. * If you don't want to overwrite the iridescence but modify the existing
  17094. * value instead, use {@link materialIridescence}.
  17095. *
  17096. * @type {?Node<float>}
  17097. * @default null
  17098. */
  17099. this.iridescenceNode = null;
  17100. /**
  17101. * The iridescence IOR of physical materials is by default inferred from the `iridescenceIOR`
  17102. * property. This node property allows to overwrite the default
  17103. * and define the iridescence IOR with a node instead.
  17104. *
  17105. * If you don't want to overwrite the iridescence IOR but modify the existing
  17106. * value instead, use {@link materialIridescenceIOR}.
  17107. *
  17108. * @type {?Node<float>}
  17109. * @default null
  17110. */
  17111. this.iridescenceIORNode = null;
  17112. /**
  17113. * The iridescence thickness of physical materials is by default inferred from the `iridescenceThicknessRange`
  17114. * and `iridescenceThicknessMap` properties. This node property allows to overwrite the default
  17115. * and define the iridescence thickness with a node instead.
  17116. *
  17117. * If you don't want to overwrite the iridescence thickness but modify the existing
  17118. * value instead, use {@link materialIridescenceThickness}.
  17119. *
  17120. * @type {?Node<float>}
  17121. * @default null
  17122. */
  17123. this.iridescenceThicknessNode = null;
  17124. /**
  17125. * The specular intensity of physical materials is by default inferred from the `specularIntensity`
  17126. * and `specularIntensityMap` properties. This node property allows to overwrite the default
  17127. * and define the specular intensity with a node instead.
  17128. *
  17129. * If you don't want to overwrite the specular intensity but modify the existing
  17130. * value instead, use {@link materialSpecularIntensity}.
  17131. *
  17132. * @type {?Node<float>}
  17133. * @default null
  17134. */
  17135. this.specularIntensityNode = null;
  17136. /**
  17137. * The specular color of physical materials is by default inferred from the `specularColor`
  17138. * and `specularColorMap` properties. This node property allows to overwrite the default
  17139. * and define the specular color with a node instead.
  17140. *
  17141. * If you don't want to overwrite the specular color but modify the existing
  17142. * value instead, use {@link materialSpecularColor}.
  17143. *
  17144. * @type {?Node<vec3>}
  17145. * @default null
  17146. */
  17147. this.specularColorNode = null;
  17148. /**
  17149. * The ior of physical materials is by default inferred from the `ior`
  17150. * property. This node property allows to overwrite the default
  17151. * and define the ior with a node instead.
  17152. *
  17153. * If you don't want to overwrite the ior but modify the existing
  17154. * value instead, use {@link materialIOR}.
  17155. *
  17156. * @type {?Node<float>}
  17157. * @default null
  17158. */
  17159. this.iorNode = null;
  17160. /**
  17161. * The transmission of physical materials is by default inferred from the `transmission` and
  17162. * `transmissionMap` properties. This node property allows to overwrite the default
  17163. * and define the transmission with a node instead.
  17164. *
  17165. * If you don't want to overwrite the transmission but modify the existing
  17166. * value instead, use {@link materialTransmission}.
  17167. *
  17168. * @type {?Node<float>}
  17169. * @default null
  17170. */
  17171. this.transmissionNode = null;
  17172. /**
  17173. * The thickness of physical materials is by default inferred from the `thickness` and
  17174. * `thicknessMap` properties. This node property allows to overwrite the default
  17175. * and define the thickness with a node instead.
  17176. *
  17177. * If you don't want to overwrite the thickness but modify the existing
  17178. * value instead, use {@link materialThickness}.
  17179. *
  17180. * @type {?Node<float>}
  17181. * @default null
  17182. */
  17183. this.thicknessNode = null;
  17184. /**
  17185. * The attenuation distance of physical materials is by default inferred from the
  17186. * `attenuationDistance` property. This node property allows to overwrite the default
  17187. * and define the attenuation distance with a node instead.
  17188. *
  17189. * If you don't want to overwrite the attenuation distance but modify the existing
  17190. * value instead, use {@link materialAttenuationDistance}.
  17191. *
  17192. * @type {?Node<float>}
  17193. * @default null
  17194. */
  17195. this.attenuationDistanceNode = null;
  17196. /**
  17197. * The attenuation color of physical materials is by default inferred from the
  17198. * `attenuationColor` property. This node property allows to overwrite the default
  17199. * and define the attenuation color with a node instead.
  17200. *
  17201. * If you don't want to overwrite the attenuation color but modify the existing
  17202. * value instead, use {@link materialAttenuationColor}.
  17203. *
  17204. * @type {?Node<vec3>}
  17205. * @default null
  17206. */
  17207. this.attenuationColorNode = null;
  17208. /**
  17209. * The dispersion of physical materials is by default inferred from the
  17210. * `dispersion` property. This node property allows to overwrite the default
  17211. * and define the dispersion with a node instead.
  17212. *
  17213. * If you don't want to overwrite the dispersion but modify the existing
  17214. * value instead, use {@link materialDispersion}.
  17215. *
  17216. * @type {?Node<float>}
  17217. * @default null
  17218. */
  17219. this.dispersionNode = null;
  17220. /**
  17221. * The anisotropy of physical materials is by default inferred from the
  17222. * `anisotropy` property. This node property allows to overwrite the default
  17223. * and define the anisotropy with a node instead.
  17224. *
  17225. * If you don't want to overwrite the anisotropy but modify the existing
  17226. * value instead, use {@link materialAnisotropy}.
  17227. *
  17228. * @type {?Node<float>}
  17229. * @default null
  17230. */
  17231. this.anisotropyNode = null;
  17232. this.setDefaultValues( _defaultValues$5 );
  17233. this.setValues( parameters );
  17234. }
  17235. /**
  17236. * Whether the lighting model should use clearcoat or not.
  17237. *
  17238. * @type {boolean}
  17239. * @default true
  17240. */
  17241. get useClearcoat() {
  17242. return this.clearcoat > 0 || this.clearcoatNode !== null;
  17243. }
  17244. /**
  17245. * Whether the lighting model should use iridescence or not.
  17246. *
  17247. * @type {boolean}
  17248. * @default true
  17249. */
  17250. get useIridescence() {
  17251. return this.iridescence > 0 || this.iridescenceNode !== null;
  17252. }
  17253. /**
  17254. * Whether the lighting model should use sheen or not.
  17255. *
  17256. * @type {boolean}
  17257. * @default true
  17258. */
  17259. get useSheen() {
  17260. return this.sheen > 0 || this.sheenNode !== null;
  17261. }
  17262. /**
  17263. * Whether the lighting model should use anisotropy or not.
  17264. *
  17265. * @type {boolean}
  17266. * @default true
  17267. */
  17268. get useAnisotropy() {
  17269. return this.anisotropy > 0 || this.anisotropyNode !== null;
  17270. }
  17271. /**
  17272. * Whether the lighting model should use transmission or not.
  17273. *
  17274. * @type {boolean}
  17275. * @default true
  17276. */
  17277. get useTransmission() {
  17278. return this.transmission > 0 || this.transmissionNode !== null;
  17279. }
  17280. /**
  17281. * Whether the lighting model should use dispersion or not.
  17282. *
  17283. * @type {boolean}
  17284. * @default true
  17285. */
  17286. get useDispersion() {
  17287. return this.dispersion > 0 || this.dispersionNode !== null;
  17288. }
  17289. /**
  17290. * Setups the specular related node variables.
  17291. */
  17292. setupSpecular() {
  17293. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  17294. ior.assign( iorNode );
  17295. 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 ) );
  17296. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  17297. }
  17298. /**
  17299. * Setups the lighting model.
  17300. *
  17301. * @return {PhysicalLightingModel} The lighting model.
  17302. */
  17303. setupLightingModel( /*builder*/ ) {
  17304. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion );
  17305. }
  17306. /**
  17307. * Setups the physical specific node variables.
  17308. *
  17309. * @param {NodeBuilder} builder - The current node builder.
  17310. */
  17311. setupVariants( builder ) {
  17312. super.setupVariants( builder );
  17313. // CLEARCOAT
  17314. if ( this.useClearcoat ) {
  17315. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  17316. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  17317. clearcoat.assign( clearcoatNode );
  17318. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  17319. }
  17320. // SHEEN
  17321. if ( this.useSheen ) {
  17322. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  17323. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  17324. sheen.assign( sheenNode );
  17325. sheenRoughness.assign( sheenRoughnessNode );
  17326. }
  17327. // IRIDESCENCE
  17328. if ( this.useIridescence ) {
  17329. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  17330. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  17331. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  17332. iridescence.assign( iridescenceNode );
  17333. iridescenceIOR.assign( iridescenceIORNode );
  17334. iridescenceThickness.assign( iridescenceThicknessNode );
  17335. }
  17336. // ANISOTROPY
  17337. if ( this.useAnisotropy ) {
  17338. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  17339. anisotropy.assign( anisotropyV.length() );
  17340. If( anisotropy.equal( 0.0 ), () => {
  17341. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  17342. } ).Else( () => {
  17343. anisotropyV.divAssign( vec2( anisotropy ) );
  17344. anisotropy.assign( anisotropy.saturate() );
  17345. } );
  17346. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  17347. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  17348. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  17349. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  17350. }
  17351. // TRANSMISSION
  17352. if ( this.useTransmission ) {
  17353. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  17354. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  17355. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  17356. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  17357. transmission.assign( transmissionNode );
  17358. thickness.assign( thicknessNode );
  17359. attenuationDistance.assign( attenuationDistanceNode );
  17360. attenuationColor.assign( attenuationColorNode );
  17361. if ( this.useDispersion ) {
  17362. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  17363. dispersion.assign( dispersionNode );
  17364. }
  17365. }
  17366. }
  17367. /**
  17368. * Setups the clearcoat normal node.
  17369. *
  17370. * @return {Node<vec3>} The clearcoat normal.
  17371. */
  17372. setupClearcoatNormal() {
  17373. return this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  17374. }
  17375. setup( builder ) {
  17376. builder.context.setupClearcoatNormal = () => this.setupClearcoatNormal( builder );
  17377. super.setup( builder );
  17378. }
  17379. copy( source ) {
  17380. this.clearcoatNode = source.clearcoatNode;
  17381. this.clearcoatRoughnessNode = source.clearcoatRoughnessNode;
  17382. this.clearcoatNormalNode = source.clearcoatNormalNode;
  17383. this.sheenNode = source.sheenNode;
  17384. this.sheenRoughnessNode = source.sheenRoughnessNode;
  17385. this.iridescenceNode = source.iridescenceNode;
  17386. this.iridescenceIORNode = source.iridescenceIORNode;
  17387. this.iridescenceThicknessNode = source.iridescenceThicknessNode;
  17388. this.specularIntensityNode = source.specularIntensityNode;
  17389. this.specularColorNode = source.specularColorNode;
  17390. this.transmissionNode = source.transmissionNode;
  17391. this.thicknessNode = source.thicknessNode;
  17392. this.attenuationDistanceNode = source.attenuationDistanceNode;
  17393. this.attenuationColorNode = source.attenuationColorNode;
  17394. this.dispersionNode = source.dispersionNode;
  17395. this.anisotropyNode = source.anisotropyNode;
  17396. return super.copy( source );
  17397. }
  17398. }
  17399. /**
  17400. * Represents the lighting model for {@link MeshSSSNodeMaterial}.
  17401. *
  17402. * @augments PhysicalLightingModel
  17403. */
  17404. class SSSLightingModel extends PhysicalLightingModel {
  17405. /**
  17406. * Constructs a new physical lighting model.
  17407. *
  17408. * @param {boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  17409. * @param {boolean} [sheen=false] - Whether sheen is supported or not.
  17410. * @param {boolean} [iridescence=false] - Whether iridescence is supported or not.
  17411. * @param {boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  17412. * @param {boolean} [transmission=false] - Whether transmission is supported or not.
  17413. * @param {boolean} [dispersion=false] - Whether dispersion is supported or not.
  17414. * @param {boolean} [sss=false] - Whether SSS is supported or not.
  17415. */
  17416. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false, sss = false ) {
  17417. super( clearcoat, sheen, iridescence, anisotropy, transmission, dispersion );
  17418. /**
  17419. * Whether the lighting model should use SSS or not.
  17420. *
  17421. * @type {boolean}
  17422. * @default false
  17423. */
  17424. this.useSSS = sss;
  17425. }
  17426. /**
  17427. * Extends the default implementation with a SSS term.
  17428. *
  17429. * 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/}
  17430. *
  17431. * @param {Object} input - The input data.
  17432. * @param {NodeBuilder} builder - The current node builder.
  17433. */
  17434. direct( { lightDirection, lightColor, reflectedLight }, builder ) {
  17435. if ( this.useSSS === true ) {
  17436. const material = builder.material;
  17437. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  17438. const scatteringHalf = lightDirection.add( transformedNormalView.mul( thicknessDistortionNode ) ).normalize();
  17439. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  17440. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  17441. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  17442. }
  17443. super.direct( { lightDirection, lightColor, reflectedLight }, builder );
  17444. }
  17445. }
  17446. /**
  17447. * This node material is an experimental extension of {@link MeshPhysicalNodeMaterial}
  17448. * that implements a Subsurface scattering (SSS) term.
  17449. *
  17450. * @augments MeshPhysicalNodeMaterial
  17451. */
  17452. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  17453. static get type() {
  17454. return 'MeshSSSNodeMaterial';
  17455. }
  17456. /**
  17457. * Constructs a new mesh SSS node material.
  17458. *
  17459. * @param {Object} [parameters] - The configuration parameter.
  17460. */
  17461. constructor( parameters ) {
  17462. super( parameters );
  17463. /**
  17464. * Represents the thickness color.
  17465. *
  17466. * @type {?Node<vec3>}
  17467. * @default null
  17468. */
  17469. this.thicknessColorNode = null;
  17470. /**
  17471. * Represents the distortion factor.
  17472. *
  17473. * @type {?Node<float>}
  17474. */
  17475. this.thicknessDistortionNode = float( 0.1 );
  17476. /**
  17477. * Represents the thickness ambient factor.
  17478. *
  17479. * @type {?Node<float>}
  17480. */
  17481. this.thicknessAmbientNode = float( 0.0 );
  17482. /**
  17483. * Represents the thickness attenuation.
  17484. *
  17485. * @type {?Node<float>}
  17486. */
  17487. this.thicknessAttenuationNode = float( .1 );
  17488. /**
  17489. * Represents the thickness power.
  17490. *
  17491. * @type {?Node<float>}
  17492. */
  17493. this.thicknessPowerNode = float( 2.0 );
  17494. /**
  17495. * Represents the thickness scale.
  17496. *
  17497. * @type {?Node<float>}
  17498. */
  17499. this.thicknessScaleNode = float( 10.0 );
  17500. }
  17501. /**
  17502. * Whether the lighting model should use SSS or not.
  17503. *
  17504. * @type {boolean}
  17505. * @default true
  17506. */
  17507. get useSSS() {
  17508. return this.thicknessColorNode !== null;
  17509. }
  17510. /**
  17511. * Setups the lighting model.
  17512. *
  17513. * @return {SSSLightingModel} The lighting model.
  17514. */
  17515. setupLightingModel( /*builder*/ ) {
  17516. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion, this.useSSS );
  17517. }
  17518. copy( source ) {
  17519. this.thicknessColorNode = source.thicknessColorNode;
  17520. this.thicknessDistortionNode = source.thicknessDistortionNode;
  17521. this.thicknessAmbientNode = source.thicknessAmbientNode;
  17522. this.thicknessAttenuationNode = source.thicknessAttenuationNode;
  17523. this.thicknessPowerNode = source.thicknessPowerNode;
  17524. this.thicknessScaleNode = source.thicknessScaleNode;
  17525. return super.copy( source );
  17526. }
  17527. }
  17528. const getGradientIrradiance = /*@__PURE__*/ Fn( ( { normal, lightDirection, builder } ) => {
  17529. // dotNL will be from -1.0 to 1.0
  17530. const dotNL = normal.dot( lightDirection );
  17531. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  17532. if ( builder.material.gradientMap ) {
  17533. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  17534. return vec3( gradientMap.r );
  17535. } else {
  17536. const fw = coord.fwidth().mul( 0.5 );
  17537. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  17538. }
  17539. } );
  17540. /**
  17541. * Represents the lighting model for a toon material. Used in {@link MeshToonNodeMaterial}.
  17542. *
  17543. * @augments LightingModel
  17544. */
  17545. class ToonLightingModel extends LightingModel {
  17546. /**
  17547. * Implements the direct lighting. Instead of using a conventional smooth irradiance, the irradiance is
  17548. * reduced to a small number of discrete shades to create a comic-like, flat look.
  17549. *
  17550. * @param {Object} lightData - The light data.
  17551. * @param {NodeBuilder} builder - The current node builder.
  17552. */
  17553. direct( { lightDirection, lightColor, reflectedLight }, builder ) {
  17554. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  17555. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  17556. }
  17557. /**
  17558. * Implements the indirect lighting.
  17559. *
  17560. * @param {NodeBuilder} builder - The current node builder.
  17561. */
  17562. indirect( builder ) {
  17563. const { ambientOcclusion, irradiance, reflectedLight } = builder.context;
  17564. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  17565. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  17566. }
  17567. }
  17568. const _defaultValues$4 = /*@__PURE__*/ new MeshToonMaterial();
  17569. /**
  17570. * Node material version of {@link MeshToonMaterial}.
  17571. *
  17572. * @augments NodeMaterial
  17573. */
  17574. class MeshToonNodeMaterial extends NodeMaterial {
  17575. static get type() {
  17576. return 'MeshToonNodeMaterial';
  17577. }
  17578. /**
  17579. * Constructs a new mesh toon node material.
  17580. *
  17581. * @param {Object} [parameters] - The configuration parameter.
  17582. */
  17583. constructor( parameters ) {
  17584. super();
  17585. /**
  17586. * This flag can be used for type testing.
  17587. *
  17588. * @type {boolean}
  17589. * @readonly
  17590. * @default true
  17591. */
  17592. this.isMeshToonNodeMaterial = true;
  17593. /**
  17594. * Set to `true` because toon materials react on lights.
  17595. *
  17596. * @type {boolean}
  17597. * @default true
  17598. */
  17599. this.lights = true;
  17600. this.setDefaultValues( _defaultValues$4 );
  17601. this.setValues( parameters );
  17602. }
  17603. /**
  17604. * Setups the lighting model.
  17605. *
  17606. * @return {ToonLightingModel} The lighting model.
  17607. */
  17608. setupLightingModel( /*builder*/ ) {
  17609. return new ToonLightingModel();
  17610. }
  17611. }
  17612. /**
  17613. * Can be used to compute texture coordinates for projecting a
  17614. * matcap onto a mesh. Used by {@link MeshMatcapNodeMaterial}.
  17615. *
  17616. * @augments TempNode
  17617. */
  17618. class MatcapUVNode extends TempNode {
  17619. static get type() {
  17620. return 'MatcapUVNode';
  17621. }
  17622. /**
  17623. * Constructs a new matcap uv node.
  17624. */
  17625. constructor() {
  17626. super( 'vec2' );
  17627. }
  17628. setup() {
  17629. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  17630. const y = positionViewDirection.cross( x );
  17631. return vec2( x.dot( transformedNormalView ), y.dot( transformedNormalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  17632. }
  17633. }
  17634. /**
  17635. * TSL function for creating a matcap uv node.
  17636. *
  17637. * @tsl
  17638. * @function
  17639. * @returns {MatcapUVNode}
  17640. */
  17641. const matcapUV = /*@__PURE__*/ nodeImmutable( MatcapUVNode );
  17642. const _defaultValues$3 = /*@__PURE__*/ new MeshMatcapMaterial();
  17643. /**
  17644. * Node material version of {@link MeshMatcapMaterial}.
  17645. *
  17646. * @augments NodeMaterial
  17647. */
  17648. class MeshMatcapNodeMaterial extends NodeMaterial {
  17649. static get type() {
  17650. return 'MeshMatcapNodeMaterial';
  17651. }
  17652. /**
  17653. * Constructs a new mesh normal node material.
  17654. *
  17655. * @param {Object} [parameters] - The configuration parameter.
  17656. */
  17657. constructor( parameters ) {
  17658. super();
  17659. /**
  17660. * This flag can be used for type testing.
  17661. *
  17662. * @type {boolean}
  17663. * @readonly
  17664. * @default true
  17665. */
  17666. this.isMeshMatcapNodeMaterial = true;
  17667. this.setDefaultValues( _defaultValues$3 );
  17668. this.setValues( parameters );
  17669. }
  17670. /**
  17671. * Setups the matcap specific node variables.
  17672. *
  17673. * @param {NodeBuilder} builder - The current node builder.
  17674. */
  17675. setupVariants( builder ) {
  17676. const uv = matcapUV;
  17677. let matcapColor;
  17678. if ( builder.material.matcap ) {
  17679. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  17680. } else {
  17681. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  17682. }
  17683. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  17684. }
  17685. }
  17686. /**
  17687. * Applies a rotation to the given position node.
  17688. *
  17689. * @augments TempNode
  17690. */
  17691. class RotateNode extends TempNode {
  17692. static get type() {
  17693. return 'RotateNode';
  17694. }
  17695. /**
  17696. * Constructs a new rotate node.
  17697. *
  17698. * @param {Node} positionNode - The position node.
  17699. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  17700. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  17701. */
  17702. constructor( positionNode, rotationNode ) {
  17703. super();
  17704. /**
  17705. * The position node.
  17706. *
  17707. * @type {Node}
  17708. */
  17709. this.positionNode = positionNode;
  17710. /**
  17711. * Represents the rotation that is applied to the position node.
  17712. * Depending on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  17713. *
  17714. * @type {Node}
  17715. */
  17716. this.rotationNode = rotationNode;
  17717. }
  17718. /**
  17719. * The type of the {@link RotateNode#positionNode} defines the node's type.
  17720. *
  17721. * @param {NodeBuilder} builder - The current node builder.
  17722. * @return {string} The node's type.
  17723. */
  17724. getNodeType( builder ) {
  17725. return this.positionNode.getNodeType( builder );
  17726. }
  17727. setup( builder ) {
  17728. const { rotationNode, positionNode } = this;
  17729. const nodeType = this.getNodeType( builder );
  17730. if ( nodeType === 'vec2' ) {
  17731. const cosAngle = rotationNode.cos();
  17732. const sinAngle = rotationNode.sin();
  17733. const rotationMatrix = mat2(
  17734. cosAngle, sinAngle,
  17735. sinAngle.negate(), cosAngle
  17736. );
  17737. return rotationMatrix.mul( positionNode );
  17738. } else {
  17739. const rotation = rotationNode;
  17740. 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 ) );
  17741. 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 ) );
  17742. 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 ) );
  17743. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  17744. }
  17745. }
  17746. }
  17747. /**
  17748. * TSL function for creating a rotate node.
  17749. *
  17750. * @tsl
  17751. * @function
  17752. * @param {Node} positionNode - The position node.
  17753. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  17754. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  17755. * @returns {RotateNode}
  17756. */
  17757. const rotate = /*@__PURE__*/ nodeProxy( RotateNode ).setParameterLength( 2 );
  17758. const _defaultValues$2 = /*@__PURE__*/ new SpriteMaterial();
  17759. /**
  17760. * Node material version of {@link SpriteMaterial}.
  17761. *
  17762. * @augments NodeMaterial
  17763. */
  17764. class SpriteNodeMaterial extends NodeMaterial {
  17765. static get type() {
  17766. return 'SpriteNodeMaterial';
  17767. }
  17768. /**
  17769. * Constructs a new sprite node material.
  17770. *
  17771. * @param {Object} [parameters] - The configuration parameter.
  17772. */
  17773. constructor( parameters ) {
  17774. super();
  17775. /**
  17776. * This flag can be used for type testing.
  17777. *
  17778. * @type {boolean}
  17779. * @readonly
  17780. * @default true
  17781. */
  17782. this.isSpriteNodeMaterial = true;
  17783. this._useSizeAttenuation = true;
  17784. /**
  17785. * This property makes it possible to define the position of the sprite with a
  17786. * node. That can be useful when the material is used with instanced rendering
  17787. * and node data are defined with an instanced attribute node:
  17788. * ```js
  17789. * const positionAttribute = new InstancedBufferAttribute( new Float32Array( positions ), 3 );
  17790. * material.positionNode = instancedBufferAttribute( positionAttribute );
  17791. * ```
  17792. * Another possibility is to compute the instanced data with a compute shader:
  17793. * ```js
  17794. * const positionBuffer = instancedArray( particleCount, 'vec3' );
  17795. * particleMaterial.positionNode = positionBuffer.toAttribute();
  17796. * ```
  17797. *
  17798. * @type {?Node<vec2>}
  17799. * @default null
  17800. */
  17801. this.positionNode = null;
  17802. /**
  17803. * The rotation of sprite materials is by default inferred from the `rotation`,
  17804. * property. This node property allows to overwrite the default and define
  17805. * the rotation with a node instead.
  17806. *
  17807. * If you don't want to overwrite the rotation but modify the existing
  17808. * value instead, use {@link materialRotation}.
  17809. *
  17810. * @type {?Node<float>}
  17811. * @default null
  17812. */
  17813. this.rotationNode = null;
  17814. /**
  17815. * This node property provides an additional way to scale sprites next to
  17816. * `Object3D.scale`. The scale transformation based in `Object3D.scale`
  17817. * is multiplied with the scale value of this node in the vertex shader.
  17818. *
  17819. * @type {?Node<vec2>}
  17820. * @default null
  17821. */
  17822. this.scaleNode = null;
  17823. /**
  17824. * In Sprites, the transparent property is enabled by default.
  17825. *
  17826. * @type {boolean}
  17827. * @default true
  17828. */
  17829. this.transparent = true;
  17830. this.setDefaultValues( _defaultValues$2 );
  17831. this.setValues( parameters );
  17832. }
  17833. /**
  17834. * Setups the position node in view space. This method implements
  17835. * the sprite specific vertex shader.
  17836. *
  17837. * @param {NodeBuilder} builder - The current node builder.
  17838. * @return {Node<vec3>} The position in view space.
  17839. */
  17840. setupPositionView( builder ) {
  17841. const { object, camera } = builder;
  17842. const sizeAttenuation = this.sizeAttenuation;
  17843. const { positionNode, rotationNode, scaleNode } = this;
  17844. const mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  17845. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  17846. if ( scaleNode !== null ) {
  17847. scale = scale.mul( vec2( scaleNode ) );
  17848. }
  17849. if ( sizeAttenuation === false ) {
  17850. if ( camera.isPerspectiveCamera ) {
  17851. scale = scale.mul( mvPosition.z.negate() );
  17852. } else {
  17853. const orthoScale = float( 2.0 ).div( cameraProjectionMatrix.element( 1 ).element( 1 ) );
  17854. scale = scale.mul( orthoScale.mul( 2 ) );
  17855. }
  17856. }
  17857. let alignedPosition = positionGeometry.xy;
  17858. if ( object.center && object.center.isVector2 === true ) {
  17859. const center = reference$1( 'center', 'vec2', object );
  17860. alignedPosition = alignedPosition.sub( center.sub( 0.5 ) );
  17861. }
  17862. alignedPosition = alignedPosition.mul( scale );
  17863. const rotation = float( rotationNode || materialRotation );
  17864. const rotatedPosition = rotate( alignedPosition, rotation );
  17865. return vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  17866. }
  17867. copy( source ) {
  17868. this.positionNode = source.positionNode;
  17869. this.rotationNode = source.rotationNode;
  17870. this.scaleNode = source.scaleNode;
  17871. return super.copy( source );
  17872. }
  17873. /**
  17874. * Whether to use size attenuation or not.
  17875. *
  17876. * @type {boolean}
  17877. * @default true
  17878. */
  17879. get sizeAttenuation() {
  17880. return this._useSizeAttenuation;
  17881. }
  17882. set sizeAttenuation( value ) {
  17883. if ( this._useSizeAttenuation !== value ) {
  17884. this._useSizeAttenuation = value;
  17885. this.needsUpdate = true;
  17886. }
  17887. }
  17888. }
  17889. const _defaultValues$1 = /*@__PURE__*/ new PointsMaterial();
  17890. /**
  17891. * Node material version of {@link PointsMaterial}.
  17892. *
  17893. * @augments SpriteNodeMaterial
  17894. */
  17895. class PointsNodeMaterial extends SpriteNodeMaterial {
  17896. static get type() {
  17897. return 'PointsNodeMaterial';
  17898. }
  17899. /**
  17900. * Constructs a new points node material.
  17901. *
  17902. * @param {Object} [parameters] - The configuration parameter.
  17903. */
  17904. constructor( parameters ) {
  17905. super();
  17906. /**
  17907. * This node property provides an additional way to set the point size.
  17908. *
  17909. * @type {?Node<vec2>}
  17910. * @default null
  17911. */
  17912. this.sizeNode = null;
  17913. /**
  17914. * This flag can be used for type testing.
  17915. *
  17916. * @type {boolean}
  17917. * @readonly
  17918. * @default true
  17919. */
  17920. this.isPointsNodeMaterial = true;
  17921. this.setDefaultValues( _defaultValues$1 );
  17922. this.setValues( parameters );
  17923. }
  17924. setupPositionView() {
  17925. const { positionNode } = this;
  17926. return modelViewMatrix.mul( vec3( positionNode || positionLocal ) ).xyz;
  17927. }
  17928. setupVertex( builder ) {
  17929. const mvp = super.setupVertex( builder );
  17930. // skip further processing if the material is not a node material
  17931. if ( builder.material.isNodeMaterial !== true ) {
  17932. return mvp;
  17933. }
  17934. // ndc space
  17935. const { rotationNode, scaleNode, sizeNode } = this;
  17936. const alignedPosition = positionGeometry.xy.toVar();
  17937. const aspect = viewport.z.div( viewport.w );
  17938. // rotation
  17939. if ( rotationNode && rotationNode.isNode ) {
  17940. const rotation = float( rotationNode );
  17941. alignedPosition.assign( rotate( alignedPosition, rotation ) );
  17942. }
  17943. // point size
  17944. let pointSize = sizeNode !== null ? vec2( sizeNode ) : materialPointSize;
  17945. if ( this.sizeAttenuation === true ) {
  17946. pointSize = pointSize.mul( pointSize.div( positionView.z.negate() ) );
  17947. }
  17948. // scale
  17949. if ( scaleNode && scaleNode.isNode ) {
  17950. pointSize = pointSize.mul( vec2( scaleNode ) );
  17951. }
  17952. alignedPosition.mulAssign( pointSize.mul( 2 ) );
  17953. alignedPosition.assign( alignedPosition.div( viewport.z ) );
  17954. alignedPosition.y.assign( alignedPosition.y.mul( aspect ) );
  17955. // back to clip space
  17956. alignedPosition.assign( alignedPosition.mul( mvp.w ) );
  17957. //clipPos.xy += offset;
  17958. mvp.addAssign( vec4( alignedPosition, 0, 0 ) );
  17959. return mvp;
  17960. }
  17961. /**
  17962. * Whether alpha to coverage should be used or not.
  17963. *
  17964. * @type {boolean}
  17965. * @default true
  17966. */
  17967. get alphaToCoverage() {
  17968. return this._useAlphaToCoverage;
  17969. }
  17970. set alphaToCoverage( value ) {
  17971. if ( this._useAlphaToCoverage !== value ) {
  17972. this._useAlphaToCoverage = value;
  17973. this.needsUpdate = true;
  17974. }
  17975. }
  17976. }
  17977. /**
  17978. * Represents lighting model for a shadow material. Used in {@link ShadowNodeMaterial}.
  17979. *
  17980. * @augments LightingModel
  17981. */
  17982. class ShadowMaskModel extends LightingModel {
  17983. /**
  17984. * Constructs a new shadow mask model.
  17985. */
  17986. constructor() {
  17987. super();
  17988. /**
  17989. * The shadow mask node.
  17990. *
  17991. * @type {Node}
  17992. */
  17993. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  17994. }
  17995. /**
  17996. * Only used to save the shadow mask.
  17997. *
  17998. * @param {Object} input - The input data.
  17999. */
  18000. direct( { lightNode } ) {
  18001. if ( lightNode.shadowNode !== null ) {
  18002. this.shadowNode.mulAssign( lightNode.shadowNode );
  18003. }
  18004. }
  18005. /**
  18006. * Uses the shadow mask to produce the final color.
  18007. *
  18008. * @param {NodeBuilder} builder - The current node builder.
  18009. */
  18010. finish( { context } ) {
  18011. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  18012. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  18013. }
  18014. }
  18015. const _defaultValues = /*@__PURE__*/ new ShadowMaterial();
  18016. /**
  18017. * Node material version of {@link ShadowMaterial}.
  18018. *
  18019. * @augments NodeMaterial
  18020. */
  18021. class ShadowNodeMaterial extends NodeMaterial {
  18022. static get type() {
  18023. return 'ShadowNodeMaterial';
  18024. }
  18025. /**
  18026. * Constructs a new shadow node material.
  18027. *
  18028. * @param {Object} [parameters] - The configuration parameter.
  18029. */
  18030. constructor( parameters ) {
  18031. super();
  18032. /**
  18033. * This flag can be used for type testing.
  18034. *
  18035. * @type {boolean}
  18036. * @readonly
  18037. * @default true
  18038. */
  18039. this.isShadowNodeMaterial = true;
  18040. /**
  18041. * Set to `true` because so it's possible to implement
  18042. * the shadow mask effect.
  18043. *
  18044. * @type {boolean}
  18045. * @default true
  18046. */
  18047. this.lights = true;
  18048. /**
  18049. * Overwritten since shadow materials are transparent
  18050. * by default.
  18051. *
  18052. * @type {boolean}
  18053. * @default true
  18054. */
  18055. this.transparent = true;
  18056. this.setDefaultValues( _defaultValues );
  18057. this.setValues( parameters );
  18058. }
  18059. /**
  18060. * Setups the lighting model.
  18061. *
  18062. * @return {ShadowMaskModel} The lighting model.
  18063. */
  18064. setupLightingModel( /*builder*/ ) {
  18065. return new ShadowMaskModel();
  18066. }
  18067. }
  18068. const scatteringDensity = property( 'vec3' );
  18069. const linearDepthRay = property( 'vec3' );
  18070. const outgoingRayLight = property( 'vec3' );
  18071. /**
  18072. * VolumetricLightingModel class extends the LightingModel to implement volumetric lighting effects.
  18073. * This model calculates the scattering and transmittance of light through a volumetric medium.
  18074. * It dynamically adjusts the direction of the ray based on the camera and object positions.
  18075. * The model supports custom scattering and depth nodes to enhance the lighting effects.
  18076. *
  18077. * @augments LightingModel
  18078. */
  18079. class VolumetricLightingModel extends LightingModel {
  18080. constructor() {
  18081. super();
  18082. }
  18083. start( builder ) {
  18084. const { material, context } = builder;
  18085. const startPos = property( 'vec3' );
  18086. const endPos = property( 'vec3' );
  18087. // This approach dynamically changes the direction of the ray,
  18088. // 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.
  18089. If( cameraPosition.sub( positionWorld ).length().greaterThan( modelRadius.mul( 2 ) ), () => {
  18090. startPos.assign( cameraPosition );
  18091. endPos.assign( positionWorld );
  18092. } ).Else( () => {
  18093. startPos.assign( positionWorld );
  18094. endPos.assign( cameraPosition );
  18095. } );
  18096. //
  18097. const viewVector = endPos.sub( startPos );
  18098. const steps = uniform( 'int' ).onRenderUpdate( ( { material } ) => material.steps );
  18099. const stepSize = viewVector.length().div( steps ).toVar();
  18100. const rayDir = viewVector.normalize().toVar(); // TODO: toVar() should be automatic here ( in loop )
  18101. const distTravelled = float( 0.0 ).toVar();
  18102. const transmittance = vec3( 1 ).toVar();
  18103. if ( material.offsetNode ) {
  18104. // reduce banding
  18105. distTravelled.addAssign( material.offsetNode.mul( stepSize ) );
  18106. }
  18107. Loop( steps, () => {
  18108. const positionRay = startPos.add( rayDir.mul( distTravelled ) );
  18109. const positionViewRay = cameraViewMatrix.mul( vec4( positionRay, 1 ) ).xyz;
  18110. if ( material.depthNode !== null ) {
  18111. linearDepthRay.assign( linearDepth( viewZToPerspectiveDepth( positionViewRay.z, cameraNear, cameraFar ) ) );
  18112. context.sceneDepthNode = linearDepth( material.depthNode ).toVar();
  18113. }
  18114. context.positionWorld = positionRay;
  18115. context.shadowPositionWorld = positionRay;
  18116. context.positionView = positionViewRay;
  18117. scatteringDensity.assign( 0 );
  18118. let scatteringNode;
  18119. if ( material.scatteringNode ) {
  18120. scatteringNode = material.scatteringNode( {
  18121. positionRay
  18122. } );
  18123. }
  18124. super.start( builder );
  18125. if ( scatteringNode ) {
  18126. scatteringDensity.mulAssign( scatteringNode );
  18127. }
  18128. // beer's law
  18129. const falloff = scatteringDensity.mul( .01 ).negate().mul( stepSize ).exp();
  18130. transmittance.mulAssign( falloff );
  18131. // move along the ray
  18132. distTravelled.addAssign( stepSize );
  18133. } );
  18134. outgoingRayLight.addAssign( transmittance.saturate().oneMinus() );
  18135. }
  18136. scatteringLight( lightColor, builder ) {
  18137. const sceneDepthNode = builder.context.sceneDepthNode;
  18138. if ( sceneDepthNode ) {
  18139. If( sceneDepthNode.greaterThanEqual( linearDepthRay ), () => {
  18140. scatteringDensity.addAssign( lightColor );
  18141. } );
  18142. } else {
  18143. scatteringDensity.addAssign( lightColor );
  18144. }
  18145. }
  18146. direct( { lightNode, lightColor }, builder ) {
  18147. // Ignore lights with infinite distance
  18148. if ( lightNode.light.distance === undefined ) return;
  18149. // TODO: We need a viewportOpaque*() ( output, depth ) to fit with modern rendering approaches
  18150. const directLight = lightColor.xyz.toVar();
  18151. directLight.mulAssign( lightNode.shadowNode ); // it no should be necessary if used in the same render pass
  18152. this.scatteringLight( directLight, builder );
  18153. }
  18154. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight }, builder ) {
  18155. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  18156. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  18157. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  18158. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  18159. const P = builder.context.positionView;
  18160. const directLight = lightColor.xyz.mul( LTC_Evaluate_Volume( { P, p0, p1, p2, p3 } ) ).pow( 1.5 );
  18161. this.scatteringLight( directLight, builder );
  18162. }
  18163. finish( builder ) {
  18164. builder.context.outgoingLight.assign( outgoingRayLight );
  18165. }
  18166. }
  18167. /**
  18168. * Volume node material.
  18169. *
  18170. * @augments NodeMaterial
  18171. */
  18172. class VolumeNodeMaterial extends NodeMaterial {
  18173. static get type() {
  18174. return 'VolumeNodeMaterial';
  18175. }
  18176. /**
  18177. * Constructs a new volume node material.
  18178. *
  18179. * @param {Object} [parameters] - The configuration parameter.
  18180. */
  18181. constructor( parameters ) {
  18182. super();
  18183. /**
  18184. * This flag can be used for type testing.
  18185. *
  18186. * @type {boolean}
  18187. * @readonly
  18188. * @default true
  18189. */
  18190. this.isVolumeNodeMaterial = true;
  18191. /**
  18192. * Number of steps used for raymarching.
  18193. *
  18194. * @type {number}
  18195. * @default 25
  18196. */
  18197. this.steps = 25;
  18198. /**
  18199. * Offsets the distance a ray has been traveled through a volume.
  18200. * Can be used to implement dithering to reduce banding.
  18201. *
  18202. * @type {Node<float>}
  18203. * @default null
  18204. */
  18205. this.offsetNode = null;
  18206. /**
  18207. * Node used for scattering calculations.
  18208. *
  18209. * @type {Function|FunctionNode<vec4>}
  18210. * @default null
  18211. */
  18212. this.scatteringNode = null;
  18213. this.lights = true;
  18214. this.transparent = true;
  18215. this.side = BackSide;
  18216. this.depthTest = false;
  18217. this.depthWrite = false;
  18218. this.setValues( parameters );
  18219. }
  18220. setupLightingModel() {
  18221. return new VolumetricLightingModel();
  18222. }
  18223. }
  18224. /**
  18225. * This module manages the internal animation loop of the renderer.
  18226. *
  18227. * @private
  18228. */
  18229. class Animation {
  18230. /**
  18231. * Constructs a new animation loop management component.
  18232. *
  18233. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  18234. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  18235. */
  18236. constructor( nodes, info ) {
  18237. /**
  18238. * Renderer component for managing nodes related logic.
  18239. *
  18240. * @type {Nodes}
  18241. */
  18242. this.nodes = nodes;
  18243. /**
  18244. * Renderer component for managing metrics and monitoring data.
  18245. *
  18246. * @type {Info}
  18247. */
  18248. this.info = info;
  18249. /**
  18250. * A reference to the context from `requestAnimationFrame()` can
  18251. * be called (usually `window`).
  18252. *
  18253. * @type {?(Window|XRSession)}
  18254. */
  18255. this._context = typeof self !== 'undefined' ? self : null;
  18256. /**
  18257. * The user-defined animation loop.
  18258. *
  18259. * @type {?Function}
  18260. * @default null
  18261. */
  18262. this._animationLoop = null;
  18263. /**
  18264. * The requestId which is returned from the `requestAnimationFrame()` call.
  18265. * Can be used to cancel the stop the animation loop.
  18266. *
  18267. * @type {?number}
  18268. * @default null
  18269. */
  18270. this._requestId = null;
  18271. }
  18272. /**
  18273. * Starts the internal animation loop.
  18274. */
  18275. start() {
  18276. const update = ( time, xrFrame ) => {
  18277. this._requestId = this._context.requestAnimationFrame( update );
  18278. if ( this.info.autoReset === true ) this.info.reset();
  18279. this.nodes.nodeFrame.update();
  18280. this.info.frame = this.nodes.nodeFrame.frameId;
  18281. if ( this._animationLoop !== null ) this._animationLoop( time, xrFrame );
  18282. };
  18283. update();
  18284. }
  18285. /**
  18286. * Stops the internal animation loop.
  18287. */
  18288. stop() {
  18289. this._context.cancelAnimationFrame( this._requestId );
  18290. this._requestId = null;
  18291. }
  18292. /**
  18293. * Returns the user-level animation loop.
  18294. *
  18295. * @return {?Function} The animation loop.
  18296. */
  18297. getAnimationLoop() {
  18298. return this._animationLoop;
  18299. }
  18300. /**
  18301. * Defines the user-level animation loop.
  18302. *
  18303. * @param {?Function} callback - The animation loop.
  18304. */
  18305. setAnimationLoop( callback ) {
  18306. this._animationLoop = callback;
  18307. }
  18308. /**
  18309. * Returns the animation context.
  18310. *
  18311. * @return {Window|XRSession} The animation context.
  18312. */
  18313. getContext() {
  18314. return this._context;
  18315. }
  18316. /**
  18317. * Defines the context in which `requestAnimationFrame()` is executed.
  18318. *
  18319. * @param {Window|XRSession} context - The context to set.
  18320. */
  18321. setContext( context ) {
  18322. this._context = context;
  18323. }
  18324. /**
  18325. * Frees all internal resources and stops the animation loop.
  18326. */
  18327. dispose() {
  18328. this.stop();
  18329. }
  18330. }
  18331. /**
  18332. * Data structure for the renderer. It allows defining values
  18333. * with chained, hierarchical keys. Keys are meant to be
  18334. * objects since the module internally works with Weak Maps
  18335. * for performance reasons.
  18336. *
  18337. * @private
  18338. */
  18339. class ChainMap {
  18340. /**
  18341. * Constructs a new Chain Map.
  18342. */
  18343. constructor() {
  18344. /**
  18345. * The root Weak Map.
  18346. *
  18347. * @type {WeakMap}
  18348. */
  18349. this.weakMap = new WeakMap();
  18350. }
  18351. /**
  18352. * Returns the value for the given array of keys.
  18353. *
  18354. * @param {Array<Object>} keys - List of keys.
  18355. * @return {any} The value. Returns `undefined` if no value was found.
  18356. */
  18357. get( keys ) {
  18358. let map = this.weakMap;
  18359. for ( let i = 0; i < keys.length - 1; i ++ ) {
  18360. map = map.get( keys[ i ] );
  18361. if ( map === undefined ) return undefined;
  18362. }
  18363. return map.get( keys[ keys.length - 1 ] );
  18364. }
  18365. /**
  18366. * Sets the value for the given keys.
  18367. *
  18368. * @param {Array<Object>} keys - List of keys.
  18369. * @param {any} value - The value to set.
  18370. * @return {ChainMap} A reference to this Chain Map.
  18371. */
  18372. set( keys, value ) {
  18373. let map = this.weakMap;
  18374. for ( let i = 0; i < keys.length - 1; i ++ ) {
  18375. const key = keys[ i ];
  18376. if ( map.has( key ) === false ) map.set( key, new WeakMap() );
  18377. map = map.get( key );
  18378. }
  18379. map.set( keys[ keys.length - 1 ], value );
  18380. return this;
  18381. }
  18382. /**
  18383. * Deletes a value for the given keys.
  18384. *
  18385. * @param {Array<Object>} keys - The keys.
  18386. * @return {boolean} Returns `true` if the value has been removed successfully and `false` if the value has not be found.
  18387. */
  18388. delete( keys ) {
  18389. let map = this.weakMap;
  18390. for ( let i = 0; i < keys.length - 1; i ++ ) {
  18391. map = map.get( keys[ i ] );
  18392. if ( map === undefined ) return false;
  18393. }
  18394. return map.delete( keys[ keys.length - 1 ] );
  18395. }
  18396. }
  18397. let _id$9 = 0;
  18398. function getKeys( obj ) {
  18399. const keys = Object.keys( obj );
  18400. let proto = Object.getPrototypeOf( obj );
  18401. while ( proto ) {
  18402. const descriptors = Object.getOwnPropertyDescriptors( proto );
  18403. for ( const key in descriptors ) {
  18404. if ( descriptors[ key ] !== undefined ) {
  18405. const descriptor = descriptors[ key ];
  18406. if ( descriptor && typeof descriptor.get === 'function' ) {
  18407. keys.push( key );
  18408. }
  18409. }
  18410. }
  18411. proto = Object.getPrototypeOf( proto );
  18412. }
  18413. return keys;
  18414. }
  18415. /**
  18416. * A render object is the renderer's representation of single entity that gets drawn
  18417. * with a draw command. There is no unique mapping of render objects to 3D objects in the
  18418. * scene since render objects also depend from the used material, the current render context
  18419. * and the current scene's lighting.
  18420. *
  18421. * In general, the basic process of the renderer is:
  18422. *
  18423. * - Analyze the 3D objects in the scene and generate render lists containing render items.
  18424. * - Process the render lists by calling one or more render commands for each render item.
  18425. * - For each render command, request a render object and perform the draw.
  18426. *
  18427. * The module provides an interface to get data required for the draw command like the actual
  18428. * draw parameters or vertex buffers. It also holds a series of caching related methods since
  18429. * creating render objects should only be done when necessary.
  18430. *
  18431. * @private
  18432. */
  18433. class RenderObject {
  18434. /**
  18435. * Constructs a new render object.
  18436. *
  18437. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  18438. * @param {Geometries} geometries - Renderer component for managing geometries.
  18439. * @param {Renderer} renderer - The renderer.
  18440. * @param {Object3D} object - The 3D object.
  18441. * @param {Material} material - The 3D object's material.
  18442. * @param {Scene} scene - The scene the 3D object belongs to.
  18443. * @param {Camera} camera - The camera the object should be rendered with.
  18444. * @param {LightsNode} lightsNode - The lights node.
  18445. * @param {RenderContext} renderContext - The render context.
  18446. * @param {ClippingContext} clippingContext - The clipping context.
  18447. */
  18448. constructor( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext ) {
  18449. this.id = _id$9 ++;
  18450. /**
  18451. * Renderer component for managing nodes related logic.
  18452. *
  18453. * @type {Nodes}
  18454. * @private
  18455. */
  18456. this._nodes = nodes;
  18457. /**
  18458. * Renderer component for managing geometries.
  18459. *
  18460. * @type {Geometries}
  18461. * @private
  18462. */
  18463. this._geometries = geometries;
  18464. /**
  18465. * The renderer.
  18466. *
  18467. * @type {Renderer}
  18468. */
  18469. this.renderer = renderer;
  18470. /**
  18471. * The 3D object.
  18472. *
  18473. * @type {Object3D}
  18474. */
  18475. this.object = object;
  18476. /**
  18477. * The 3D object's material.
  18478. *
  18479. * @type {Material}
  18480. */
  18481. this.material = material;
  18482. /**
  18483. * The scene the 3D object belongs to.
  18484. *
  18485. * @type {Scene}
  18486. */
  18487. this.scene = scene;
  18488. /**
  18489. * The camera the 3D object should be rendered with.
  18490. *
  18491. * @type {Camera}
  18492. */
  18493. this.camera = camera;
  18494. /**
  18495. * The lights node.
  18496. *
  18497. * @type {LightsNode}
  18498. */
  18499. this.lightsNode = lightsNode;
  18500. /**
  18501. * The render context.
  18502. *
  18503. * @type {RenderContext}
  18504. */
  18505. this.context = renderContext;
  18506. /**
  18507. * The 3D object's geometry.
  18508. *
  18509. * @type {BufferGeometry}
  18510. */
  18511. this.geometry = object.geometry;
  18512. /**
  18513. * The render object's version.
  18514. *
  18515. * @type {number}
  18516. */
  18517. this.version = material.version;
  18518. /**
  18519. * The draw range of the geometry.
  18520. *
  18521. * @type {?Object}
  18522. * @default null
  18523. */
  18524. this.drawRange = null;
  18525. /**
  18526. * An array holding the buffer attributes
  18527. * of the render object. This entails attribute
  18528. * definitions on geometry and node level.
  18529. *
  18530. * @type {?Array<BufferAttribute>}
  18531. * @default null
  18532. */
  18533. this.attributes = null;
  18534. /**
  18535. * A reference to a render pipeline the render
  18536. * object is processed with.
  18537. *
  18538. * @type {RenderPipeline}
  18539. * @default null
  18540. */
  18541. this.pipeline = null;
  18542. /**
  18543. * Only relevant for objects using
  18544. * multiple materials. This represents a group entry
  18545. * from the respective `BufferGeometry`.
  18546. *
  18547. * @type {?{start: number, count: number}}
  18548. * @default null
  18549. */
  18550. this.group = null;
  18551. /**
  18552. * An array holding the vertex buffers which can
  18553. * be buffer attributes but also interleaved buffers.
  18554. *
  18555. * @type {?Array<BufferAttribute|InterleavedBuffer>}
  18556. * @default null
  18557. */
  18558. this.vertexBuffers = null;
  18559. /**
  18560. * The parameters for the draw command.
  18561. *
  18562. * @type {?Object}
  18563. * @default null
  18564. */
  18565. this.drawParams = null;
  18566. /**
  18567. * If this render object is used inside a render bundle,
  18568. * this property points to the respective bundle group.
  18569. *
  18570. * @type {?BundleGroup}
  18571. * @default null
  18572. */
  18573. this.bundle = null;
  18574. /**
  18575. * The clipping context.
  18576. *
  18577. * @type {ClippingContext}
  18578. */
  18579. this.clippingContext = clippingContext;
  18580. /**
  18581. * The clipping context's cache key.
  18582. *
  18583. * @type {string}
  18584. */
  18585. this.clippingContextCacheKey = clippingContext !== null ? clippingContext.cacheKey : '';
  18586. /**
  18587. * The initial node cache key.
  18588. *
  18589. * @type {number}
  18590. */
  18591. this.initialNodesCacheKey = this.getDynamicCacheKey();
  18592. /**
  18593. * The initial cache key.
  18594. *
  18595. * @type {number}
  18596. */
  18597. this.initialCacheKey = this.getCacheKey();
  18598. /**
  18599. * The node builder state.
  18600. *
  18601. * @type {?NodeBuilderState}
  18602. * @private
  18603. * @default null
  18604. */
  18605. this._nodeBuilderState = null;
  18606. /**
  18607. * An array of bindings.
  18608. *
  18609. * @type {?Array<BindGroup>}
  18610. * @private
  18611. * @default null
  18612. */
  18613. this._bindings = null;
  18614. /**
  18615. * Reference to the node material observer.
  18616. *
  18617. * @type {?NodeMaterialObserver}
  18618. * @private
  18619. * @default null
  18620. */
  18621. this._monitor = null;
  18622. /**
  18623. * An event listener which is defined by `RenderObjects`. It performs
  18624. * clean up tasks when `dispose()` on this render object.
  18625. *
  18626. * @method
  18627. */
  18628. this.onDispose = null;
  18629. /**
  18630. * This flag can be used for type testing.
  18631. *
  18632. * @type {boolean}
  18633. * @readonly
  18634. * @default true
  18635. */
  18636. this.isRenderObject = true;
  18637. /**
  18638. * An event listener which is executed when `dispose()` is called on
  18639. * the render object's material.
  18640. *
  18641. * @method
  18642. */
  18643. this.onMaterialDispose = () => {
  18644. this.dispose();
  18645. };
  18646. this.material.addEventListener( 'dispose', this.onMaterialDispose );
  18647. }
  18648. /**
  18649. * Updates the clipping context.
  18650. *
  18651. * @param {ClippingContext} context - The clipping context to set.
  18652. */
  18653. updateClipping( context ) {
  18654. this.clippingContext = context;
  18655. }
  18656. /**
  18657. * Whether the clipping requires an update or not.
  18658. *
  18659. * @type {boolean}
  18660. * @readonly
  18661. */
  18662. get clippingNeedsUpdate() {
  18663. if ( this.clippingContext === null || this.clippingContext.cacheKey === this.clippingContextCacheKey ) return false;
  18664. this.clippingContextCacheKey = this.clippingContext.cacheKey;
  18665. return true;
  18666. }
  18667. /**
  18668. * The number of clipping planes defined in context of hardware clipping.
  18669. *
  18670. * @type {number}
  18671. * @readonly
  18672. */
  18673. get hardwareClippingPlanes() {
  18674. return this.material.hardwareClipping === true ? this.clippingContext.unionClippingCount : 0;
  18675. }
  18676. /**
  18677. * Returns the node builder state of this render object.
  18678. *
  18679. * @return {NodeBuilderState} The node builder state.
  18680. */
  18681. getNodeBuilderState() {
  18682. return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) );
  18683. }
  18684. /**
  18685. * Returns the node material observer of this render object.
  18686. *
  18687. * @return {NodeMaterialObserver} The node material observer.
  18688. */
  18689. getMonitor() {
  18690. return this._monitor || ( this._monitor = this.getNodeBuilderState().observer );
  18691. }
  18692. /**
  18693. * Returns an array of bind groups of this render object.
  18694. *
  18695. * @return {Array<BindGroup>} The bindings.
  18696. */
  18697. getBindings() {
  18698. return this._bindings || ( this._bindings = this.getNodeBuilderState().createBindings() );
  18699. }
  18700. /**
  18701. * Returns a binding group by group name of this render object.
  18702. *
  18703. * @param {string} name - The name of the binding group.
  18704. * @return {?BindGroup} The bindings.
  18705. */
  18706. getBindingGroup( name ) {
  18707. for ( const bindingGroup of this.getBindings() ) {
  18708. if ( bindingGroup.name === name ) {
  18709. return bindingGroup;
  18710. }
  18711. }
  18712. }
  18713. /**
  18714. * Returns the index of the render object's geometry.
  18715. *
  18716. * @return {?BufferAttribute} The index. Returns `null` for non-indexed geometries.
  18717. */
  18718. getIndex() {
  18719. return this._geometries.getIndex( this );
  18720. }
  18721. /**
  18722. * Returns the indirect buffer attribute.
  18723. *
  18724. * @return {?BufferAttribute} The indirect attribute. `null` if no indirect drawing is used.
  18725. */
  18726. getIndirect() {
  18727. return this._geometries.getIndirect( this );
  18728. }
  18729. /**
  18730. * Returns an array that acts as a key for identifying the render object in a chain map.
  18731. *
  18732. * @return {Array<Object>} An array with object references.
  18733. */
  18734. getChainArray() {
  18735. return [ this.object, this.material, this.context, this.lightsNode ];
  18736. }
  18737. /**
  18738. * This method is used when the geometry of a 3D object has been exchanged and the
  18739. * respective render object now requires an update.
  18740. *
  18741. * @param {BufferGeometry} geometry - The geometry to set.
  18742. */
  18743. setGeometry( geometry ) {
  18744. this.geometry = geometry;
  18745. this.attributes = null;
  18746. }
  18747. /**
  18748. * Returns the buffer attributes of the render object. The returned array holds
  18749. * attribute definitions on geometry and node level.
  18750. *
  18751. * @return {Array<BufferAttribute>} An array with buffer attributes.
  18752. */
  18753. getAttributes() {
  18754. if ( this.attributes !== null ) return this.attributes;
  18755. const nodeAttributes = this.getNodeBuilderState().nodeAttributes;
  18756. const geometry = this.geometry;
  18757. const attributes = [];
  18758. const vertexBuffers = new Set();
  18759. for ( const nodeAttribute of nodeAttributes ) {
  18760. const attribute = nodeAttribute.node && nodeAttribute.node.attribute ? nodeAttribute.node.attribute : geometry.getAttribute( nodeAttribute.name );
  18761. if ( attribute === undefined ) continue;
  18762. attributes.push( attribute );
  18763. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  18764. vertexBuffers.add( bufferAttribute );
  18765. }
  18766. this.attributes = attributes;
  18767. this.vertexBuffers = Array.from( vertexBuffers.values() );
  18768. return attributes;
  18769. }
  18770. /**
  18771. * Returns the vertex buffers of the render object.
  18772. *
  18773. * @return {Array<BufferAttribute|InterleavedBuffer>} An array with buffer attribute or interleaved buffers.
  18774. */
  18775. getVertexBuffers() {
  18776. if ( this.vertexBuffers === null ) this.getAttributes();
  18777. return this.vertexBuffers;
  18778. }
  18779. /**
  18780. * Returns the draw parameters for the render object.
  18781. *
  18782. * @return {?{vertexCount: number, firstVertex: number, instanceCount: number, firstInstance: number}} The draw parameters.
  18783. */
  18784. getDrawParameters() {
  18785. const { object, material, geometry, group, drawRange } = this;
  18786. const drawParams = this.drawParams || ( this.drawParams = {
  18787. vertexCount: 0,
  18788. firstVertex: 0,
  18789. instanceCount: 0,
  18790. firstInstance: 0
  18791. } );
  18792. const index = this.getIndex();
  18793. const hasIndex = ( index !== null );
  18794. let instanceCount = 1;
  18795. if ( geometry.isInstancedBufferGeometry === true ) {
  18796. instanceCount = geometry.instanceCount;
  18797. } else if ( object.count !== undefined ) {
  18798. instanceCount = Math.max( 0, object.count );
  18799. }
  18800. if ( instanceCount === 0 ) return null;
  18801. drawParams.instanceCount = instanceCount;
  18802. if ( object.isBatchedMesh === true ) return drawParams;
  18803. let rangeFactor = 1;
  18804. if ( material.wireframe === true && ! object.isPoints && ! object.isLineSegments && ! object.isLine && ! object.isLineLoop ) {
  18805. rangeFactor = 2;
  18806. }
  18807. let firstVertex = drawRange.start * rangeFactor;
  18808. let lastVertex = ( drawRange.start + drawRange.count ) * rangeFactor;
  18809. if ( group !== null ) {
  18810. firstVertex = Math.max( firstVertex, group.start * rangeFactor );
  18811. lastVertex = Math.min( lastVertex, ( group.start + group.count ) * rangeFactor );
  18812. }
  18813. const position = geometry.attributes.position;
  18814. let itemCount = Infinity;
  18815. if ( hasIndex ) {
  18816. itemCount = index.count;
  18817. } else if ( position !== undefined && position !== null ) {
  18818. itemCount = position.count;
  18819. }
  18820. firstVertex = Math.max( firstVertex, 0 );
  18821. lastVertex = Math.min( lastVertex, itemCount );
  18822. const count = lastVertex - firstVertex;
  18823. if ( count < 0 || count === Infinity ) return null;
  18824. drawParams.vertexCount = count;
  18825. drawParams.firstVertex = firstVertex;
  18826. return drawParams;
  18827. }
  18828. /**
  18829. * Returns the render object's geometry cache key.
  18830. *
  18831. * The geometry cache key is part of the material cache key.
  18832. *
  18833. * @return {string} The geometry cache key.
  18834. */
  18835. getGeometryCacheKey() {
  18836. const { geometry } = this;
  18837. let cacheKey = '';
  18838. for ( const name of Object.keys( geometry.attributes ).sort() ) {
  18839. const attribute = geometry.attributes[ name ];
  18840. cacheKey += name + ',';
  18841. if ( attribute.data ) cacheKey += attribute.data.stride + ',';
  18842. if ( attribute.offset ) cacheKey += attribute.offset + ',';
  18843. if ( attribute.itemSize ) cacheKey += attribute.itemSize + ',';
  18844. if ( attribute.normalized ) cacheKey += 'n,';
  18845. }
  18846. // structural equality isn't sufficient for morph targets since the
  18847. // data are maintained in textures. only if the targets are all equal
  18848. // the texture and thus the instance of `MorphNode` can be shared.
  18849. for ( const name of Object.keys( geometry.morphAttributes ).sort() ) {
  18850. const targets = geometry.morphAttributes[ name ];
  18851. cacheKey += 'morph-' + name + ',';
  18852. for ( let i = 0, l = targets.length; i < l; i ++ ) {
  18853. const attribute = targets[ i ];
  18854. cacheKey += attribute.id + ',';
  18855. }
  18856. }
  18857. if ( geometry.index ) {
  18858. cacheKey += 'index,';
  18859. }
  18860. return cacheKey;
  18861. }
  18862. /**
  18863. * Returns the render object's material cache key.
  18864. *
  18865. * The material cache key is part of the render object cache key.
  18866. *
  18867. * @return {number} The material cache key.
  18868. */
  18869. getMaterialCacheKey() {
  18870. const { object, material } = this;
  18871. let cacheKey = material.customProgramCacheKey();
  18872. for ( const property of getKeys( material ) ) {
  18873. if ( /^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test( property ) ) continue;
  18874. const value = material[ property ];
  18875. let valueKey;
  18876. if ( value !== null ) {
  18877. // some material values require a formatting
  18878. const type = typeof value;
  18879. if ( type === 'number' ) {
  18880. valueKey = value !== 0 ? '1' : '0'; // Convert to on/off, important for clearcoat, transmission, etc
  18881. } else if ( type === 'object' ) {
  18882. valueKey = '{';
  18883. if ( value.isTexture ) {
  18884. valueKey += value.mapping;
  18885. }
  18886. valueKey += '}';
  18887. } else {
  18888. valueKey = String( value );
  18889. }
  18890. } else {
  18891. valueKey = String( value );
  18892. }
  18893. cacheKey += /*property + ':' +*/ valueKey + ',';
  18894. }
  18895. cacheKey += this.clippingContextCacheKey + ',';
  18896. if ( object.geometry ) {
  18897. cacheKey += this.getGeometryCacheKey();
  18898. }
  18899. if ( object.skeleton ) {
  18900. cacheKey += object.skeleton.bones.length + ',';
  18901. }
  18902. if ( object.isBatchedMesh ) {
  18903. cacheKey += object._matricesTexture.uuid + ',';
  18904. if ( object._colorsTexture !== null ) {
  18905. cacheKey += object._colorsTexture.uuid + ',';
  18906. }
  18907. }
  18908. if ( object.count > 1 ) {
  18909. // TODO: https://github.com/mrdoob/three.js/pull/29066#issuecomment-2269400850
  18910. cacheKey += object.uuid + ',';
  18911. }
  18912. cacheKey += object.receiveShadow + ',';
  18913. return hashString( cacheKey );
  18914. }
  18915. /**
  18916. * Whether the geometry requires an update or not.
  18917. *
  18918. * @type {boolean}
  18919. * @readonly
  18920. */
  18921. get needsGeometryUpdate() {
  18922. return this.geometry.id !== this.object.geometry.id;
  18923. }
  18924. /**
  18925. * Whether the render object requires an update or not.
  18926. *
  18927. * Note: There are two distinct places where render objects are checked for an update.
  18928. *
  18929. * 1. In `RenderObjects.get()` which is executed when the render object is request. This
  18930. * method checks the `needsUpdate` flag and recreates the render object if necessary.
  18931. * 2. In `Renderer._renderObjectDirect()` right after getting the render object via
  18932. * `RenderObjects.get()`. The render object's NodeMaterialObserver is then used to detect
  18933. * a need for a refresh due to material, geometry or object related value changes.
  18934. *
  18935. * TODO: Investigate if it's possible to merge both steps so there is only a single place
  18936. * that performs the 'needsUpdate' check.
  18937. *
  18938. * @type {boolean}
  18939. * @readonly
  18940. */
  18941. get needsUpdate() {
  18942. return /*this.object.static !== true &&*/ ( this.initialNodesCacheKey !== this.getDynamicCacheKey() || this.clippingNeedsUpdate );
  18943. }
  18944. /**
  18945. * Returns the dynamic cache key which represents a key that is computed per draw command.
  18946. *
  18947. * @return {number} The cache key.
  18948. */
  18949. getDynamicCacheKey() {
  18950. let cacheKey = 0;
  18951. // `Nodes.getCacheKey()` returns an environment cache key which is not relevant when
  18952. // the renderer is inside a shadow pass.
  18953. if ( this.material.isShadowPassMaterial !== true ) {
  18954. cacheKey = this._nodes.getCacheKey( this.scene, this.lightsNode );
  18955. }
  18956. if ( this.camera.isArrayCamera ) {
  18957. cacheKey = hash$1( cacheKey, this.camera.cameras.length );
  18958. }
  18959. if ( this.object.receiveShadow ) {
  18960. cacheKey = hash$1( cacheKey, 1 );
  18961. }
  18962. return cacheKey;
  18963. }
  18964. /**
  18965. * Returns the render object's cache key.
  18966. *
  18967. * @return {number} The cache key.
  18968. */
  18969. getCacheKey() {
  18970. return this.getMaterialCacheKey() + this.getDynamicCacheKey();
  18971. }
  18972. /**
  18973. * Frees internal resources.
  18974. */
  18975. dispose() {
  18976. this.material.removeEventListener( 'dispose', this.onMaterialDispose );
  18977. this.onDispose();
  18978. }
  18979. }
  18980. const _chainKeys$5 = [];
  18981. /**
  18982. * This module manages the render objects of the renderer.
  18983. *
  18984. * @private
  18985. */
  18986. class RenderObjects {
  18987. /**
  18988. * Constructs a new render object management component.
  18989. *
  18990. * @param {Renderer} renderer - The renderer.
  18991. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  18992. * @param {Geometries} geometries - Renderer component for managing geometries.
  18993. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  18994. * @param {Bindings} bindings - Renderer component for managing bindings.
  18995. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  18996. */
  18997. constructor( renderer, nodes, geometries, pipelines, bindings, info ) {
  18998. /**
  18999. * The renderer.
  19000. *
  19001. * @type {Renderer}
  19002. */
  19003. this.renderer = renderer;
  19004. /**
  19005. * Renderer component for managing nodes related logic.
  19006. *
  19007. * @type {Nodes}
  19008. */
  19009. this.nodes = nodes;
  19010. /**
  19011. * Renderer component for managing geometries.
  19012. *
  19013. * @type {Geometries}
  19014. */
  19015. this.geometries = geometries;
  19016. /**
  19017. * Renderer component for managing pipelines.
  19018. *
  19019. * @type {Pipelines}
  19020. */
  19021. this.pipelines = pipelines;
  19022. /**
  19023. * Renderer component for managing bindings.
  19024. *
  19025. * @type {Bindings}
  19026. */
  19027. this.bindings = bindings;
  19028. /**
  19029. * Renderer component for managing metrics and monitoring data.
  19030. *
  19031. * @type {Info}
  19032. */
  19033. this.info = info;
  19034. /**
  19035. * A dictionary that manages render contexts in chain maps
  19036. * for each pass ID.
  19037. *
  19038. * @type {Object<string,ChainMap>}
  19039. */
  19040. this.chainMaps = {};
  19041. }
  19042. /**
  19043. * Returns a render object for the given object and state data.
  19044. *
  19045. * @param {Object3D} object - The 3D object.
  19046. * @param {Material} material - The 3D object's material.
  19047. * @param {Scene} scene - The scene the 3D object belongs to.
  19048. * @param {Camera} camera - The camera the 3D object should be rendered with.
  19049. * @param {LightsNode} lightsNode - The lights node.
  19050. * @param {RenderContext} renderContext - The render context.
  19051. * @param {ClippingContext} clippingContext - The clipping context.
  19052. * @param {string} [passId] - An optional ID for identifying the pass.
  19053. * @return {RenderObject} The render object.
  19054. */
  19055. get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  19056. const chainMap = this.getChainMap( passId );
  19057. // reuse chainArray
  19058. _chainKeys$5[ 0 ] = object;
  19059. _chainKeys$5[ 1 ] = material;
  19060. _chainKeys$5[ 2 ] = renderContext;
  19061. _chainKeys$5[ 3 ] = lightsNode;
  19062. let renderObject = chainMap.get( _chainKeys$5 );
  19063. if ( renderObject === undefined ) {
  19064. renderObject = this.createRenderObject( this.nodes, this.geometries, this.renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  19065. chainMap.set( _chainKeys$5, renderObject );
  19066. } else {
  19067. renderObject.updateClipping( clippingContext );
  19068. if ( renderObject.needsGeometryUpdate ) {
  19069. renderObject.setGeometry( object.geometry );
  19070. }
  19071. if ( renderObject.version !== material.version || renderObject.needsUpdate ) {
  19072. if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) {
  19073. renderObject.dispose();
  19074. renderObject = this.get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  19075. } else {
  19076. renderObject.version = material.version;
  19077. }
  19078. }
  19079. }
  19080. _chainKeys$5.length = 0;
  19081. return renderObject;
  19082. }
  19083. /**
  19084. * Returns a chain map for the given pass ID.
  19085. *
  19086. * @param {string} [passId='default'] - The pass ID.
  19087. * @return {ChainMap} The chain map.
  19088. */
  19089. getChainMap( passId = 'default' ) {
  19090. return this.chainMaps[ passId ] || ( this.chainMaps[ passId ] = new ChainMap() );
  19091. }
  19092. /**
  19093. * Frees internal resources.
  19094. */
  19095. dispose() {
  19096. this.chainMaps = {};
  19097. }
  19098. /**
  19099. * Factory method for creating render objects with the given list of parameters.
  19100. *
  19101. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  19102. * @param {Geometries} geometries - Renderer component for managing geometries.
  19103. * @param {Renderer} renderer - The renderer.
  19104. * @param {Object3D} object - The 3D object.
  19105. * @param {Material} material - The object's material.
  19106. * @param {Scene} scene - The scene the 3D object belongs to.
  19107. * @param {Camera} camera - The camera the object should be rendered with.
  19108. * @param {LightsNode} lightsNode - The lights node.
  19109. * @param {RenderContext} renderContext - The render context.
  19110. * @param {ClippingContext} clippingContext - The clipping context.
  19111. * @param {string} [passId] - An optional ID for identifying the pass.
  19112. * @return {RenderObject} The render object.
  19113. */
  19114. createRenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  19115. const chainMap = this.getChainMap( passId );
  19116. const renderObject = new RenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext );
  19117. renderObject.onDispose = () => {
  19118. this.pipelines.delete( renderObject );
  19119. this.bindings.delete( renderObject );
  19120. this.nodes.delete( renderObject );
  19121. chainMap.delete( renderObject.getChainArray() );
  19122. };
  19123. return renderObject;
  19124. }
  19125. }
  19126. /**
  19127. * Data structure for the renderer. It is intended to manage
  19128. * data of objects in dictionaries.
  19129. *
  19130. * @private
  19131. */
  19132. class DataMap {
  19133. /**
  19134. * Constructs a new data map.
  19135. */
  19136. constructor() {
  19137. /**
  19138. * `DataMap` internally uses a weak map
  19139. * to manage its data.
  19140. *
  19141. * @type {WeakMap}
  19142. */
  19143. this.data = new WeakMap();
  19144. }
  19145. /**
  19146. * Returns the dictionary for the given object.
  19147. *
  19148. * @param {Object} object - The object.
  19149. * @return {Object} The dictionary.
  19150. */
  19151. get( object ) {
  19152. let map = this.data.get( object );
  19153. if ( map === undefined ) {
  19154. map = {};
  19155. this.data.set( object, map );
  19156. }
  19157. return map;
  19158. }
  19159. /**
  19160. * Deletes the dictionary for the given object.
  19161. *
  19162. * @param {Object} object - The object.
  19163. * @return {?Object} The deleted dictionary.
  19164. */
  19165. delete( object ) {
  19166. let map = null;
  19167. if ( this.data.has( object ) ) {
  19168. map = this.data.get( object );
  19169. this.data.delete( object );
  19170. }
  19171. return map;
  19172. }
  19173. /**
  19174. * Returns `true` if the given object has a dictionary defined.
  19175. *
  19176. * @param {Object} object - The object to test.
  19177. * @return {boolean} Whether a dictionary is defined or not.
  19178. */
  19179. has( object ) {
  19180. return this.data.has( object );
  19181. }
  19182. /**
  19183. * Frees internal resources.
  19184. */
  19185. dispose() {
  19186. this.data = new WeakMap();
  19187. }
  19188. }
  19189. const AttributeType = {
  19190. VERTEX: 1,
  19191. INDEX: 2,
  19192. STORAGE: 3,
  19193. INDIRECT: 4
  19194. };
  19195. // size of a chunk in bytes (STD140 layout)
  19196. const GPU_CHUNK_BYTES = 16;
  19197. // @TODO: Move to src/constants.js
  19198. const BlendColorFactor = 211;
  19199. const OneMinusBlendColorFactor = 212;
  19200. /**
  19201. * This renderer module manages geometry attributes.
  19202. *
  19203. * @private
  19204. * @augments DataMap
  19205. */
  19206. class Attributes extends DataMap {
  19207. /**
  19208. * Constructs a new attribute management component.
  19209. *
  19210. * @param {Backend} backend - The renderer's backend.
  19211. */
  19212. constructor( backend ) {
  19213. super();
  19214. /**
  19215. * The renderer's backend.
  19216. *
  19217. * @type {Backend}
  19218. */
  19219. this.backend = backend;
  19220. }
  19221. /**
  19222. * Deletes the data for the given attribute.
  19223. *
  19224. * @param {BufferAttribute} attribute - The attribute.
  19225. * @return {Object|null} The deleted attribute data.
  19226. */
  19227. delete( attribute ) {
  19228. const attributeData = super.delete( attribute );
  19229. if ( attributeData !== null ) {
  19230. this.backend.destroyAttribute( attribute );
  19231. }
  19232. return attributeData;
  19233. }
  19234. /**
  19235. * Updates the given attribute. This method creates attribute buffers
  19236. * for new attributes and updates data for existing ones.
  19237. *
  19238. * @param {BufferAttribute} attribute - The attribute to update.
  19239. * @param {number} type - The attribute type.
  19240. */
  19241. update( attribute, type ) {
  19242. const data = this.get( attribute );
  19243. if ( data.version === undefined ) {
  19244. if ( type === AttributeType.VERTEX ) {
  19245. this.backend.createAttribute( attribute );
  19246. } else if ( type === AttributeType.INDEX ) {
  19247. this.backend.createIndexAttribute( attribute );
  19248. } else if ( type === AttributeType.STORAGE ) {
  19249. this.backend.createStorageAttribute( attribute );
  19250. } else if ( type === AttributeType.INDIRECT ) {
  19251. this.backend.createIndirectStorageAttribute( attribute );
  19252. }
  19253. data.version = this._getBufferAttribute( attribute ).version;
  19254. } else {
  19255. const bufferAttribute = this._getBufferAttribute( attribute );
  19256. if ( data.version < bufferAttribute.version || bufferAttribute.usage === DynamicDrawUsage ) {
  19257. this.backend.updateAttribute( attribute );
  19258. data.version = bufferAttribute.version;
  19259. }
  19260. }
  19261. }
  19262. /**
  19263. * Utility method for handling interleaved buffer attributes correctly.
  19264. * To process them, their `InterleavedBuffer` is returned.
  19265. *
  19266. * @param {BufferAttribute} attribute - The attribute.
  19267. * @return {BufferAttribute|InterleavedBuffer}
  19268. */
  19269. _getBufferAttribute( attribute ) {
  19270. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  19271. return attribute;
  19272. }
  19273. }
  19274. /**
  19275. * Returns the wireframe version for the given geometry.
  19276. *
  19277. * @private
  19278. * @function
  19279. * @param {BufferGeometry} geometry - The geometry.
  19280. * @return {number} The version.
  19281. */
  19282. function getWireframeVersion( geometry ) {
  19283. return ( geometry.index !== null ) ? geometry.index.version : geometry.attributes.position.version;
  19284. }
  19285. /**
  19286. * Returns a wireframe index attribute for the given geometry.
  19287. *
  19288. * @private
  19289. * @function
  19290. * @param {BufferGeometry} geometry - The geometry.
  19291. * @return {BufferAttribute} The wireframe index attribute.
  19292. */
  19293. function getWireframeIndex( geometry ) {
  19294. const indices = [];
  19295. const geometryIndex = geometry.index;
  19296. const geometryPosition = geometry.attributes.position;
  19297. if ( geometryIndex !== null ) {
  19298. const array = geometryIndex.array;
  19299. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  19300. const a = array[ i + 0 ];
  19301. const b = array[ i + 1 ];
  19302. const c = array[ i + 2 ];
  19303. indices.push( a, b, b, c, c, a );
  19304. }
  19305. } else {
  19306. const array = geometryPosition.array;
  19307. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  19308. const a = i + 0;
  19309. const b = i + 1;
  19310. const c = i + 2;
  19311. indices.push( a, b, b, c, c, a );
  19312. }
  19313. }
  19314. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  19315. attribute.version = getWireframeVersion( geometry );
  19316. return attribute;
  19317. }
  19318. /**
  19319. * This renderer module manages geometries.
  19320. *
  19321. * @private
  19322. * @augments DataMap
  19323. */
  19324. class Geometries extends DataMap {
  19325. /**
  19326. * Constructs a new geometry management component.
  19327. *
  19328. * @param {Attributes} attributes - Renderer component for managing attributes.
  19329. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  19330. */
  19331. constructor( attributes, info ) {
  19332. super();
  19333. /**
  19334. * Renderer component for managing attributes.
  19335. *
  19336. * @type {Attributes}
  19337. */
  19338. this.attributes = attributes;
  19339. /**
  19340. * Renderer component for managing metrics and monitoring data.
  19341. *
  19342. * @type {Info}
  19343. */
  19344. this.info = info;
  19345. /**
  19346. * Weak Map for managing attributes for wireframe rendering.
  19347. *
  19348. * @type {WeakMap<BufferGeometry,BufferAttribute>}
  19349. */
  19350. this.wireframes = new WeakMap();
  19351. /**
  19352. * This Weak Map is used to make sure buffer attributes are
  19353. * updated only once per render call.
  19354. *
  19355. * @type {WeakMap<BufferAttribute,number>}
  19356. */
  19357. this.attributeCall = new WeakMap();
  19358. }
  19359. /**
  19360. * Returns `true` if the given render object has an initialized geometry.
  19361. *
  19362. * @param {RenderObject} renderObject - The render object.
  19363. * @return {boolean} Whether if the given render object has an initialized geometry or not.
  19364. */
  19365. has( renderObject ) {
  19366. const geometry = renderObject.geometry;
  19367. return super.has( geometry ) && this.get( geometry ).initialized === true;
  19368. }
  19369. /**
  19370. * Prepares the geometry of the given render object for rendering.
  19371. *
  19372. * @param {RenderObject} renderObject - The render object.
  19373. */
  19374. updateForRender( renderObject ) {
  19375. if ( this.has( renderObject ) === false ) this.initGeometry( renderObject );
  19376. this.updateAttributes( renderObject );
  19377. }
  19378. /**
  19379. * Initializes the geometry of the given render object.
  19380. *
  19381. * @param {RenderObject} renderObject - The render object.
  19382. */
  19383. initGeometry( renderObject ) {
  19384. const geometry = renderObject.geometry;
  19385. const geometryData = this.get( geometry );
  19386. geometryData.initialized = true;
  19387. this.info.memory.geometries ++;
  19388. const onDispose = () => {
  19389. this.info.memory.geometries --;
  19390. const index = geometry.index;
  19391. const geometryAttributes = renderObject.getAttributes();
  19392. if ( index !== null ) {
  19393. this.attributes.delete( index );
  19394. }
  19395. for ( const geometryAttribute of geometryAttributes ) {
  19396. this.attributes.delete( geometryAttribute );
  19397. }
  19398. const wireframeAttribute = this.wireframes.get( geometry );
  19399. if ( wireframeAttribute !== undefined ) {
  19400. this.attributes.delete( wireframeAttribute );
  19401. }
  19402. geometry.removeEventListener( 'dispose', onDispose );
  19403. };
  19404. geometry.addEventListener( 'dispose', onDispose );
  19405. }
  19406. /**
  19407. * Updates the geometry attributes of the given render object.
  19408. *
  19409. * @param {RenderObject} renderObject - The render object.
  19410. */
  19411. updateAttributes( renderObject ) {
  19412. // attributes
  19413. const attributes = renderObject.getAttributes();
  19414. for ( const attribute of attributes ) {
  19415. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  19416. this.updateAttribute( attribute, AttributeType.STORAGE );
  19417. } else {
  19418. this.updateAttribute( attribute, AttributeType.VERTEX );
  19419. }
  19420. }
  19421. // indexes
  19422. const index = this.getIndex( renderObject );
  19423. if ( index !== null ) {
  19424. this.updateAttribute( index, AttributeType.INDEX );
  19425. }
  19426. // indirect
  19427. const indirect = renderObject.geometry.indirect;
  19428. if ( indirect !== null ) {
  19429. this.updateAttribute( indirect, AttributeType.INDIRECT );
  19430. }
  19431. }
  19432. /**
  19433. * Updates the given attribute.
  19434. *
  19435. * @param {BufferAttribute} attribute - The attribute to update.
  19436. * @param {number} type - The attribute type.
  19437. */
  19438. updateAttribute( attribute, type ) {
  19439. const callId = this.info.render.calls;
  19440. if ( ! attribute.isInterleavedBufferAttribute ) {
  19441. if ( this.attributeCall.get( attribute ) !== callId ) {
  19442. this.attributes.update( attribute, type );
  19443. this.attributeCall.set( attribute, callId );
  19444. }
  19445. } else {
  19446. if ( this.attributeCall.get( attribute ) === undefined ) {
  19447. this.attributes.update( attribute, type );
  19448. this.attributeCall.set( attribute, callId );
  19449. } else if ( this.attributeCall.get( attribute.data ) !== callId ) {
  19450. this.attributes.update( attribute, type );
  19451. this.attributeCall.set( attribute.data, callId );
  19452. this.attributeCall.set( attribute, callId );
  19453. }
  19454. }
  19455. }
  19456. /**
  19457. * Returns the indirect buffer attribute of the given render object.
  19458. *
  19459. * @param {RenderObject} renderObject - The render object.
  19460. * @return {?BufferAttribute} The indirect attribute. `null` if no indirect drawing is used.
  19461. */
  19462. getIndirect( renderObject ) {
  19463. return renderObject.geometry.indirect;
  19464. }
  19465. /**
  19466. * Returns the index of the given render object's geometry. This is implemented
  19467. * in a method to return a wireframe index if necessary.
  19468. *
  19469. * @param {RenderObject} renderObject - The render object.
  19470. * @return {?BufferAttribute} The index. Returns `null` for non-indexed geometries.
  19471. */
  19472. getIndex( renderObject ) {
  19473. const { geometry, material } = renderObject;
  19474. let index = geometry.index;
  19475. if ( material.wireframe === true ) {
  19476. const wireframes = this.wireframes;
  19477. let wireframeAttribute = wireframes.get( geometry );
  19478. if ( wireframeAttribute === undefined ) {
  19479. wireframeAttribute = getWireframeIndex( geometry );
  19480. wireframes.set( geometry, wireframeAttribute );
  19481. } else if ( wireframeAttribute.version !== getWireframeVersion( geometry ) ) {
  19482. this.attributes.delete( wireframeAttribute );
  19483. wireframeAttribute = getWireframeIndex( geometry );
  19484. wireframes.set( geometry, wireframeAttribute );
  19485. }
  19486. index = wireframeAttribute;
  19487. }
  19488. return index;
  19489. }
  19490. }
  19491. /**
  19492. * This renderer module provides a series of statistical information
  19493. * about the GPU memory and the rendering process. Useful for debugging
  19494. * and monitoring.
  19495. */
  19496. class Info {
  19497. /**
  19498. * Constructs a new info component.
  19499. */
  19500. constructor() {
  19501. /**
  19502. * Whether frame related metrics should automatically
  19503. * be resetted or not. This property should be set to `false`
  19504. * by apps which manage their own animation loop. They must
  19505. * then call `renderer.info.reset()` once per frame manually.
  19506. *
  19507. * @type {boolean}
  19508. * @default true
  19509. */
  19510. this.autoReset = true;
  19511. /**
  19512. * The current frame ID. This ID is managed
  19513. * by `NodeFrame`.
  19514. *
  19515. * @type {number}
  19516. * @readonly
  19517. * @default 0
  19518. */
  19519. this.frame = 0;
  19520. /**
  19521. * The number of render calls since the
  19522. * app has been started.
  19523. *
  19524. * @type {number}
  19525. * @readonly
  19526. * @default 0
  19527. */
  19528. this.calls = 0;
  19529. /**
  19530. * Render related metrics.
  19531. *
  19532. * @type {Object}
  19533. * @readonly
  19534. * @property {number} calls - The number of render calls since the app has been started.
  19535. * @property {number} frameCalls - The number of render calls of the current frame.
  19536. * @property {number} drawCalls - The number of draw calls of the current frame.
  19537. * @property {number} triangles - The number of rendered triangle primitives of the current frame.
  19538. * @property {number} points - The number of rendered point primitives of the current frame.
  19539. * @property {number} lines - The number of rendered line primitives of the current frame.
  19540. * @property {number} timestamp - The timestamp of the frame when using `renderer.renderAsync()`.
  19541. */
  19542. this.render = {
  19543. calls: 0,
  19544. frameCalls: 0,
  19545. drawCalls: 0,
  19546. triangles: 0,
  19547. points: 0,
  19548. lines: 0,
  19549. timestamp: 0,
  19550. };
  19551. /**
  19552. * Compute related metrics.
  19553. *
  19554. * @type {Object}
  19555. * @readonly
  19556. * @property {number} calls - The number of compute calls since the app has been started.
  19557. * @property {number} frameCalls - The number of compute calls of the current frame.
  19558. * @property {number} timestamp - The timestamp of the frame when using `renderer.computeAsync()`.
  19559. */
  19560. this.compute = {
  19561. calls: 0,
  19562. frameCalls: 0,
  19563. timestamp: 0
  19564. };
  19565. /**
  19566. * Memory related metrics.
  19567. *
  19568. * @type {Object}
  19569. * @readonly
  19570. * @property {number} geometries - The number of active geometries.
  19571. * @property {number} frameCalls - The number of active textures.
  19572. */
  19573. this.memory = {
  19574. geometries: 0,
  19575. textures: 0
  19576. };
  19577. }
  19578. /**
  19579. * This method should be executed per draw call and updates the corresponding metrics.
  19580. *
  19581. * @param {Object3D} object - The 3D object that is going to be rendered.
  19582. * @param {number} count - The vertex or index count.
  19583. * @param {number} instanceCount - The instance count.
  19584. */
  19585. update( object, count, instanceCount ) {
  19586. this.render.drawCalls ++;
  19587. if ( object.isMesh || object.isSprite ) {
  19588. this.render.triangles += instanceCount * ( count / 3 );
  19589. } else if ( object.isPoints ) {
  19590. this.render.points += instanceCount * count;
  19591. } else if ( object.isLineSegments ) {
  19592. this.render.lines += instanceCount * ( count / 2 );
  19593. } else if ( object.isLine ) {
  19594. this.render.lines += instanceCount * ( count - 1 );
  19595. } else {
  19596. console.error( 'THREE.WebGPUInfo: Unknown object type.' );
  19597. }
  19598. }
  19599. /**
  19600. * Resets frame related metrics.
  19601. */
  19602. reset() {
  19603. this.render.drawCalls = 0;
  19604. this.render.frameCalls = 0;
  19605. this.compute.frameCalls = 0;
  19606. this.render.triangles = 0;
  19607. this.render.points = 0;
  19608. this.render.lines = 0;
  19609. }
  19610. /**
  19611. * Performs a complete reset of the object.
  19612. */
  19613. dispose() {
  19614. this.reset();
  19615. this.calls = 0;
  19616. this.render.calls = 0;
  19617. this.compute.calls = 0;
  19618. this.render.timestamp = 0;
  19619. this.compute.timestamp = 0;
  19620. this.memory.geometries = 0;
  19621. this.memory.textures = 0;
  19622. }
  19623. }
  19624. /**
  19625. * Abstract class for representing pipelines.
  19626. *
  19627. * @private
  19628. * @abstract
  19629. */
  19630. class Pipeline {
  19631. /**
  19632. * Constructs a new pipeline.
  19633. *
  19634. * @param {string} cacheKey - The pipeline's cache key.
  19635. */
  19636. constructor( cacheKey ) {
  19637. /**
  19638. * The pipeline's cache key.
  19639. *
  19640. * @type {string}
  19641. */
  19642. this.cacheKey = cacheKey;
  19643. /**
  19644. * How often the pipeline is currently in use.
  19645. *
  19646. * @type {number}
  19647. * @default 0
  19648. */
  19649. this.usedTimes = 0;
  19650. }
  19651. }
  19652. /**
  19653. * Class for representing render pipelines.
  19654. *
  19655. * @private
  19656. * @augments Pipeline
  19657. */
  19658. class RenderPipeline extends Pipeline {
  19659. /**
  19660. * Constructs a new render pipeline.
  19661. *
  19662. * @param {string} cacheKey - The pipeline's cache key.
  19663. * @param {ProgrammableStage} vertexProgram - The pipeline's vertex shader.
  19664. * @param {ProgrammableStage} fragmentProgram - The pipeline's fragment shader.
  19665. */
  19666. constructor( cacheKey, vertexProgram, fragmentProgram ) {
  19667. super( cacheKey );
  19668. /**
  19669. * The pipeline's vertex shader.
  19670. *
  19671. * @type {ProgrammableStage}
  19672. */
  19673. this.vertexProgram = vertexProgram;
  19674. /**
  19675. * The pipeline's fragment shader.
  19676. *
  19677. * @type {ProgrammableStage}
  19678. */
  19679. this.fragmentProgram = fragmentProgram;
  19680. }
  19681. }
  19682. /**
  19683. * Class for representing compute pipelines.
  19684. *
  19685. * @private
  19686. * @augments Pipeline
  19687. */
  19688. class ComputePipeline extends Pipeline {
  19689. /**
  19690. * Constructs a new render pipeline.
  19691. *
  19692. * @param {string} cacheKey - The pipeline's cache key.
  19693. * @param {ProgrammableStage} computeProgram - The pipeline's compute shader.
  19694. */
  19695. constructor( cacheKey, computeProgram ) {
  19696. super( cacheKey );
  19697. /**
  19698. * The pipeline's compute shader.
  19699. *
  19700. * @type {ProgrammableStage}
  19701. */
  19702. this.computeProgram = computeProgram;
  19703. /**
  19704. * This flag can be used for type testing.
  19705. *
  19706. * @type {boolean}
  19707. * @readonly
  19708. * @default true
  19709. */
  19710. this.isComputePipeline = true;
  19711. }
  19712. }
  19713. let _id$8 = 0;
  19714. /**
  19715. * Class for representing programmable stages which are vertex,
  19716. * fragment or compute shaders. Unlike fixed-function states (like blending),
  19717. * they represent the programmable part of a pipeline.
  19718. *
  19719. * @private
  19720. */
  19721. class ProgrammableStage {
  19722. /**
  19723. * Constructs a new programmable stage.
  19724. *
  19725. * @param {string} code - The shader code.
  19726. * @param {('vertex'|'fragment'|'compute')} stage - The type of stage.
  19727. * @param {string} name - The name of the shader.
  19728. * @param {?Array<Object>} [transforms=null] - The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  19729. * @param {?Array<Object>} [attributes=null] - The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  19730. */
  19731. constructor( code, stage, name, transforms = null, attributes = null ) {
  19732. /**
  19733. * The id of the programmable stage.
  19734. *
  19735. * @type {number}
  19736. */
  19737. this.id = _id$8 ++;
  19738. /**
  19739. * The shader code.
  19740. *
  19741. * @type {string}
  19742. */
  19743. this.code = code;
  19744. /**
  19745. * The type of stage.
  19746. *
  19747. * @type {string}
  19748. */
  19749. this.stage = stage;
  19750. /**
  19751. * The name of the stage.
  19752. * This is used for debugging purposes.
  19753. *
  19754. * @type {string}
  19755. */
  19756. this.name = name;
  19757. /**
  19758. * The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  19759. *
  19760. * @type {?Array<Object>}
  19761. */
  19762. this.transforms = transforms;
  19763. /**
  19764. * The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  19765. *
  19766. * @type {?Array<Object>}
  19767. */
  19768. this.attributes = attributes;
  19769. /**
  19770. * How often the programmable stage is currently in use.
  19771. *
  19772. * @type {number}
  19773. * @default 0
  19774. */
  19775. this.usedTimes = 0;
  19776. }
  19777. }
  19778. /**
  19779. * This renderer module manages the pipelines of the renderer.
  19780. *
  19781. * @private
  19782. * @augments DataMap
  19783. */
  19784. class Pipelines extends DataMap {
  19785. /**
  19786. * Constructs a new pipeline management component.
  19787. *
  19788. * @param {Backend} backend - The renderer's backend.
  19789. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  19790. */
  19791. constructor( backend, nodes ) {
  19792. super();
  19793. /**
  19794. * The renderer's backend.
  19795. *
  19796. * @type {Backend}
  19797. */
  19798. this.backend = backend;
  19799. /**
  19800. * Renderer component for managing nodes related logic.
  19801. *
  19802. * @type {Nodes}
  19803. */
  19804. this.nodes = nodes;
  19805. /**
  19806. * A references to the bindings management component.
  19807. * This reference will be set inside the `Bindings`
  19808. * constructor.
  19809. *
  19810. * @type {?Bindings}
  19811. * @default null
  19812. */
  19813. this.bindings = null;
  19814. /**
  19815. * Internal cache for maintaining pipelines.
  19816. * The key of the map is a cache key, the value the pipeline.
  19817. *
  19818. * @type {Map<string,Pipeline>}
  19819. */
  19820. this.caches = new Map();
  19821. /**
  19822. * This dictionary maintains for each shader stage type (vertex,
  19823. * fragment and compute) the programmable stage objects which
  19824. * represent the actual shader code.
  19825. *
  19826. * @type {Object<string,Map>}
  19827. */
  19828. this.programs = {
  19829. vertex: new Map(),
  19830. fragment: new Map(),
  19831. compute: new Map()
  19832. };
  19833. }
  19834. /**
  19835. * Returns a compute pipeline for the given compute node.
  19836. *
  19837. * @param {Node} computeNode - The compute node.
  19838. * @param {Array<BindGroup>} bindings - The bindings.
  19839. * @return {ComputePipeline} The compute pipeline.
  19840. */
  19841. getForCompute( computeNode, bindings ) {
  19842. const { backend } = this;
  19843. const data = this.get( computeNode );
  19844. if ( this._needsComputeUpdate( computeNode ) ) {
  19845. const previousPipeline = data.pipeline;
  19846. if ( previousPipeline ) {
  19847. previousPipeline.usedTimes --;
  19848. previousPipeline.computeProgram.usedTimes --;
  19849. }
  19850. // get shader
  19851. const nodeBuilderState = this.nodes.getForCompute( computeNode );
  19852. // programmable stage
  19853. let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader );
  19854. if ( stageCompute === undefined ) {
  19855. if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram );
  19856. stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', computeNode.name, nodeBuilderState.transforms, nodeBuilderState.nodeAttributes );
  19857. this.programs.compute.set( nodeBuilderState.computeShader, stageCompute );
  19858. backend.createProgram( stageCompute );
  19859. }
  19860. // determine compute pipeline
  19861. const cacheKey = this._getComputeCacheKey( computeNode, stageCompute );
  19862. let pipeline = this.caches.get( cacheKey );
  19863. if ( pipeline === undefined ) {
  19864. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  19865. pipeline = this._getComputePipeline( computeNode, stageCompute, cacheKey, bindings );
  19866. }
  19867. // keep track of all used times
  19868. pipeline.usedTimes ++;
  19869. stageCompute.usedTimes ++;
  19870. //
  19871. data.version = computeNode.version;
  19872. data.pipeline = pipeline;
  19873. }
  19874. return data.pipeline;
  19875. }
  19876. /**
  19877. * Returns a render pipeline for the given render object.
  19878. *
  19879. * @param {RenderObject} renderObject - The render object.
  19880. * @param {?Array<Promise>} [promises=null] - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  19881. * @return {RenderPipeline} The render pipeline.
  19882. */
  19883. getForRender( renderObject, promises = null ) {
  19884. const { backend } = this;
  19885. const data = this.get( renderObject );
  19886. if ( this._needsRenderUpdate( renderObject ) ) {
  19887. const previousPipeline = data.pipeline;
  19888. if ( previousPipeline ) {
  19889. previousPipeline.usedTimes --;
  19890. previousPipeline.vertexProgram.usedTimes --;
  19891. previousPipeline.fragmentProgram.usedTimes --;
  19892. }
  19893. // get shader
  19894. const nodeBuilderState = renderObject.getNodeBuilderState();
  19895. const name = renderObject.material ? renderObject.material.name : '';
  19896. // programmable stages
  19897. let stageVertex = this.programs.vertex.get( nodeBuilderState.vertexShader );
  19898. if ( stageVertex === undefined ) {
  19899. if ( previousPipeline && previousPipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.vertexProgram );
  19900. stageVertex = new ProgrammableStage( nodeBuilderState.vertexShader, 'vertex', name );
  19901. this.programs.vertex.set( nodeBuilderState.vertexShader, stageVertex );
  19902. backend.createProgram( stageVertex );
  19903. }
  19904. let stageFragment = this.programs.fragment.get( nodeBuilderState.fragmentShader );
  19905. if ( stageFragment === undefined ) {
  19906. if ( previousPipeline && previousPipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.fragmentProgram );
  19907. stageFragment = new ProgrammableStage( nodeBuilderState.fragmentShader, 'fragment', name );
  19908. this.programs.fragment.set( nodeBuilderState.fragmentShader, stageFragment );
  19909. backend.createProgram( stageFragment );
  19910. }
  19911. // determine render pipeline
  19912. const cacheKey = this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  19913. let pipeline = this.caches.get( cacheKey );
  19914. if ( pipeline === undefined ) {
  19915. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  19916. pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises );
  19917. } else {
  19918. renderObject.pipeline = pipeline;
  19919. }
  19920. // keep track of all used times
  19921. pipeline.usedTimes ++;
  19922. stageVertex.usedTimes ++;
  19923. stageFragment.usedTimes ++;
  19924. //
  19925. data.pipeline = pipeline;
  19926. }
  19927. return data.pipeline;
  19928. }
  19929. /**
  19930. * Deletes the pipeline for the given render object.
  19931. *
  19932. * @param {RenderObject} object - The render object.
  19933. * @return {?Object} The deleted dictionary.
  19934. */
  19935. delete( object ) {
  19936. const pipeline = this.get( object ).pipeline;
  19937. if ( pipeline ) {
  19938. // pipeline
  19939. pipeline.usedTimes --;
  19940. if ( pipeline.usedTimes === 0 ) this._releasePipeline( pipeline );
  19941. // programs
  19942. if ( pipeline.isComputePipeline ) {
  19943. pipeline.computeProgram.usedTimes --;
  19944. if ( pipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( pipeline.computeProgram );
  19945. } else {
  19946. pipeline.fragmentProgram.usedTimes --;
  19947. pipeline.vertexProgram.usedTimes --;
  19948. if ( pipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( pipeline.vertexProgram );
  19949. if ( pipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( pipeline.fragmentProgram );
  19950. }
  19951. }
  19952. return super.delete( object );
  19953. }
  19954. /**
  19955. * Frees internal resources.
  19956. */
  19957. dispose() {
  19958. super.dispose();
  19959. this.caches = new Map();
  19960. this.programs = {
  19961. vertex: new Map(),
  19962. fragment: new Map(),
  19963. compute: new Map()
  19964. };
  19965. }
  19966. /**
  19967. * Updates the pipeline for the given render object.
  19968. *
  19969. * @param {RenderObject} renderObject - The render object.
  19970. */
  19971. updateForRender( renderObject ) {
  19972. this.getForRender( renderObject );
  19973. }
  19974. /**
  19975. * Returns a compute pipeline for the given parameters.
  19976. *
  19977. * @private
  19978. * @param {Node} computeNode - The compute node.
  19979. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  19980. * @param {string} cacheKey - The cache key.
  19981. * @param {Array<BindGroup>} bindings - The bindings.
  19982. * @return {ComputePipeline} The compute pipeline.
  19983. */
  19984. _getComputePipeline( computeNode, stageCompute, cacheKey, bindings ) {
  19985. // check for existing pipeline
  19986. cacheKey = cacheKey || this._getComputeCacheKey( computeNode, stageCompute );
  19987. let pipeline = this.caches.get( cacheKey );
  19988. if ( pipeline === undefined ) {
  19989. pipeline = new ComputePipeline( cacheKey, stageCompute );
  19990. this.caches.set( cacheKey, pipeline );
  19991. this.backend.createComputePipeline( pipeline, bindings );
  19992. }
  19993. return pipeline;
  19994. }
  19995. /**
  19996. * Returns a render pipeline for the given parameters.
  19997. *
  19998. * @private
  19999. * @param {RenderObject} renderObject - The render object.
  20000. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  20001. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  20002. * @param {string} cacheKey - The cache key.
  20003. * @param {?Array<Promise>} promises - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  20004. * @return {ComputePipeline} The compute pipeline.
  20005. */
  20006. _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) {
  20007. // check for existing pipeline
  20008. cacheKey = cacheKey || this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  20009. let pipeline = this.caches.get( cacheKey );
  20010. if ( pipeline === undefined ) {
  20011. pipeline = new RenderPipeline( cacheKey, stageVertex, stageFragment );
  20012. this.caches.set( cacheKey, pipeline );
  20013. renderObject.pipeline = pipeline;
  20014. // The `promises` array is `null` by default and only set to an empty array when
  20015. // `Renderer.compileAsync()` is used. The next call actually fills the array with
  20016. // pending promises that resolve when the render pipelines are ready for rendering.
  20017. this.backend.createRenderPipeline( renderObject, promises );
  20018. }
  20019. return pipeline;
  20020. }
  20021. /**
  20022. * Computes a cache key representing a compute pipeline.
  20023. *
  20024. * @private
  20025. * @param {Node} computeNode - The compute node.
  20026. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  20027. * @return {string} The cache key.
  20028. */
  20029. _getComputeCacheKey( computeNode, stageCompute ) {
  20030. return computeNode.id + ',' + stageCompute.id;
  20031. }
  20032. /**
  20033. * Computes a cache key representing a render pipeline.
  20034. *
  20035. * @private
  20036. * @param {RenderObject} renderObject - The render object.
  20037. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  20038. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  20039. * @return {string} The cache key.
  20040. */
  20041. _getRenderCacheKey( renderObject, stageVertex, stageFragment ) {
  20042. return stageVertex.id + ',' + stageFragment.id + ',' + this.backend.getRenderCacheKey( renderObject );
  20043. }
  20044. /**
  20045. * Releases the given pipeline.
  20046. *
  20047. * @private
  20048. * @param {Pipeline} pipeline - The pipeline to release.
  20049. */
  20050. _releasePipeline( pipeline ) {
  20051. this.caches.delete( pipeline.cacheKey );
  20052. }
  20053. /**
  20054. * Releases the shader program.
  20055. *
  20056. * @private
  20057. * @param {Object} program - The shader program to release.
  20058. */
  20059. _releaseProgram( program ) {
  20060. const code = program.code;
  20061. const stage = program.stage;
  20062. this.programs[ stage ].delete( code );
  20063. }
  20064. /**
  20065. * Returns `true` if the compute pipeline for the given compute node requires an update.
  20066. *
  20067. * @private
  20068. * @param {Node} computeNode - The compute node.
  20069. * @return {boolean} Whether the compute pipeline for the given compute node requires an update or not.
  20070. */
  20071. _needsComputeUpdate( computeNode ) {
  20072. const data = this.get( computeNode );
  20073. return data.pipeline === undefined || data.version !== computeNode.version;
  20074. }
  20075. /**
  20076. * Returns `true` if the render pipeline for the given render object requires an update.
  20077. *
  20078. * @private
  20079. * @param {RenderObject} renderObject - The render object.
  20080. * @return {boolean} Whether the render object for the given render object requires an update or not.
  20081. */
  20082. _needsRenderUpdate( renderObject ) {
  20083. const data = this.get( renderObject );
  20084. return data.pipeline === undefined || this.backend.needsRenderUpdate( renderObject );
  20085. }
  20086. }
  20087. /**
  20088. * This renderer module manages the bindings of the renderer.
  20089. *
  20090. * @private
  20091. * @augments DataMap
  20092. */
  20093. class Bindings extends DataMap {
  20094. /**
  20095. * Constructs a new bindings management component.
  20096. *
  20097. * @param {Backend} backend - The renderer's backend.
  20098. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  20099. * @param {Textures} textures - Renderer component for managing textures.
  20100. * @param {Attributes} attributes - Renderer component for managing attributes.
  20101. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  20102. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  20103. */
  20104. constructor( backend, nodes, textures, attributes, pipelines, info ) {
  20105. super();
  20106. /**
  20107. * The renderer's backend.
  20108. *
  20109. * @type {Backend}
  20110. */
  20111. this.backend = backend;
  20112. /**
  20113. * Renderer component for managing textures.
  20114. *
  20115. * @type {Textures}
  20116. */
  20117. this.textures = textures;
  20118. /**
  20119. * Renderer component for managing pipelines.
  20120. *
  20121. * @type {Pipelines}
  20122. */
  20123. this.pipelines = pipelines;
  20124. /**
  20125. * Renderer component for managing attributes.
  20126. *
  20127. * @type {Attributes}
  20128. */
  20129. this.attributes = attributes;
  20130. /**
  20131. * Renderer component for managing nodes related logic.
  20132. *
  20133. * @type {Nodes}
  20134. */
  20135. this.nodes = nodes;
  20136. /**
  20137. * Renderer component for managing metrics and monitoring data.
  20138. *
  20139. * @type {Info}
  20140. */
  20141. this.info = info;
  20142. this.pipelines.bindings = this; // assign bindings to pipelines
  20143. }
  20144. /**
  20145. * Returns the bind groups for the given render object.
  20146. *
  20147. * @param {RenderObject} renderObject - The render object.
  20148. * @return {Array<BindGroup>} The bind groups.
  20149. */
  20150. getForRender( renderObject ) {
  20151. const bindings = renderObject.getBindings();
  20152. for ( const bindGroup of bindings ) {
  20153. const groupData = this.get( bindGroup );
  20154. if ( groupData.bindGroup === undefined ) {
  20155. // each object defines an array of bindings (ubos, textures, samplers etc.)
  20156. this._init( bindGroup );
  20157. this.backend.createBindings( bindGroup, bindings, 0 );
  20158. groupData.bindGroup = bindGroup;
  20159. }
  20160. }
  20161. return bindings;
  20162. }
  20163. /**
  20164. * Returns the bind groups for the given compute node.
  20165. *
  20166. * @param {Node} computeNode - The compute node.
  20167. * @return {Array<BindGroup>} The bind groups.
  20168. */
  20169. getForCompute( computeNode ) {
  20170. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  20171. for ( const bindGroup of bindings ) {
  20172. const groupData = this.get( bindGroup );
  20173. if ( groupData.bindGroup === undefined ) {
  20174. this._init( bindGroup );
  20175. this.backend.createBindings( bindGroup, bindings, 0 );
  20176. groupData.bindGroup = bindGroup;
  20177. }
  20178. }
  20179. return bindings;
  20180. }
  20181. /**
  20182. * Updates the bindings for the given compute node.
  20183. *
  20184. * @param {Node} computeNode - The compute node.
  20185. */
  20186. updateForCompute( computeNode ) {
  20187. this._updateBindings( this.getForCompute( computeNode ) );
  20188. }
  20189. /**
  20190. * Updates the bindings for the given render object.
  20191. *
  20192. * @param {RenderObject} renderObject - The render object.
  20193. */
  20194. updateForRender( renderObject ) {
  20195. this._updateBindings( this.getForRender( renderObject ) );
  20196. }
  20197. /**
  20198. * Updates the given array of bindings.
  20199. *
  20200. * @param {Array<BindGroup>} bindings - The bind groups.
  20201. */
  20202. _updateBindings( bindings ) {
  20203. for ( const bindGroup of bindings ) {
  20204. this._update( bindGroup, bindings );
  20205. }
  20206. }
  20207. /**
  20208. * Initializes the given bind group.
  20209. *
  20210. * @param {BindGroup} bindGroup - The bind group to initialize.
  20211. */
  20212. _init( bindGroup ) {
  20213. for ( const binding of bindGroup.bindings ) {
  20214. if ( binding.isSampledTexture ) {
  20215. this.textures.updateTexture( binding.texture );
  20216. } else if ( binding.isStorageBuffer ) {
  20217. const attribute = binding.attribute;
  20218. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  20219. this.attributes.update( attribute, attributeType );
  20220. }
  20221. }
  20222. }
  20223. /**
  20224. * Updates the given bind group.
  20225. *
  20226. * @param {BindGroup} bindGroup - The bind group to update.
  20227. * @param {Array<BindGroup>} bindings - The bind groups.
  20228. */
  20229. _update( bindGroup, bindings ) {
  20230. const { backend } = this;
  20231. let needsBindingsUpdate = false;
  20232. let cacheBindings = true;
  20233. let cacheIndex = 0;
  20234. let version = 0;
  20235. // iterate over all bindings and check if buffer updates or a new binding group is required
  20236. for ( const binding of bindGroup.bindings ) {
  20237. if ( binding.isNodeUniformsGroup ) {
  20238. const updated = this.nodes.updateGroup( binding );
  20239. // every uniforms group is a uniform buffer. So if no update is required,
  20240. // we move one with the next binding. Otherwise the next if block will update the group.
  20241. if ( updated === false ) continue;
  20242. }
  20243. if ( binding.isStorageBuffer ) {
  20244. const attribute = binding.attribute;
  20245. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  20246. this.attributes.update( attribute, attributeType );
  20247. }
  20248. if ( binding.isUniformBuffer ) {
  20249. const updated = binding.update();
  20250. if ( updated ) {
  20251. backend.updateBinding( binding );
  20252. }
  20253. } else if ( binding.isSampler ) {
  20254. binding.update();
  20255. } else if ( binding.isSampledTexture ) {
  20256. const texturesTextureData = this.textures.get( binding.texture );
  20257. if ( binding.needsBindingsUpdate( texturesTextureData.generation ) ) needsBindingsUpdate = true;
  20258. const updated = binding.update();
  20259. const texture = binding.texture;
  20260. if ( updated ) {
  20261. this.textures.updateTexture( texture );
  20262. }
  20263. const textureData = backend.get( texture );
  20264. if ( textureData.externalTexture !== undefined || texturesTextureData.isDefaultTexture ) {
  20265. cacheBindings = false;
  20266. } else {
  20267. cacheIndex = cacheIndex * 10 + texture.id;
  20268. version += texture.version;
  20269. }
  20270. if ( backend.isWebGPUBackend === true && textureData.texture === undefined && textureData.externalTexture === undefined ) {
  20271. // TODO: Remove this once we found why updated === false isn't bound to a texture in the WebGPU backend
  20272. console.error( 'Bindings._update: binding should be available:', binding, updated, texture, binding.textureNode.value, needsBindingsUpdate );
  20273. this.textures.updateTexture( texture );
  20274. needsBindingsUpdate = true;
  20275. }
  20276. if ( texture.isStorageTexture === true ) {
  20277. const textureData = this.get( texture );
  20278. if ( binding.store === true ) {
  20279. textureData.needsMipmap = true;
  20280. } else if ( this.textures.needsMipmaps( texture ) && textureData.needsMipmap === true ) {
  20281. this.backend.generateMipmaps( texture );
  20282. textureData.needsMipmap = false;
  20283. }
  20284. }
  20285. }
  20286. }
  20287. if ( needsBindingsUpdate === true ) {
  20288. this.backend.updateBindings( bindGroup, bindings, cacheBindings ? cacheIndex : 0, version );
  20289. }
  20290. }
  20291. }
  20292. /**
  20293. * Default sorting function for opaque render items.
  20294. *
  20295. * @private
  20296. * @function
  20297. * @param {Object} a - The first render item.
  20298. * @param {Object} b - The second render item.
  20299. * @return {number} A numeric value which defines the sort order.
  20300. */
  20301. function painterSortStable( a, b ) {
  20302. if ( a.groupOrder !== b.groupOrder ) {
  20303. return a.groupOrder - b.groupOrder;
  20304. } else if ( a.renderOrder !== b.renderOrder ) {
  20305. return a.renderOrder - b.renderOrder;
  20306. } else if ( a.z !== b.z ) {
  20307. return a.z - b.z;
  20308. } else {
  20309. return a.id - b.id;
  20310. }
  20311. }
  20312. /**
  20313. * Default sorting function for transparent render items.
  20314. *
  20315. * @private
  20316. * @function
  20317. * @param {Object} a - The first render item.
  20318. * @param {Object} b - The second render item.
  20319. * @return {number} A numeric value which defines the sort order.
  20320. */
  20321. function reversePainterSortStable( a, b ) {
  20322. if ( a.groupOrder !== b.groupOrder ) {
  20323. return a.groupOrder - b.groupOrder;
  20324. } else if ( a.renderOrder !== b.renderOrder ) {
  20325. return a.renderOrder - b.renderOrder;
  20326. } else if ( a.z !== b.z ) {
  20327. return b.z - a.z;
  20328. } else {
  20329. return a.id - b.id;
  20330. }
  20331. }
  20332. /**
  20333. * Returns `true` if the given transparent material requires a double pass.
  20334. *
  20335. * @private
  20336. * @function
  20337. * @param {Material} material - The transparent material.
  20338. * @return {boolean} Whether the given material requires a double pass or not.
  20339. */
  20340. function needsDoublePass( material ) {
  20341. const hasTransmission = material.transmission > 0 || material.transmissionNode;
  20342. return hasTransmission && material.side === DoubleSide && material.forceSinglePass === false;
  20343. }
  20344. /**
  20345. * When the renderer analyzes the scene at the beginning of a render call,
  20346. * it stores 3D object for further processing in render lists. Depending on the
  20347. * properties of a 3D objects (like their transformation or material state), the
  20348. * objects are maintained in ordered lists for the actual rendering.
  20349. *
  20350. * Render lists are unique per scene and camera combination.
  20351. *
  20352. * @private
  20353. * @augments Pipeline
  20354. */
  20355. class RenderList {
  20356. /**
  20357. * Constructs a render list.
  20358. *
  20359. * @param {Lighting} lighting - The lighting management component.
  20360. * @param {Scene} scene - The scene.
  20361. * @param {Camera} camera - The camera the scene is rendered with.
  20362. */
  20363. constructor( lighting, scene, camera ) {
  20364. /**
  20365. * 3D objects are transformed into render items and stored in this array.
  20366. *
  20367. * @type {Array<Object>}
  20368. */
  20369. this.renderItems = [];
  20370. /**
  20371. * The current render items index.
  20372. *
  20373. * @type {number}
  20374. * @default 0
  20375. */
  20376. this.renderItemsIndex = 0;
  20377. /**
  20378. * A list with opaque render items.
  20379. *
  20380. * @type {Array<Object>}
  20381. */
  20382. this.opaque = [];
  20383. /**
  20384. * A list with transparent render items which require
  20385. * double pass rendering (e.g. transmissive objects).
  20386. *
  20387. * @type {Array<Object>}
  20388. */
  20389. this.transparentDoublePass = [];
  20390. /**
  20391. * A list with transparent render items.
  20392. *
  20393. * @type {Array<Object>}
  20394. */
  20395. this.transparent = [];
  20396. /**
  20397. * A list with transparent render bundle data.
  20398. *
  20399. * @type {Array<Object>}
  20400. */
  20401. this.bundles = [];
  20402. /**
  20403. * The render list's lights node. This node is later
  20404. * relevant for the actual analytical light nodes which
  20405. * compute the scene's lighting in the shader.
  20406. *
  20407. * @type {LightsNode}
  20408. */
  20409. this.lightsNode = lighting.getNode( scene, camera );
  20410. /**
  20411. * The scene's lights stored in an array. This array
  20412. * is used to setup the lights node.
  20413. *
  20414. * @type {Array<Light>}
  20415. */
  20416. this.lightsArray = [];
  20417. /**
  20418. * The scene.
  20419. *
  20420. * @type {Scene}
  20421. */
  20422. this.scene = scene;
  20423. /**
  20424. * The camera the scene is rendered with.
  20425. *
  20426. * @type {Camera}
  20427. */
  20428. this.camera = camera;
  20429. /**
  20430. * How many objects perform occlusion query tests.
  20431. *
  20432. * @type {number}
  20433. * @default 0
  20434. */
  20435. this.occlusionQueryCount = 0;
  20436. }
  20437. /**
  20438. * This method is called right at the beginning of a render call
  20439. * before the scene is analyzed. It prepares the internal data
  20440. * structures for the upcoming render lists generation.
  20441. *
  20442. * @return {RenderList} A reference to this render list.
  20443. */
  20444. begin() {
  20445. this.renderItemsIndex = 0;
  20446. this.opaque.length = 0;
  20447. this.transparentDoublePass.length = 0;
  20448. this.transparent.length = 0;
  20449. this.bundles.length = 0;
  20450. this.lightsArray.length = 0;
  20451. this.occlusionQueryCount = 0;
  20452. return this;
  20453. }
  20454. /**
  20455. * Returns a render item for the giving render item state. The state is defined
  20456. * by a series of object-related parameters.
  20457. *
  20458. * The method avoids object creation by holding render items and reusing them in
  20459. * subsequent render calls (just with different property values).
  20460. *
  20461. * @param {Object3D} object - The 3D object.
  20462. * @param {BufferGeometry} geometry - The 3D object's geometry.
  20463. * @param {Material} material - The 3D object's material.
  20464. * @param {number} groupOrder - The current group order.
  20465. * @param {number} z - Th 3D object's depth value (z value in clip space).
  20466. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  20467. * @param {ClippingContext} clippingContext - The current clipping context.
  20468. * @return {Object} The render item.
  20469. */
  20470. getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext ) {
  20471. let renderItem = this.renderItems[ this.renderItemsIndex ];
  20472. if ( renderItem === undefined ) {
  20473. renderItem = {
  20474. id: object.id,
  20475. object: object,
  20476. geometry: geometry,
  20477. material: material,
  20478. groupOrder: groupOrder,
  20479. renderOrder: object.renderOrder,
  20480. z: z,
  20481. group: group,
  20482. clippingContext: clippingContext
  20483. };
  20484. this.renderItems[ this.renderItemsIndex ] = renderItem;
  20485. } else {
  20486. renderItem.id = object.id;
  20487. renderItem.object = object;
  20488. renderItem.geometry = geometry;
  20489. renderItem.material = material;
  20490. renderItem.groupOrder = groupOrder;
  20491. renderItem.renderOrder = object.renderOrder;
  20492. renderItem.z = z;
  20493. renderItem.group = group;
  20494. renderItem.clippingContext = clippingContext;
  20495. }
  20496. this.renderItemsIndex ++;
  20497. return renderItem;
  20498. }
  20499. /**
  20500. * Pushes the given object as a render item to the internal render lists.
  20501. * The selected lists depend on the object properties.
  20502. *
  20503. * @param {Object3D} object - The 3D object.
  20504. * @param {BufferGeometry} geometry - The 3D object's geometry.
  20505. * @param {Material} material - The 3D object's material.
  20506. * @param {number} groupOrder - The current group order.
  20507. * @param {number} z - Th 3D object's depth value (z value in clip space).
  20508. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  20509. * @param {ClippingContext} clippingContext - The current clipping context.
  20510. */
  20511. push( object, geometry, material, groupOrder, z, group, clippingContext ) {
  20512. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  20513. if ( object.occlusionTest === true ) this.occlusionQueryCount ++;
  20514. if ( material.transparent === true || material.transmission > 0 ) {
  20515. if ( needsDoublePass( material ) ) this.transparentDoublePass.push( renderItem );
  20516. this.transparent.push( renderItem );
  20517. } else {
  20518. this.opaque.push( renderItem );
  20519. }
  20520. }
  20521. /**
  20522. * Inserts the given object as a render item at the start of the internal render lists.
  20523. * The selected lists depend on the object properties.
  20524. *
  20525. * @param {Object3D} object - The 3D object.
  20526. * @param {BufferGeometry} geometry - The 3D object's geometry.
  20527. * @param {Material} material - The 3D object's material.
  20528. * @param {number} groupOrder - The current group order.
  20529. * @param {number} z - Th 3D object's depth value (z value in clip space).
  20530. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  20531. * @param {ClippingContext} clippingContext - The current clipping context.
  20532. */
  20533. unshift( object, geometry, material, groupOrder, z, group, clippingContext ) {
  20534. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  20535. if ( material.transparent === true || material.transmission > 0 ) {
  20536. if ( needsDoublePass( material ) ) this.transparentDoublePass.unshift( renderItem );
  20537. this.transparent.unshift( renderItem );
  20538. } else {
  20539. this.opaque.unshift( renderItem );
  20540. }
  20541. }
  20542. /**
  20543. * Pushes render bundle group data into the render list.
  20544. *
  20545. * @param {Object} group - Bundle group data.
  20546. */
  20547. pushBundle( group ) {
  20548. this.bundles.push( group );
  20549. }
  20550. /**
  20551. * Pushes a light into the render list.
  20552. *
  20553. * @param {Light} light - The light.
  20554. */
  20555. pushLight( light ) {
  20556. this.lightsArray.push( light );
  20557. }
  20558. /**
  20559. * Sorts the internal render lists.
  20560. *
  20561. * @param {?function(any, any): number} customOpaqueSort - A custom sort function for opaque objects.
  20562. * @param {?function(any, any): number} customTransparentSort - A custom sort function for transparent objects.
  20563. */
  20564. sort( customOpaqueSort, customTransparentSort ) {
  20565. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  20566. if ( this.transparentDoublePass.length > 1 ) this.transparentDoublePass.sort( customTransparentSort || reversePainterSortStable );
  20567. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  20568. }
  20569. /**
  20570. * This method performs finalizing tasks right after the render lists
  20571. * have been generated.
  20572. */
  20573. finish() {
  20574. // update lights
  20575. this.lightsNode.setLights( this.lightsArray );
  20576. // Clear references from inactive renderItems in the list
  20577. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  20578. const renderItem = this.renderItems[ i ];
  20579. if ( renderItem.id === null ) break;
  20580. renderItem.id = null;
  20581. renderItem.object = null;
  20582. renderItem.geometry = null;
  20583. renderItem.material = null;
  20584. renderItem.groupOrder = null;
  20585. renderItem.renderOrder = null;
  20586. renderItem.z = null;
  20587. renderItem.group = null;
  20588. renderItem.clippingContext = null;
  20589. }
  20590. }
  20591. }
  20592. const _chainKeys$4 = [];
  20593. /**
  20594. * This renderer module manages the render lists which are unique
  20595. * per scene and camera combination.
  20596. *
  20597. * @private
  20598. */
  20599. class RenderLists {
  20600. /**
  20601. * Constructs a render lists management component.
  20602. *
  20603. * @param {Lighting} lighting - The lighting management component.
  20604. */
  20605. constructor( lighting ) {
  20606. /**
  20607. * The lighting management component.
  20608. *
  20609. * @type {Lighting}
  20610. */
  20611. this.lighting = lighting;
  20612. /**
  20613. * The internal chain map which holds the render lists.
  20614. *
  20615. * @type {ChainMap}
  20616. */
  20617. this.lists = new ChainMap();
  20618. }
  20619. /**
  20620. * Returns a render list for the given scene and camera.
  20621. *
  20622. * @param {Scene} scene - The scene.
  20623. * @param {Camera} camera - The camera.
  20624. * @return {RenderList} The render list.
  20625. */
  20626. get( scene, camera ) {
  20627. const lists = this.lists;
  20628. _chainKeys$4[ 0 ] = scene;
  20629. _chainKeys$4[ 1 ] = camera;
  20630. let list = lists.get( _chainKeys$4 );
  20631. if ( list === undefined ) {
  20632. list = new RenderList( this.lighting, scene, camera );
  20633. lists.set( _chainKeys$4, list );
  20634. }
  20635. _chainKeys$4.length = 0;
  20636. return list;
  20637. }
  20638. /**
  20639. * Frees all internal resources.
  20640. */
  20641. dispose() {
  20642. this.lists = new ChainMap();
  20643. }
  20644. }
  20645. let _id$7 = 0;
  20646. /**
  20647. * Any render or compute command is executed in a specific context that defines
  20648. * the state of the renderer and its backend. Typical examples for such context
  20649. * data are the current clear values or data from the active framebuffer. This
  20650. * module is used to represent these contexts as objects.
  20651. *
  20652. * @private
  20653. */
  20654. class RenderContext {
  20655. /**
  20656. * Constructs a new render context.
  20657. */
  20658. constructor() {
  20659. /**
  20660. * The context's ID.
  20661. *
  20662. * @type {number}
  20663. */
  20664. this.id = _id$7 ++;
  20665. /**
  20666. * Whether the current active framebuffer has a color attachment.
  20667. *
  20668. * @type {boolean}
  20669. * @default true
  20670. */
  20671. this.color = true;
  20672. /**
  20673. * Whether the color attachment should be cleared or not.
  20674. *
  20675. * @type {boolean}
  20676. * @default true
  20677. */
  20678. this.clearColor = true;
  20679. /**
  20680. * The clear color value.
  20681. *
  20682. * @type {Object}
  20683. * @default true
  20684. */
  20685. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  20686. /**
  20687. * Whether the current active framebuffer has a depth attachment.
  20688. *
  20689. * @type {boolean}
  20690. * @default true
  20691. */
  20692. this.depth = true;
  20693. /**
  20694. * Whether the depth attachment should be cleared or not.
  20695. *
  20696. * @type {boolean}
  20697. * @default true
  20698. */
  20699. this.clearDepth = true;
  20700. /**
  20701. * The clear depth value.
  20702. *
  20703. * @type {number}
  20704. * @default 1
  20705. */
  20706. this.clearDepthValue = 1;
  20707. /**
  20708. * Whether the current active framebuffer has a stencil attachment.
  20709. *
  20710. * @type {boolean}
  20711. * @default false
  20712. */
  20713. this.stencil = false;
  20714. /**
  20715. * Whether the stencil attachment should be cleared or not.
  20716. *
  20717. * @type {boolean}
  20718. * @default true
  20719. */
  20720. this.clearStencil = true;
  20721. /**
  20722. * The clear stencil value.
  20723. *
  20724. * @type {number}
  20725. * @default 1
  20726. */
  20727. this.clearStencilValue = 1;
  20728. /**
  20729. * By default the viewport encloses the entire framebuffer If a smaller
  20730. * viewport is manually defined, this property is to `true` by the renderer.
  20731. *
  20732. * @type {boolean}
  20733. * @default false
  20734. */
  20735. this.viewport = false;
  20736. /**
  20737. * The viewport value. This value is in physical pixels meaning it incorporates
  20738. * the renderer's pixel ratio. The viewport property of render targets or
  20739. * the renderer is in logical pixels.
  20740. *
  20741. * @type {Vector4}
  20742. */
  20743. this.viewportValue = new Vector4();
  20744. /**
  20745. * When the scissor test is active and scissor rectangle smaller than the
  20746. * framebuffers dimensions, this property is to `true` by the renderer.
  20747. *
  20748. * @type {boolean}
  20749. * @default false
  20750. */
  20751. this.scissor = false;
  20752. /**
  20753. * The scissor rectangle.
  20754. *
  20755. * @type {Vector4}
  20756. */
  20757. this.scissorValue = new Vector4();
  20758. /**
  20759. * The active render target.
  20760. *
  20761. * @type {?RenderTarget}
  20762. * @default null
  20763. */
  20764. this.renderTarget = null;
  20765. /**
  20766. * The textures of the active render target.
  20767. * `null` when no render target is set.
  20768. *
  20769. * @type {?Array<Texture>}
  20770. * @default null
  20771. */
  20772. this.textures = null;
  20773. /**
  20774. * The depth texture of the active render target.
  20775. * `null` when no render target is set.
  20776. *
  20777. * @type {?DepthTexture}
  20778. * @default null
  20779. */
  20780. this.depthTexture = null;
  20781. /**
  20782. * The active cube face.
  20783. *
  20784. * @type {number}
  20785. * @default 0
  20786. */
  20787. this.activeCubeFace = 0;
  20788. /**
  20789. * The active mipmap level.
  20790. *
  20791. * @type {number}
  20792. * @default 0
  20793. */
  20794. this.activeMipmapLevel = 0;
  20795. /**
  20796. * The number of MSAA samples. This value is always `1` when
  20797. * MSAA isn't used.
  20798. *
  20799. * @type {number}
  20800. * @default 1
  20801. */
  20802. this.sampleCount = 1;
  20803. /**
  20804. * The active render target's width in physical pixels.
  20805. *
  20806. * @type {number}
  20807. * @default 0
  20808. */
  20809. this.width = 0;
  20810. /**
  20811. * The active render target's height in physical pixels.
  20812. *
  20813. * @type {number}
  20814. * @default 0
  20815. */
  20816. this.height = 0;
  20817. /**
  20818. * The occlusion query count.
  20819. *
  20820. * @type {number}
  20821. * @default 0
  20822. */
  20823. this.occlusionQueryCount = 0;
  20824. /**
  20825. * The current clipping context.
  20826. *
  20827. * @type {?ClippingContext}
  20828. * @default null
  20829. */
  20830. this.clippingContext = null;
  20831. /**
  20832. * This flag can be used for type testing.
  20833. *
  20834. * @type {boolean}
  20835. * @readonly
  20836. * @default true
  20837. */
  20838. this.isRenderContext = true;
  20839. }
  20840. /**
  20841. * Returns the cache key of this render context.
  20842. *
  20843. * @return {number} The cache key.
  20844. */
  20845. getCacheKey() {
  20846. return getCacheKey( this );
  20847. }
  20848. }
  20849. /**
  20850. * Computes a cache key for the given render context. This key
  20851. * should identify the render target state so it is possible to
  20852. * configure the correct attachments in the respective backend.
  20853. *
  20854. * @param {RenderContext} renderContext - The render context.
  20855. * @return {number} The cache key.
  20856. */
  20857. function getCacheKey( renderContext ) {
  20858. const { textures, activeCubeFace } = renderContext;
  20859. const values = [ activeCubeFace ];
  20860. for ( const texture of textures ) {
  20861. values.push( texture.id );
  20862. }
  20863. return hashArray( values );
  20864. }
  20865. const _chainKeys$3 = [];
  20866. const _defaultScene = /*@__PURE__*/ new Scene();
  20867. const _defaultCamera = /*@__PURE__*/ new Camera();
  20868. /**
  20869. * This module manages the render contexts of the renderer.
  20870. *
  20871. * @private
  20872. */
  20873. class RenderContexts {
  20874. /**
  20875. * Constructs a new render context management component.
  20876. */
  20877. constructor() {
  20878. /**
  20879. * A dictionary that manages render contexts in chain maps
  20880. * for each attachment state.
  20881. *
  20882. * @type {Object<string,ChainMap>}
  20883. */
  20884. this.chainMaps = {};
  20885. }
  20886. /**
  20887. * Returns a render context for the given scene, camera and render target.
  20888. *
  20889. * @param {Scene} scene - The scene.
  20890. * @param {Camera} camera - The camera that is used to render the scene.
  20891. * @param {?RenderTarget} [renderTarget=null] - The active render target.
  20892. * @return {RenderContext} The render context.
  20893. */
  20894. get( scene, camera, renderTarget = null ) {
  20895. _chainKeys$3[ 0 ] = scene;
  20896. _chainKeys$3[ 1 ] = camera;
  20897. let attachmentState;
  20898. if ( renderTarget === null ) {
  20899. attachmentState = 'default';
  20900. } else {
  20901. const format = renderTarget.texture.format;
  20902. const count = renderTarget.textures.length;
  20903. attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  20904. }
  20905. const chainMap = this._getChainMap( attachmentState );
  20906. let renderState = chainMap.get( _chainKeys$3 );
  20907. if ( renderState === undefined ) {
  20908. renderState = new RenderContext();
  20909. chainMap.set( _chainKeys$3, renderState );
  20910. }
  20911. _chainKeys$3.length = 0;
  20912. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  20913. return renderState;
  20914. }
  20915. /**
  20916. * Returns a render context intended for clear operations.
  20917. *
  20918. * @param {?RenderTarget} [renderTarget=null] - The active render target.
  20919. * @return {RenderContext} The render context.
  20920. */
  20921. getForClear( renderTarget = null ) {
  20922. return this.get( _defaultScene, _defaultCamera, renderTarget );
  20923. }
  20924. /**
  20925. * Returns a chain map for the given attachment state.
  20926. *
  20927. * @private
  20928. * @param {string} attachmentState - The attachment state.
  20929. * @return {ChainMap} The chain map.
  20930. */
  20931. _getChainMap( attachmentState ) {
  20932. return this.chainMaps[ attachmentState ] || ( this.chainMaps[ attachmentState ] = new ChainMap() );
  20933. }
  20934. /**
  20935. * Frees internal resources.
  20936. */
  20937. dispose() {
  20938. this.chainMaps = {};
  20939. }
  20940. }
  20941. const _size$3 = /*@__PURE__*/ new Vector3();
  20942. /**
  20943. * This module manages the textures of the renderer.
  20944. *
  20945. * @private
  20946. * @augments DataMap
  20947. */
  20948. class Textures extends DataMap {
  20949. /**
  20950. * Constructs a new texture management component.
  20951. *
  20952. * @param {Renderer} renderer - The renderer.
  20953. * @param {Backend} backend - The renderer's backend.
  20954. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  20955. */
  20956. constructor( renderer, backend, info ) {
  20957. super();
  20958. /**
  20959. * The renderer.
  20960. *
  20961. * @type {Renderer}
  20962. */
  20963. this.renderer = renderer;
  20964. /**
  20965. * The backend.
  20966. *
  20967. * @type {Backend}
  20968. */
  20969. this.backend = backend;
  20970. /**
  20971. * Renderer component for managing metrics and monitoring data.
  20972. *
  20973. * @type {Info}
  20974. */
  20975. this.info = info;
  20976. }
  20977. /**
  20978. * Updates the given render target. Based on the given render target configuration,
  20979. * it updates the texture states representing the attachments of the framebuffer.
  20980. *
  20981. * @param {RenderTarget} renderTarget - The render target to update.
  20982. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  20983. */
  20984. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  20985. const renderTargetData = this.get( renderTarget );
  20986. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  20987. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  20988. const textures = renderTarget.textures;
  20989. const size = this.getSize( textures[ 0 ] );
  20990. const mipWidth = size.width >> activeMipmapLevel;
  20991. const mipHeight = size.height >> activeMipmapLevel;
  20992. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  20993. const useDepthTexture = renderTarget.depthBuffer === true || renderTarget.stencilBuffer === true;
  20994. let textureNeedsUpdate = false;
  20995. if ( depthTexture === undefined && useDepthTexture ) {
  20996. depthTexture = new DepthTexture();
  20997. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  20998. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  20999. depthTexture.image.width = mipWidth;
  21000. depthTexture.image.height = mipHeight;
  21001. depthTexture.image.depth = size.depth;
  21002. depthTexture.isArrayTexture = renderTarget.multiview === true && size.depth > 1;
  21003. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  21004. }
  21005. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  21006. textureNeedsUpdate = true;
  21007. if ( depthTexture ) {
  21008. depthTexture.needsUpdate = true;
  21009. depthTexture.image.width = mipWidth;
  21010. depthTexture.image.height = mipHeight;
  21011. depthTexture.image.depth = depthTexture.isArrayTexture ? depthTexture.image.depth : 1;
  21012. }
  21013. }
  21014. renderTargetData.width = size.width;
  21015. renderTargetData.height = size.height;
  21016. renderTargetData.textures = textures;
  21017. renderTargetData.depthTexture = depthTexture || null;
  21018. renderTargetData.depth = renderTarget.depthBuffer;
  21019. renderTargetData.stencil = renderTarget.stencilBuffer;
  21020. renderTargetData.renderTarget = renderTarget;
  21021. if ( renderTargetData.sampleCount !== sampleCount ) {
  21022. textureNeedsUpdate = true;
  21023. if ( depthTexture ) {
  21024. depthTexture.needsUpdate = true;
  21025. }
  21026. renderTargetData.sampleCount = sampleCount;
  21027. }
  21028. //
  21029. const options = { sampleCount };
  21030. // XR render targets require no texture updates
  21031. if ( renderTarget.isXRRenderTarget !== true ) {
  21032. for ( let i = 0; i < textures.length; i ++ ) {
  21033. const texture = textures[ i ];
  21034. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  21035. this.updateTexture( texture, options );
  21036. }
  21037. if ( depthTexture ) {
  21038. this.updateTexture( depthTexture, options );
  21039. }
  21040. }
  21041. // dispose handler
  21042. if ( renderTargetData.initialized !== true ) {
  21043. renderTargetData.initialized = true;
  21044. // dispose
  21045. const onDispose = () => {
  21046. renderTarget.removeEventListener( 'dispose', onDispose );
  21047. for ( let i = 0; i < textures.length; i ++ ) {
  21048. this._destroyTexture( textures[ i ] );
  21049. }
  21050. if ( depthTexture ) {
  21051. this._destroyTexture( depthTexture );
  21052. }
  21053. this.delete( renderTarget );
  21054. };
  21055. renderTarget.addEventListener( 'dispose', onDispose );
  21056. }
  21057. }
  21058. /**
  21059. * Updates the given texture. Depending on the texture state, this method
  21060. * triggers the upload of texture data to the GPU memory. If the texture data are
  21061. * not yet ready for the upload, it uses default texture data for as a placeholder.
  21062. *
  21063. * @param {Texture} texture - The texture to update.
  21064. * @param {Object} [options={}] - The options.
  21065. */
  21066. updateTexture( texture, options = {} ) {
  21067. const textureData = this.get( texture );
  21068. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  21069. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  21070. const backend = this.backend;
  21071. if ( isRenderTarget && textureData.initialized === true ) {
  21072. // it's an update
  21073. backend.destroySampler( texture );
  21074. backend.destroyTexture( texture );
  21075. }
  21076. //
  21077. if ( texture.isFramebufferTexture ) {
  21078. const renderTarget = this.renderer.getRenderTarget();
  21079. if ( renderTarget ) {
  21080. texture.type = renderTarget.texture.type;
  21081. } else {
  21082. texture.type = UnsignedByteType;
  21083. }
  21084. }
  21085. //
  21086. const { width, height, depth } = this.getSize( texture );
  21087. options.width = width;
  21088. options.height = height;
  21089. options.depth = depth;
  21090. options.needsMipmaps = this.needsMipmaps( texture );
  21091. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  21092. //
  21093. if ( isRenderTarget || texture.isStorageTexture === true ) {
  21094. backend.createSampler( texture );
  21095. backend.createTexture( texture, options );
  21096. textureData.generation = texture.version;
  21097. } else {
  21098. const needsCreate = textureData.initialized !== true;
  21099. if ( needsCreate ) backend.createSampler( texture );
  21100. if ( texture.version > 0 ) {
  21101. const image = texture.image;
  21102. if ( image === undefined ) {
  21103. console.warn( 'THREE.Renderer: Texture marked for update but image is undefined.' );
  21104. } else if ( image.complete === false ) {
  21105. console.warn( 'THREE.Renderer: Texture marked for update but image is incomplete.' );
  21106. } else {
  21107. if ( texture.images ) {
  21108. const images = [];
  21109. for ( const image of texture.images ) {
  21110. images.push( image );
  21111. }
  21112. options.images = images;
  21113. } else {
  21114. options.image = image;
  21115. }
  21116. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  21117. backend.createTexture( texture, options );
  21118. textureData.isDefaultTexture = false;
  21119. textureData.generation = texture.version;
  21120. }
  21121. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  21122. if ( options.needsMipmaps && texture.mipmaps.length === 0 ) backend.generateMipmaps( texture );
  21123. }
  21124. } else {
  21125. // async update
  21126. backend.createDefaultTexture( texture );
  21127. textureData.isDefaultTexture = true;
  21128. textureData.generation = texture.version;
  21129. }
  21130. }
  21131. // dispose handler
  21132. if ( textureData.initialized !== true ) {
  21133. textureData.initialized = true;
  21134. textureData.generation = texture.version;
  21135. //
  21136. this.info.memory.textures ++;
  21137. // dispose
  21138. const onDispose = () => {
  21139. texture.removeEventListener( 'dispose', onDispose );
  21140. this._destroyTexture( texture );
  21141. };
  21142. texture.addEventListener( 'dispose', onDispose );
  21143. }
  21144. //
  21145. textureData.version = texture.version;
  21146. }
  21147. /**
  21148. * Computes the size of the given texture and writes the result
  21149. * into the target vector. This vector is also returned by the
  21150. * method.
  21151. *
  21152. * If no texture data are available for the compute yet, the method
  21153. * returns default size values.
  21154. *
  21155. * @param {Texture} texture - The texture to compute the size for.
  21156. * @param {Vector3} target - The target vector.
  21157. * @return {Vector3} The target vector.
  21158. */
  21159. getSize( texture, target = _size$3 ) {
  21160. let image = texture.images ? texture.images[ 0 ] : texture.image;
  21161. if ( image ) {
  21162. if ( image.image !== undefined ) image = image.image;
  21163. target.width = image.width || 1;
  21164. target.height = image.height || 1;
  21165. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  21166. } else {
  21167. target.width = target.height = target.depth = 1;
  21168. }
  21169. return target;
  21170. }
  21171. /**
  21172. * Computes the number of mipmap levels for the given texture.
  21173. *
  21174. * @param {Texture} texture - The texture.
  21175. * @param {number} width - The texture's width.
  21176. * @param {number} height - The texture's height.
  21177. * @return {number} The number of mipmap levels.
  21178. */
  21179. getMipLevels( texture, width, height ) {
  21180. let mipLevelCount;
  21181. if ( texture.isCompressedTexture ) {
  21182. if ( texture.mipmaps ) {
  21183. mipLevelCount = texture.mipmaps.length;
  21184. } else {
  21185. mipLevelCount = 1;
  21186. }
  21187. } else {
  21188. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  21189. }
  21190. return mipLevelCount;
  21191. }
  21192. /**
  21193. * Returns `true` if the given texture requires mipmaps.
  21194. *
  21195. * @param {Texture} texture - The texture.
  21196. * @return {boolean} Whether mipmaps are required or not.
  21197. */
  21198. needsMipmaps( texture ) {
  21199. return texture.isCompressedTexture === true || texture.generateMipmaps;
  21200. }
  21201. /**
  21202. * Frees internal resource when the given texture isn't
  21203. * required anymore.
  21204. *
  21205. * @param {Texture} texture - The texture to destroy.
  21206. */
  21207. _destroyTexture( texture ) {
  21208. if ( this.has( texture ) === true ) {
  21209. this.backend.destroySampler( texture );
  21210. this.backend.destroyTexture( texture );
  21211. this.delete( texture );
  21212. this.info.memory.textures --;
  21213. }
  21214. }
  21215. }
  21216. /**
  21217. * A four-component version of {@link Color} which is internally
  21218. * used by the renderer to represents clear color with alpha as
  21219. * one object.
  21220. *
  21221. * @private
  21222. * @augments Color
  21223. */
  21224. class Color4 extends Color {
  21225. /**
  21226. * Constructs a new four-component color.
  21227. * You can also pass a single THREE.Color, hex or
  21228. * string argument to this constructor.
  21229. *
  21230. * @param {number|string} [r=1] - The red value.
  21231. * @param {number} [g=1] - The green value.
  21232. * @param {number} [b=1] - The blue value.
  21233. * @param {number} [a=1] - The alpha value.
  21234. */
  21235. constructor( r, g, b, a = 1 ) {
  21236. super( r, g, b );
  21237. this.a = a;
  21238. }
  21239. /**
  21240. * Overwrites the default to honor alpha.
  21241. * You can also pass a single THREE.Color, hex or
  21242. * string argument to this method.
  21243. *
  21244. * @param {number|string|Color} r - The red value.
  21245. * @param {number} g - The green value.
  21246. * @param {number} b - The blue value.
  21247. * @param {number} [a=1] - The alpha value.
  21248. * @return {Color4} A reference to this object.
  21249. */
  21250. set( r, g, b, a = 1 ) {
  21251. this.a = a;
  21252. return super.set( r, g, b );
  21253. }
  21254. /**
  21255. * Overwrites the default to honor alpha.
  21256. *
  21257. * @param {Color4} color - The color to copy.
  21258. * @return {Color4} A reference to this object.
  21259. */
  21260. copy( color ) {
  21261. if ( color.a !== undefined ) this.a = color.a;
  21262. return super.copy( color );
  21263. }
  21264. /**
  21265. * Overwrites the default to honor alpha.
  21266. *
  21267. * @return {Color4} The cloned color.
  21268. */
  21269. clone() {
  21270. return new this.constructor( this.r, this.g, this.b, this.a );
  21271. }
  21272. }
  21273. /**
  21274. * Special version of {@link PropertyNode} which is used for parameters.
  21275. *
  21276. * @augments PropertyNode
  21277. */
  21278. class ParameterNode extends PropertyNode {
  21279. static get type() {
  21280. return 'ParameterNode';
  21281. }
  21282. /**
  21283. * Constructs a new parameter node.
  21284. *
  21285. * @param {string} nodeType - The type of the node.
  21286. * @param {?string} [name=null] - The name of the parameter in the shader.
  21287. */
  21288. constructor( nodeType, name = null ) {
  21289. super( nodeType, name );
  21290. /**
  21291. * This flag can be used for type testing.
  21292. *
  21293. * @type {boolean}
  21294. * @readonly
  21295. * @default true
  21296. */
  21297. this.isParameterNode = true;
  21298. }
  21299. getHash() {
  21300. return this.uuid;
  21301. }
  21302. generate() {
  21303. return this.name;
  21304. }
  21305. }
  21306. /**
  21307. * TSL function for creating a parameter node.
  21308. *
  21309. * @tsl
  21310. * @function
  21311. * @param {string} type - The type of the node.
  21312. * @param {?string} name - The name of the parameter in the shader.
  21313. * @returns {ParameterNode}
  21314. */
  21315. const parameter = ( type, name ) => nodeObject( new ParameterNode( type, name ) );
  21316. /**
  21317. * Stack is a helper for Nodes that need to produce stack-based code instead of continuous flow.
  21318. * They are usually needed in cases like `If`, `Else`.
  21319. *
  21320. * @augments Node
  21321. */
  21322. class StackNode extends Node {
  21323. static get type() {
  21324. return 'StackNode';
  21325. }
  21326. /**
  21327. * Constructs a new stack node.
  21328. *
  21329. * @param {?StackNode} [parent=null] - The parent stack node.
  21330. */
  21331. constructor( parent = null ) {
  21332. super();
  21333. /**
  21334. * List of nodes.
  21335. *
  21336. * @type {Array<Node>}
  21337. */
  21338. this.nodes = [];
  21339. /**
  21340. * The output node.
  21341. *
  21342. * @type {?Node}
  21343. * @default null
  21344. */
  21345. this.outputNode = null;
  21346. /**
  21347. * The parent stack node.
  21348. *
  21349. * @type {?StackNode}
  21350. * @default null
  21351. */
  21352. this.parent = parent;
  21353. /**
  21354. * The current conditional node.
  21355. *
  21356. * @private
  21357. * @type {ConditionalNode}
  21358. * @default null
  21359. */
  21360. this._currentCond = null;
  21361. /**
  21362. * The expression node. Only
  21363. * relevant for Switch/Case.
  21364. *
  21365. * @private
  21366. * @type {Node}
  21367. * @default null
  21368. */
  21369. this._expressionNode = null;
  21370. /**
  21371. * This flag can be used for type testing.
  21372. *
  21373. * @type {boolean}
  21374. * @readonly
  21375. * @default true
  21376. */
  21377. this.isStackNode = true;
  21378. }
  21379. getNodeType( builder ) {
  21380. return this.outputNode ? this.outputNode.getNodeType( builder ) : 'void';
  21381. }
  21382. getMemberType( builder, name ) {
  21383. return this.outputNode ? this.outputNode.getMemberType( builder, name ) : 'void';
  21384. }
  21385. /**
  21386. * Adds a node to this stack.
  21387. *
  21388. * @param {Node} node - The node to add.
  21389. * @return {StackNode} A reference to this stack node.
  21390. */
  21391. add( node ) {
  21392. this.nodes.push( node );
  21393. return this;
  21394. }
  21395. /**
  21396. * Represent an `if` statement in TSL.
  21397. *
  21398. * @param {Node} boolNode - Represents the condition.
  21399. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  21400. * @return {StackNode} A reference to this stack node.
  21401. */
  21402. If( boolNode, method ) {
  21403. const methodNode = new ShaderNode( method );
  21404. this._currentCond = select( boolNode, methodNode );
  21405. return this.add( this._currentCond );
  21406. }
  21407. /**
  21408. * Represent an `elseif` statement in TSL.
  21409. *
  21410. * @param {Node} boolNode - Represents the condition.
  21411. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  21412. * @return {StackNode} A reference to this stack node.
  21413. */
  21414. ElseIf( boolNode, method ) {
  21415. const methodNode = new ShaderNode( method );
  21416. const ifNode = select( boolNode, methodNode );
  21417. this._currentCond.elseNode = ifNode;
  21418. this._currentCond = ifNode;
  21419. return this;
  21420. }
  21421. /**
  21422. * Represent an `else` statement in TSL.
  21423. *
  21424. * @param {Function} method - TSL code which is executed in the `else` case.
  21425. * @return {StackNode} A reference to this stack node.
  21426. */
  21427. Else( method ) {
  21428. this._currentCond.elseNode = new ShaderNode( method );
  21429. return this;
  21430. }
  21431. /**
  21432. * Represents a `switch` statement in TSL.
  21433. *
  21434. * @param {any} expression - Represents the expression.
  21435. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  21436. * @return {StackNode} A reference to this stack node.
  21437. */
  21438. Switch( expression ) {
  21439. this._expressionNode = nodeObject( expression );
  21440. return this;
  21441. }
  21442. /**
  21443. * Represents a `case` statement in TSL. The TSL version accepts an arbitrary numbers of values.
  21444. * The last parameter must be the callback method that should be executed in the `true` case.
  21445. *
  21446. * @param {...any} params - The values of the `Case()` statement as well as the callback method.
  21447. * @return {StackNode} A reference to this stack node.
  21448. */
  21449. Case( ...params ) {
  21450. const caseNodes = [];
  21451. // extract case nodes from the parameter list
  21452. if ( params.length >= 2 ) {
  21453. for ( let i = 0; i < params.length - 1; i ++ ) {
  21454. caseNodes.push( this._expressionNode.equal( nodeObject( params[ i ] ) ) );
  21455. }
  21456. } else {
  21457. throw new Error( 'TSL: Invalid parameter length. Case() requires at least two parameters.' );
  21458. }
  21459. // extract method
  21460. const method = params[ params.length - 1 ];
  21461. const methodNode = new ShaderNode( method );
  21462. // chain multiple cases when using Case( 1, 2, 3, () => {} )
  21463. let caseNode = caseNodes[ 0 ];
  21464. for ( let i = 1; i < caseNodes.length; i ++ ) {
  21465. caseNode = caseNode.or( caseNodes[ i ] );
  21466. }
  21467. // build condition
  21468. const condNode = select( caseNode, methodNode );
  21469. if ( this._currentCond === null ) {
  21470. this._currentCond = condNode;
  21471. return this.add( this._currentCond );
  21472. } else {
  21473. this._currentCond.elseNode = condNode;
  21474. this._currentCond = condNode;
  21475. return this;
  21476. }
  21477. }
  21478. /**
  21479. * Represents the default code block of a Switch/Case statement.
  21480. *
  21481. * @param {Function} method - TSL code which is executed in the `else` case.
  21482. * @return {StackNode} A reference to this stack node.
  21483. */
  21484. Default( method ) {
  21485. this.Else( method );
  21486. return this;
  21487. }
  21488. build( builder, ...params ) {
  21489. const previousStack = getCurrentStack();
  21490. setCurrentStack( this );
  21491. const buildStage = builder.buildStage;
  21492. for ( const node of this.nodes ) {
  21493. if ( buildStage === 'setup' ) {
  21494. node.build( builder );
  21495. } else if ( buildStage === 'analyze' ) {
  21496. node.build( builder, this );
  21497. } else if ( buildStage === 'generate' ) {
  21498. const stages = builder.getDataFromNode( node, 'any' ).stages;
  21499. const parents = stages && stages[ builder.shaderStage ];
  21500. if ( node.isVarNode && parents && parents.length === 1 && parents[ 0 ] && parents[ 0 ].isStackNode ) {
  21501. continue; // skip var nodes that are only used in .toVarying()
  21502. }
  21503. node.build( builder, 'void' );
  21504. }
  21505. }
  21506. setCurrentStack( previousStack );
  21507. return this.outputNode ? this.outputNode.build( builder, ...params ) : super.build( builder, ...params );
  21508. }
  21509. // Deprecated
  21510. /**
  21511. * @function
  21512. * @deprecated since r168. Use {@link StackNode#Else} instead.
  21513. *
  21514. * @param {...any} params
  21515. * @returns {StackNode}
  21516. */
  21517. else( ...params ) { // @deprecated, r168
  21518. console.warn( 'THREE.TSL: .else() has been renamed to .Else().' );
  21519. return this.Else( ...params );
  21520. }
  21521. /**
  21522. * @deprecated since r168. Use {@link StackNode#ElseIf} instead.
  21523. *
  21524. * @param {...any} params
  21525. * @returns {StackNode}
  21526. */
  21527. elseif( ...params ) { // @deprecated, r168
  21528. console.warn( 'THREE.TSL: .elseif() has been renamed to .ElseIf().' );
  21529. return this.ElseIf( ...params );
  21530. }
  21531. }
  21532. /**
  21533. * TSL function for creating a stack node.
  21534. *
  21535. * @tsl
  21536. * @function
  21537. * @param {?StackNode} [parent=null] - The parent stack node.
  21538. * @returns {StackNode}
  21539. */
  21540. const stack = /*@__PURE__*/ nodeProxy( StackNode ).setParameterLength( 0, 1 );
  21541. /**
  21542. * Generates a layout for struct members.
  21543. * This function takes an object representing struct members and returns an array of member layouts.
  21544. * Each member layout includes the member's name, type, and whether it is atomic.
  21545. *
  21546. * @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.
  21547. * @returns {Array.<{name: string, type: string, atomic: boolean}>} An array of member layouts.
  21548. */
  21549. function getMembersLayout( members ) {
  21550. return Object.entries( members ).map( ( [ name, value ] ) => {
  21551. if ( typeof value === 'string' ) {
  21552. return { name, type: value, atomic: false };
  21553. }
  21554. return { name, type: value.type, atomic: value.atomic || false };
  21555. } );
  21556. }
  21557. /**
  21558. * Represents a struct type node in the node-based system.
  21559. * This class is used to define and manage the layout and types of struct members.
  21560. * It extends the base Node class and provides methods to get the length of the struct,
  21561. * retrieve member types, and generate the struct type for a builder.
  21562. *
  21563. * @augments Node
  21564. */
  21565. class StructTypeNode extends Node {
  21566. static get type() {
  21567. return 'StructTypeNode';
  21568. }
  21569. /**
  21570. * Creates an instance of StructTypeNode.
  21571. *
  21572. * @param {Object} membersLayout - The layout of the members for the struct.
  21573. * @param {?string} [name=null] - The optional name of the struct.
  21574. */
  21575. constructor( membersLayout, name = null ) {
  21576. super( 'struct' );
  21577. /**
  21578. * The layout of the members for the struct
  21579. *
  21580. * @type {Array.<{name: string, type: string, atomic: boolean}>}
  21581. */
  21582. this.membersLayout = getMembersLayout( membersLayout );
  21583. /**
  21584. * The name of the struct.
  21585. *
  21586. * @type {?string}
  21587. * @default null
  21588. */
  21589. this.name = name;
  21590. /**
  21591. * This flag can be used for type testing.
  21592. *
  21593. * @type {boolean}
  21594. * @readonly
  21595. * @default true
  21596. */
  21597. this.isStructLayoutNode = true;
  21598. }
  21599. /**
  21600. * Returns the length of the struct.
  21601. * The length is calculated by summing the lengths of the struct's members.
  21602. *
  21603. * @returns {number} The length of the struct.
  21604. */
  21605. getLength() {
  21606. const GPU_CHUNK_BYTES = 8;
  21607. const BYTES_PER_ELEMENT = Float32Array.BYTES_PER_ELEMENT;
  21608. let offset = 0; // global buffer offset in bytes
  21609. for ( const member of this.membersLayout ) {
  21610. const type = member.type;
  21611. const itemSize = getMemoryLengthFromType( type ) * BYTES_PER_ELEMENT;
  21612. const boundary = getByteBoundaryFromType( type );
  21613. const chunkOffset = offset % GPU_CHUNK_BYTES; // offset in the current chunk
  21614. const chunkPadding = chunkOffset % boundary; // required padding to match boundary
  21615. const chunkStart = chunkOffset + chunkPadding; // start position in the current chunk for the data
  21616. offset += chunkPadding;
  21617. // Check for chunk overflow
  21618. if ( chunkStart !== 0 && ( GPU_CHUNK_BYTES - chunkStart ) < itemSize ) {
  21619. // Add padding to the end of the chunk
  21620. offset += ( GPU_CHUNK_BYTES - chunkStart );
  21621. }
  21622. offset += itemSize;
  21623. }
  21624. return ( Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES ) / BYTES_PER_ELEMENT;
  21625. }
  21626. getMemberType( builder, name ) {
  21627. const member = this.membersLayout.find( m => m.name === name );
  21628. return member ? member.type : 'void';
  21629. }
  21630. getNodeType( builder ) {
  21631. const structType = builder.getStructTypeFromNode( this, this.membersLayout, this.name );
  21632. return structType.name;
  21633. }
  21634. setup( builder ) {
  21635. builder.addInclude( this );
  21636. }
  21637. generate( builder ) {
  21638. return this.getNodeType( builder );
  21639. }
  21640. }
  21641. /**
  21642. * StructNode allows to create custom structures with multiple members.
  21643. * This can also be used to define structures in attribute and uniform data.
  21644. *
  21645. * ```js
  21646. * // Define a custom struct
  21647. * const BoundingBox = struct( { min: 'vec3', max: 'vec3' } );
  21648. *
  21649. * // Create a new instance of the struct
  21650. * const bb = BoundingBox( vec3( 0 ), vec3( 1 ) ); // style 1
  21651. * const bb = BoundingBox( { min: vec3( 0 ), max: vec3( 1 ) } ); // style 2
  21652. *
  21653. * // Access the struct members
  21654. * const min = bb.get( 'min' );
  21655. *
  21656. * // Assign a new value to a member
  21657. * min.assign( vec3() );
  21658. * ```
  21659. * @augments Node
  21660. */
  21661. class StructNode extends Node {
  21662. static get type() {
  21663. return 'StructNode';
  21664. }
  21665. constructor( structLayoutNode, values ) {
  21666. super( 'vec3' );
  21667. this.structLayoutNode = structLayoutNode;
  21668. this.values = values;
  21669. this.isStructNode = true;
  21670. }
  21671. getNodeType( builder ) {
  21672. return this.structLayoutNode.getNodeType( builder );
  21673. }
  21674. getMemberType( builder, name ) {
  21675. return this.structLayoutNode.getMemberType( builder, name );
  21676. }
  21677. generate( builder ) {
  21678. const nodeVar = builder.getVarFromNode( this );
  21679. const structType = nodeVar.type;
  21680. const propertyName = builder.getPropertyName( nodeVar );
  21681. builder.addLineFlowCode( `${ propertyName } = ${ builder.generateStruct( structType, this.structLayoutNode.membersLayout, this.values ) }`, this );
  21682. return nodeVar.name;
  21683. }
  21684. }
  21685. /**
  21686. * TSL function for creating a struct node.
  21687. *
  21688. * @tsl
  21689. * @function
  21690. * @param {Object} membersLayout - The layout of the struct members.
  21691. * @param {?string} [name=null] - The name of the struct.
  21692. * @returns {Function} The struct function.
  21693. */
  21694. const struct = ( membersLayout, name = null ) => {
  21695. const structLayout = new StructTypeNode( membersLayout, name );
  21696. const struct = ( ...params ) => {
  21697. let values = null;
  21698. if ( params.length > 0 ) {
  21699. if ( params[ 0 ].isNode ) {
  21700. values = {};
  21701. const names = Object.keys( membersLayout );
  21702. for ( let i = 0; i < params.length; i ++ ) {
  21703. values[ names[ i ] ] = params[ i ];
  21704. }
  21705. } else {
  21706. values = params[ 0 ];
  21707. }
  21708. }
  21709. return nodeObject( new StructNode( structLayout, values ) );
  21710. };
  21711. struct.layout = structLayout;
  21712. struct.isStruct = true;
  21713. return struct;
  21714. };
  21715. /**
  21716. * This node can be used to define multiple outputs in a shader programs.
  21717. *
  21718. * @augments Node
  21719. */
  21720. class OutputStructNode extends Node {
  21721. static get type() {
  21722. return 'OutputStructNode';
  21723. }
  21724. /**
  21725. * Constructs a new output struct node. The constructor can be invoked with an
  21726. * arbitrary number of nodes representing the members.
  21727. *
  21728. * @param {...Node} members - A parameter list of nodes.
  21729. */
  21730. constructor( ...members ) {
  21731. super();
  21732. /**
  21733. * An array of nodes which defines the output.
  21734. *
  21735. * @type {Array<Node>}
  21736. */
  21737. this.members = members;
  21738. /**
  21739. * This flag can be used for type testing.
  21740. *
  21741. * @type {boolean}
  21742. * @readonly
  21743. * @default true
  21744. */
  21745. this.isOutputStructNode = true;
  21746. }
  21747. getNodeType( builder ) {
  21748. const properties = builder.getNodeProperties( this );
  21749. if ( properties.membersLayout === undefined ) {
  21750. const members = this.members;
  21751. const membersLayout = [];
  21752. for ( let i = 0; i < members.length; i ++ ) {
  21753. const name = 'm' + i;
  21754. const type = members[ i ].getNodeType( builder );
  21755. membersLayout.push( { name, type, index: i } );
  21756. }
  21757. properties.membersLayout = membersLayout;
  21758. properties.structType = builder.getOutputStructTypeFromNode( this, properties.membersLayout );
  21759. }
  21760. return properties.structType.name;
  21761. }
  21762. generate( builder ) {
  21763. const propertyName = builder.getOutputStructName();
  21764. const members = this.members;
  21765. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  21766. for ( let i = 0; i < members.length; i ++ ) {
  21767. const snippet = members[ i ].build( builder );
  21768. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }`, this );
  21769. }
  21770. return propertyName;
  21771. }
  21772. }
  21773. /**
  21774. * TSL function for creating an output struct node.
  21775. *
  21776. * @tsl
  21777. * @function
  21778. * @param {...Node} members - A parameter list of nodes.
  21779. * @returns {OutputStructNode}
  21780. */
  21781. const outputStruct = /*@__PURE__*/ nodeProxy( OutputStructNode );
  21782. /**
  21783. * Returns the MRT texture index for the given name.
  21784. *
  21785. * @param {Array<Texture>} textures - The textures of a MRT-configured render target.
  21786. * @param {string} name - The name of the MRT texture which index is requested.
  21787. * @return {number} The texture index.
  21788. */
  21789. function getTextureIndex( textures, name ) {
  21790. for ( let i = 0; i < textures.length; i ++ ) {
  21791. if ( textures[ i ].name === name ) {
  21792. return i;
  21793. }
  21794. }
  21795. return -1;
  21796. }
  21797. /**
  21798. * This node can be used setup a MRT context for rendering. A typical MRT setup for
  21799. * post-processing is shown below:
  21800. * ```js
  21801. * const mrtNode = mrt( {
  21802. * output: output,
  21803. * normal: normalView
  21804. * } ) );
  21805. * ```
  21806. * The MRT output is defined as a dictionary.
  21807. *
  21808. * @augments OutputStructNode
  21809. */
  21810. class MRTNode extends OutputStructNode {
  21811. static get type() {
  21812. return 'MRTNode';
  21813. }
  21814. /**
  21815. * Constructs a new output struct node.
  21816. *
  21817. * @param {Object<string, Node>} outputNodes - The MRT outputs.
  21818. */
  21819. constructor( outputNodes ) {
  21820. super();
  21821. /**
  21822. * A dictionary representing the MRT outputs. The key
  21823. * is the name of the output, the value the node which produces
  21824. * the output result.
  21825. *
  21826. * @type {Object<string, Node>}
  21827. */
  21828. this.outputNodes = outputNodes;
  21829. /**
  21830. * This flag can be used for type testing.
  21831. *
  21832. * @type {boolean}
  21833. * @readonly
  21834. * @default true
  21835. */
  21836. this.isMRTNode = true;
  21837. }
  21838. /**
  21839. * Returns `true` if the MRT node has an output with the given name.
  21840. *
  21841. * @param {string} name - The name of the output.
  21842. * @return {NodeBuilder} Whether the MRT node has an output for the given name or not.
  21843. */
  21844. has( name ) {
  21845. return this.outputNodes[ name ] !== undefined;
  21846. }
  21847. /**
  21848. * Returns the output node for the given name.
  21849. *
  21850. * @param {string} name - The name of the output.
  21851. * @return {Node} The output node.
  21852. */
  21853. get( name ) {
  21854. return this.outputNodes[ name ];
  21855. }
  21856. /**
  21857. * Merges the outputs of the given MRT node with the outputs of this node.
  21858. *
  21859. * @param {MRTNode} mrtNode - The MRT to merge.
  21860. * @return {MRTNode} A new MRT node with merged outputs..
  21861. */
  21862. merge( mrtNode ) {
  21863. const outputs = { ...this.outputNodes, ...mrtNode.outputNodes };
  21864. return mrt( outputs );
  21865. }
  21866. setup( builder ) {
  21867. const outputNodes = this.outputNodes;
  21868. const mrt = builder.renderer.getRenderTarget();
  21869. const members = [];
  21870. const textures = mrt.textures;
  21871. for ( const name in outputNodes ) {
  21872. const index = getTextureIndex( textures, name );
  21873. members[ index ] = vec4( outputNodes[ name ] );
  21874. }
  21875. this.members = members;
  21876. return super.setup( builder );
  21877. }
  21878. }
  21879. /**
  21880. * TSL function for creating a MRT node.
  21881. *
  21882. * @tsl
  21883. * @function
  21884. * @param {Object<string, Node>} outputNodes - The MRT outputs.
  21885. * @returns {MRTNode}
  21886. */
  21887. const mrt = /*@__PURE__*/ nodeProxy( MRTNode );
  21888. /**
  21889. * Generates a hash value in the range `[0, 1]` from the given seed.
  21890. *
  21891. * @tsl
  21892. * @function
  21893. * @param {Node<float>} seed - The seed.
  21894. * @return {Node<float>} The hash value.
  21895. */
  21896. const hash = /*@__PURE__*/ Fn( ( [ seed ] ) => {
  21897. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  21898. const state = seed.toUint().mul( 747796405 ).add( 2891336453 );
  21899. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  21900. const result = word.shiftRight( 22 ).bitXor( word );
  21901. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  21902. } );
  21903. /**
  21904. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  21905. * The corners are mapped to `0` and the center to `1`.
  21906. * Reference: {@link https://iquilezles.org/articles/functions/}.
  21907. *
  21908. * @tsl
  21909. * @function
  21910. * @param {Node<float>} x - The value to remap.
  21911. * @param {Node<float>} k - Allows to control the remapping functions shape by rising the parabola to a power `k`.
  21912. * @return {Node<float>} The remapped value.
  21913. */
  21914. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  21915. /**
  21916. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  21917. * Expands the sides and compresses the center, and keeps `0.5` mapped to `0.5`.
  21918. * Reference: {@link https://iquilezles.org/articles/functions/}.
  21919. *
  21920. * @tsl
  21921. * @function
  21922. * @param {Node<float>} x - The value to remap.
  21923. * @param {Node<float>} k - `k=1` is the identity curve,`k<1` produces the classic `gain()` shape, and `k>1` produces "s" shaped curves.
  21924. * @return {Node<float>} The remapped value.
  21925. */
  21926. 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 ) );
  21927. /**
  21928. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  21929. * A generalization of the `parabola()`. Keeps the corners mapped to 0 but allows the control of the shape one either side of the curve.
  21930. * Reference: {@link https://iquilezles.org/articles/functions/}.
  21931. *
  21932. * @tsl
  21933. * @function
  21934. * @param {Node<float>} x - The value to remap.
  21935. * @param {Node<float>} a - First control parameter.
  21936. * @param {Node<float>} b - Second control parameter.
  21937. * @return {Node<float>} The remapped value.
  21938. */
  21939. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  21940. /**
  21941. * A phase shifted sinus curve that starts at zero and ends at zero, with bouncing behavior.
  21942. * Reference: {@link https://iquilezles.org/articles/functions/}.
  21943. *
  21944. * @tsl
  21945. * @function
  21946. * @param {Node<float>} x - The value to compute the sin for.
  21947. * @param {Node<float>} k - Controls the amount of bounces.
  21948. * @return {Node<float>} The result value.
  21949. */
  21950. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  21951. // https://github.com/cabbibo/glsl-tri-noise-3d
  21952. const tri = /*@__PURE__*/ Fn( ( [ x ] ) => {
  21953. return x.fract().sub( .5 ).abs();
  21954. } ).setLayout( {
  21955. name: 'tri',
  21956. type: 'float',
  21957. inputs: [
  21958. { name: 'x', type: 'float' }
  21959. ]
  21960. } );
  21961. const tri3 = /*@__PURE__*/ Fn( ( [ p ] ) => {
  21962. 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. ) ) ) ) );
  21963. } ).setLayout( {
  21964. name: 'tri3',
  21965. type: 'vec3',
  21966. inputs: [
  21967. { name: 'p', type: 'vec3' }
  21968. ]
  21969. } );
  21970. /**
  21971. * Generates a noise value from the given position, speed and time parameters.
  21972. *
  21973. * @tsl
  21974. * @function
  21975. * @param {Node<vec3>} position - The position.
  21976. * @param {Node<float>} speed - The speed.
  21977. * @param {Node<float>} time - The time.
  21978. * @return {Node<float>} The generated noise.
  21979. */
  21980. const triNoise3D = /*@__PURE__*/ Fn( ( [ position, speed, time ] ) => {
  21981. const p = vec3( position ).toVar();
  21982. const z = float( 1.4 ).toVar();
  21983. const rz = float( 0.0 ).toVar();
  21984. const bp = vec3( p ).toVar();
  21985. Loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  21986. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  21987. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( speed ) ) ) );
  21988. bp.mulAssign( 1.8 );
  21989. z.mulAssign( 1.5 );
  21990. p.mulAssign( 1.2 );
  21991. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  21992. rz.addAssign( t.div( z ) );
  21993. bp.addAssign( 0.14 );
  21994. } );
  21995. return rz;
  21996. } ).setLayout( {
  21997. name: 'triNoise3D',
  21998. type: 'float',
  21999. inputs: [
  22000. { name: 'position', type: 'vec3' },
  22001. { name: 'speed', type: 'float' },
  22002. { name: 'time', type: 'float' }
  22003. ]
  22004. } );
  22005. /**
  22006. * This class allows to define multiple overloaded versions
  22007. * of the same function. Depending on the parameters of the function
  22008. * call, the node picks the best-fit overloaded version.
  22009. *
  22010. * @augments Node
  22011. */
  22012. class FunctionOverloadingNode extends Node {
  22013. static get type() {
  22014. return 'FunctionOverloadingNode';
  22015. }
  22016. /**
  22017. * Constructs a new function overloading node.
  22018. *
  22019. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  22020. * @param {...Node} parametersNodes - A list of parameter nodes.
  22021. */
  22022. constructor( functionNodes = [], ...parametersNodes ) {
  22023. super();
  22024. /**
  22025. * Array of `Fn` function definitions.
  22026. *
  22027. * @type {Array<Function>}
  22028. */
  22029. this.functionNodes = functionNodes;
  22030. /**
  22031. * A list of parameter nodes.
  22032. *
  22033. * @type {Array<Node>}
  22034. */
  22035. this.parametersNodes = parametersNodes;
  22036. /**
  22037. * The selected overloaded function call.
  22038. *
  22039. * @private
  22040. * @type {ShaderCallNodeInternal}
  22041. */
  22042. this._candidateFnCall = null;
  22043. /**
  22044. * This node is marked as global.
  22045. *
  22046. * @type {boolean}
  22047. * @default true
  22048. */
  22049. this.global = true;
  22050. }
  22051. /**
  22052. * This method is overwritten since the node type is inferred from
  22053. * the function's return type.
  22054. *
  22055. * @param {NodeBuilder} builder - The current node builder.
  22056. * @return {string} The node type.
  22057. */
  22058. getNodeType() {
  22059. return this.functionNodes[ 0 ].shaderNode.layout.type;
  22060. }
  22061. setup( builder ) {
  22062. const params = this.parametersNodes;
  22063. let candidateFnCall = this._candidateFnCall;
  22064. if ( candidateFnCall === null ) {
  22065. let candidateFn = null;
  22066. let candidateScore = -1;
  22067. for ( const functionNode of this.functionNodes ) {
  22068. const shaderNode = functionNode.shaderNode;
  22069. const layout = shaderNode.layout;
  22070. if ( layout === null ) {
  22071. throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' );
  22072. }
  22073. const inputs = layout.inputs;
  22074. if ( params.length === inputs.length ) {
  22075. let score = 0;
  22076. for ( let i = 0; i < params.length; i ++ ) {
  22077. const param = params[ i ];
  22078. const input = inputs[ i ];
  22079. if ( param.getNodeType( builder ) === input.type ) {
  22080. score ++;
  22081. } else {
  22082. score = 0;
  22083. }
  22084. }
  22085. if ( score > candidateScore ) {
  22086. candidateFn = functionNode;
  22087. candidateScore = score;
  22088. }
  22089. }
  22090. }
  22091. this._candidateFnCall = candidateFnCall = candidateFn( ...params );
  22092. }
  22093. return candidateFnCall;
  22094. }
  22095. }
  22096. const overloadingBaseFn = /*@__PURE__*/ nodeProxy( FunctionOverloadingNode );
  22097. /**
  22098. * TSL function for creating a function overloading node.
  22099. *
  22100. * @tsl
  22101. * @function
  22102. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  22103. * @returns {FunctionOverloadingNode}
  22104. */
  22105. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  22106. /**
  22107. * Represents the elapsed time in seconds.
  22108. *
  22109. * @tsl
  22110. * @type {UniformNode<float>}
  22111. */
  22112. const time = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.time );
  22113. /**
  22114. * Represents the delta time in seconds.
  22115. *
  22116. * @tsl
  22117. * @type {UniformNode<float>}
  22118. */
  22119. const deltaTime = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.deltaTime );
  22120. /**
  22121. * Represents the current frame ID.
  22122. *
  22123. * @tsl
  22124. * @type {UniformNode<uint>}
  22125. */
  22126. const frameId = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.frameId );
  22127. // Deprecated
  22128. /**
  22129. * @tsl
  22130. * @function
  22131. * @deprecated since r170. Use {@link time} instead.
  22132. *
  22133. * @param {number} [timeScale=1] - The time scale.
  22134. * @returns {UniformNode<float>}
  22135. */
  22136. const timerLocal = ( timeScale = 1 ) => { // @deprecated, r170
  22137. console.warn( 'TSL: timerLocal() is deprecated. Use "time" instead.' );
  22138. return time.mul( timeScale );
  22139. };
  22140. /**
  22141. * @tsl
  22142. * @function
  22143. * @deprecated since r170. Use {@link time} instead.
  22144. *
  22145. * @param {number} [timeScale=1] - The time scale.
  22146. * @returns {UniformNode<float>}
  22147. */
  22148. const timerGlobal = ( timeScale = 1 ) => { // @deprecated, r170
  22149. console.warn( 'TSL: timerGlobal() is deprecated. Use "time" instead.' );
  22150. return time.mul( timeScale );
  22151. };
  22152. /**
  22153. * @tsl
  22154. * @function
  22155. * @deprecated since r170. Use {@link deltaTime} instead.
  22156. *
  22157. * @param {number} [timeScale=1] - The time scale.
  22158. * @returns {UniformNode<float>}
  22159. */
  22160. const timerDelta = ( timeScale = 1 ) => { // @deprecated, r170
  22161. console.warn( 'TSL: timerDelta() is deprecated. Use "deltaTime" instead.' );
  22162. return deltaTime.mul( timeScale );
  22163. };
  22164. /**
  22165. * Generates a sine wave oscillation based on a timer.
  22166. *
  22167. * @tsl
  22168. * @function
  22169. * @param {Node<float>} t - The timer to generate the oscillation with.
  22170. * @return {Node<float>} The oscillation node.
  22171. */
  22172. const oscSine = ( t = time ) => t.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  22173. /**
  22174. * Generates a square wave oscillation based on a timer.
  22175. *
  22176. * @tsl
  22177. * @function
  22178. * @param {Node<float>} t - The timer to generate the oscillation with.
  22179. * @return {Node<float>} The oscillation node.
  22180. */
  22181. const oscSquare = ( t = time ) => t.fract().round();
  22182. /**
  22183. * Generates a triangle wave oscillation based on a timer.
  22184. *
  22185. * @tsl
  22186. * @function
  22187. * @param {Node<float>} t - The timer to generate the oscillation with.
  22188. * @return {Node<float>} The oscillation node.
  22189. */
  22190. const oscTriangle = ( t = time ) => t.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  22191. /**
  22192. * Generates a sawtooth wave oscillation based on a timer.
  22193. *
  22194. * @tsl
  22195. * @function
  22196. * @param {Node<float>} t - The timer to generate the oscillation with.
  22197. * @return {Node<float>} The oscillation node.
  22198. */
  22199. const oscSawtooth = ( t = time ) => t.fract();
  22200. /**
  22201. * Rotates the given uv coordinates around a center point
  22202. *
  22203. * @tsl
  22204. * @function
  22205. * @param {Node<vec2>} uv - The uv coordinates.
  22206. * @param {Node<float>} rotation - The rotation defined in radians.
  22207. * @param {Node<vec2>} center - The center of rotation
  22208. * @return {Node<vec2>} The rotated uv coordinates.
  22209. */
  22210. const rotateUV = /*@__PURE__*/ Fn( ( [ uv, rotation, center = vec2( 0.5 ) ] ) => {
  22211. return rotate( uv.sub( center ), rotation ).add( center );
  22212. } );
  22213. /**
  22214. * Applies a spherical warping effect to the given uv coordinates.
  22215. *
  22216. * @tsl
  22217. * @function
  22218. * @param {Node<vec2>} uv - The uv coordinates.
  22219. * @param {Node<float>} strength - The strength of the effect.
  22220. * @param {Node<vec2>} center - The center point
  22221. * @return {Node<vec2>} The updated uv coordinates.
  22222. */
  22223. const spherizeUV = /*@__PURE__*/ Fn( ( [ uv, strength, center = vec2( 0.5 ) ] ) => {
  22224. const delta = uv.sub( center );
  22225. const delta2 = delta.dot( delta );
  22226. const delta4 = delta2.mul( delta2 );
  22227. const deltaOffset = delta4.mul( strength );
  22228. return uv.add( delta.mul( deltaOffset ) );
  22229. } );
  22230. /**
  22231. * This can be used to achieve a billboarding behavior for flat meshes. That means they are
  22232. * oriented always towards the camera.
  22233. *
  22234. * ```js
  22235. * material.vertexNode = billboarding();
  22236. * ```
  22237. *
  22238. * @tsl
  22239. * @function
  22240. * @param {Object} config - The configuration object.
  22241. * @param {?Node<vec3>} [config.position=null] - Can be used to define the vertex positions in world space.
  22242. * @param {boolean} [config.horizontal=true] - Whether to follow the camera rotation horizontally or not.
  22243. * @param {boolean} [config.vertical=false] - Whether to follow the camera rotation vertically or not.
  22244. * @return {Node<vec3>} The updated vertex position in clip space.
  22245. */
  22246. const billboarding = /*@__PURE__*/ Fn( ( { position = null, horizontal = true, vertical = false } ) => {
  22247. let worldMatrix;
  22248. if ( position !== null ) {
  22249. worldMatrix = modelWorldMatrix.toVar();
  22250. worldMatrix[ 3 ][ 0 ] = position.x;
  22251. worldMatrix[ 3 ][ 1 ] = position.y;
  22252. worldMatrix[ 3 ][ 2 ] = position.z;
  22253. } else {
  22254. worldMatrix = modelWorldMatrix;
  22255. }
  22256. const modelViewMatrix = cameraViewMatrix.mul( worldMatrix );
  22257. if ( defined( horizontal ) ) {
  22258. modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length();
  22259. modelViewMatrix[ 0 ][ 1 ] = 0;
  22260. modelViewMatrix[ 0 ][ 2 ] = 0;
  22261. }
  22262. if ( defined( vertical ) ) {
  22263. modelViewMatrix[ 1 ][ 0 ] = 0;
  22264. modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length();
  22265. modelViewMatrix[ 1 ][ 2 ] = 0;
  22266. }
  22267. modelViewMatrix[ 2 ][ 0 ] = 0;
  22268. modelViewMatrix[ 2 ][ 1 ] = 0;
  22269. modelViewMatrix[ 2 ][ 2 ] = 1;
  22270. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  22271. } );
  22272. /**
  22273. * A special version of a screen uv function that involves a depth comparison
  22274. * when computing the final uvs. The function mitigates visual errors when
  22275. * using viewport texture nodes for refraction purposes. Without this function
  22276. * objects in front of a refractive surface might appear on the refractive surface
  22277. * which is incorrect.
  22278. *
  22279. * @tsl
  22280. * @function
  22281. * @param {?Node<vec2>} uv - Optional uv coordinates. By default `screenUV` is used.
  22282. * @return {Node<vec2>} The update uv coordinates.
  22283. */
  22284. const viewportSafeUV = /*@__PURE__*/ Fn( ( [ uv = null ] ) => {
  22285. const depth = linearDepth();
  22286. const depthDiff = linearDepth( viewportDepthTexture( uv ) ).sub( depth );
  22287. const finalUV = depthDiff.lessThan( 0 ).select( screenUV, uv );
  22288. return finalUV;
  22289. } );
  22290. /**
  22291. * Can be used to compute texture coordinates for animated sprite sheets.
  22292. *
  22293. * ```js
  22294. * const uvNode = spritesheetUV( vec2( 6, 6 ), uv(), time.mul( animationSpeed ) );
  22295. *
  22296. * material.colorNode = texture( spriteSheet, uvNode );
  22297. * ```
  22298. *
  22299. * @augments Node
  22300. */
  22301. class SpriteSheetUVNode extends Node {
  22302. static get type() {
  22303. return 'SpriteSheetUVNode';
  22304. }
  22305. /**
  22306. * Constructs a new sprite sheet uv node.
  22307. *
  22308. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  22309. * @param {Node<vec2>} [uvNode=uv()] - The uv node.
  22310. * @param {Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  22311. */
  22312. constructor( countNode, uvNode = uv(), frameNode = float( 0 ) ) {
  22313. super( 'vec2' );
  22314. /**
  22315. * The node that defines the number of sprites in the x and y direction (e.g 6x6).
  22316. *
  22317. * @type {Node<vec2>}
  22318. */
  22319. this.countNode = countNode;
  22320. /**
  22321. * The uv node.
  22322. *
  22323. * @type {Node<vec2>}
  22324. */
  22325. this.uvNode = uvNode;
  22326. /**
  22327. * The node that defines the current frame/sprite.
  22328. *
  22329. * @type {Node<float>}
  22330. */
  22331. this.frameNode = frameNode;
  22332. }
  22333. setup() {
  22334. const { frameNode, uvNode, countNode } = this;
  22335. const { width, height } = countNode;
  22336. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  22337. const column = frameNum.mod( width );
  22338. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  22339. const scale = countNode.reciprocal();
  22340. const uvFrameOffset = vec2( column, row );
  22341. return uvNode.add( uvFrameOffset ).mul( scale );
  22342. }
  22343. }
  22344. /**
  22345. * TSL function for creating a sprite sheet uv node.
  22346. *
  22347. * @tsl
  22348. * @function
  22349. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  22350. * @param {?Node<vec2>} [uvNode=uv()] - The uv node.
  22351. * @param {?Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  22352. * @returns {SpriteSheetUVNode}
  22353. */
  22354. const spritesheetUV = /*@__PURE__*/ nodeProxy( SpriteSheetUVNode ).setParameterLength( 3 );
  22355. /**
  22356. * Can be used for triplanar texture mapping.
  22357. *
  22358. * ```js
  22359. * material.colorNode = triplanarTexture( texture( diffuseMap ) );
  22360. * ```
  22361. *
  22362. * @augments Node
  22363. */
  22364. class TriplanarTexturesNode extends Node {
  22365. static get type() {
  22366. return 'TriplanarTexturesNode';
  22367. }
  22368. /**
  22369. * Constructs a new triplanar textures node.
  22370. *
  22371. * @param {Node} textureXNode - First texture node.
  22372. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  22373. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  22374. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  22375. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  22376. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  22377. */
  22378. constructor( textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ) {
  22379. super( 'vec4' );
  22380. /**
  22381. * First texture node.
  22382. *
  22383. * @type {Node}
  22384. */
  22385. this.textureXNode = textureXNode;
  22386. /**
  22387. * Second texture node. When not set, the shader will sample from `textureXNode` instead.
  22388. *
  22389. * @type {?Node}
  22390. * @default null
  22391. */
  22392. this.textureYNode = textureYNode;
  22393. /**
  22394. * Third texture node. When not set, the shader will sample from `textureXNode` instead.
  22395. *
  22396. * @type {?Node}
  22397. * @default null
  22398. */
  22399. this.textureZNode = textureZNode;
  22400. /**
  22401. * The scale node.
  22402. *
  22403. * @type {Node<float>}
  22404. * @default float(1)
  22405. */
  22406. this.scaleNode = scaleNode;
  22407. /**
  22408. * Vertex positions in local space.
  22409. *
  22410. * @type {Node<vec3>}
  22411. * @default positionLocal
  22412. */
  22413. this.positionNode = positionNode;
  22414. /**
  22415. * Normals in local space.
  22416. *
  22417. * @type {Node<vec3>}
  22418. * @default normalLocal
  22419. */
  22420. this.normalNode = normalNode;
  22421. }
  22422. setup() {
  22423. const { textureXNode, textureYNode, textureZNode, scaleNode, positionNode, normalNode } = this;
  22424. // Ref: https://github.com/keijiro/StandardTriplanar
  22425. // Blending factor of triplanar mapping
  22426. let bf = normalNode.abs().normalize();
  22427. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  22428. // Triplanar mapping
  22429. const tx = positionNode.yz.mul( scaleNode );
  22430. const ty = positionNode.zx.mul( scaleNode );
  22431. const tz = positionNode.xy.mul( scaleNode );
  22432. // Base color
  22433. const textureX = textureXNode.value;
  22434. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  22435. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  22436. const cx = texture( textureX, tx ).mul( bf.x );
  22437. const cy = texture( textureY, ty ).mul( bf.y );
  22438. const cz = texture( textureZ, tz ).mul( bf.z );
  22439. return add( cx, cy, cz );
  22440. }
  22441. }
  22442. /**
  22443. * TSL function for creating a triplanar textures node.
  22444. *
  22445. * @tsl
  22446. * @function
  22447. * @param {Node} textureXNode - First texture node.
  22448. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  22449. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  22450. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  22451. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  22452. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  22453. * @returns {TriplanarTexturesNode}
  22454. */
  22455. const triplanarTextures = /*@__PURE__*/ nodeProxy( TriplanarTexturesNode ).setParameterLength( 1, 6 );
  22456. /**
  22457. * TSL function for creating a triplanar textures node.
  22458. *
  22459. * @tsl
  22460. * @function
  22461. * @param {Node} textureXNode - First texture node.
  22462. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  22463. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  22464. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  22465. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  22466. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  22467. * @returns {TriplanarTexturesNode}
  22468. */
  22469. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  22470. const _reflectorPlane = new Plane();
  22471. const _normal = new Vector3();
  22472. const _reflectorWorldPosition = new Vector3();
  22473. const _cameraWorldPosition = new Vector3();
  22474. const _rotationMatrix = new Matrix4();
  22475. const _lookAtPosition = new Vector3( 0, 0, -1 );
  22476. const clipPlane = new Vector4();
  22477. const _view = new Vector3();
  22478. const _target = new Vector3();
  22479. const _q = new Vector4();
  22480. const _size$2 = new Vector2();
  22481. const _defaultRT = new RenderTarget();
  22482. const _defaultUV = screenUV.flipX();
  22483. _defaultRT.depthTexture = new DepthTexture( 1, 1 );
  22484. let _inReflector = false;
  22485. /**
  22486. * This node can be used to implement mirror-like flat reflective surfaces.
  22487. *
  22488. * ```js
  22489. * const groundReflector = reflector();
  22490. * material.colorNode = groundReflector;
  22491. *
  22492. * const plane = new Mesh( geometry, material );
  22493. * plane.add( groundReflector.target );
  22494. * ```
  22495. *
  22496. * @augments TextureNode
  22497. */
  22498. class ReflectorNode extends TextureNode {
  22499. static get type() {
  22500. return 'ReflectorNode';
  22501. }
  22502. /**
  22503. * Constructs a new reflector node.
  22504. *
  22505. * @param {Object} [parameters={}] - An object holding configuration parameters.
  22506. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  22507. * @param {number} [parameters.resolution=1] - The resolution scale.
  22508. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  22509. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  22510. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  22511. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  22512. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  22513. */
  22514. constructor( parameters = {} ) {
  22515. super( parameters.defaultTexture || _defaultRT.texture, _defaultUV );
  22516. /**
  22517. * A reference to the internal reflector base node which holds the actual implementation.
  22518. *
  22519. * @private
  22520. * @type {ReflectorBaseNode}
  22521. * @default ReflectorBaseNode
  22522. */
  22523. this._reflectorBaseNode = parameters.reflector || new ReflectorBaseNode( this, parameters );
  22524. /**
  22525. * A reference to the internal depth node.
  22526. *
  22527. * @private
  22528. * @type {?Node}
  22529. * @default null
  22530. */
  22531. this._depthNode = null;
  22532. this.setUpdateMatrix( false );
  22533. }
  22534. /**
  22535. * A reference to the internal reflector node.
  22536. *
  22537. * @type {ReflectorBaseNode}
  22538. */
  22539. get reflector() {
  22540. return this._reflectorBaseNode;
  22541. }
  22542. /**
  22543. * A reference to 3D object the reflector is linked to.
  22544. *
  22545. * @type {Object3D}
  22546. */
  22547. get target() {
  22548. return this._reflectorBaseNode.target;
  22549. }
  22550. /**
  22551. * Returns a node representing the mirror's depth. That can be used
  22552. * to implement more advanced reflection effects like distance attenuation.
  22553. *
  22554. * @return {Node} The depth node.
  22555. */
  22556. getDepthNode() {
  22557. if ( this._depthNode === null ) {
  22558. if ( this._reflectorBaseNode.depth !== true ) {
  22559. throw new Error( 'THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ' );
  22560. }
  22561. this._depthNode = nodeObject( new ReflectorNode( {
  22562. defaultTexture: _defaultRT.depthTexture,
  22563. reflector: this._reflectorBaseNode
  22564. } ) );
  22565. }
  22566. return this._depthNode;
  22567. }
  22568. setup( builder ) {
  22569. // ignore if used in post-processing
  22570. if ( ! builder.object.isQuadMesh ) this._reflectorBaseNode.build( builder );
  22571. return super.setup( builder );
  22572. }
  22573. clone() {
  22574. const texture = new this.constructor( this.reflectorNode );
  22575. texture._reflectorBaseNode = this._reflectorBaseNode;
  22576. return texture;
  22577. }
  22578. /**
  22579. * Frees internal resources. Should be called when the node is no longer in use.
  22580. */
  22581. dispose() {
  22582. super.dispose();
  22583. this._reflectorBaseNode.dispose();
  22584. }
  22585. }
  22586. /**
  22587. * Holds the actual implementation of the reflector.
  22588. *
  22589. * TODO: Explain why `ReflectorBaseNode`. Originally the entire logic was implemented
  22590. * in `ReflectorNode`, see #29619.
  22591. *
  22592. * @private
  22593. * @augments Node
  22594. */
  22595. class ReflectorBaseNode extends Node {
  22596. static get type() {
  22597. return 'ReflectorBaseNode';
  22598. }
  22599. /**
  22600. * Constructs a new reflector base node.
  22601. *
  22602. * @param {TextureNode} textureNode - Represents the rendered reflections as a texture node.
  22603. * @param {Object} [parameters={}] - An object holding configuration parameters.
  22604. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  22605. * @param {number} [parameters.resolution=1] - The resolution scale.
  22606. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  22607. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  22608. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  22609. */
  22610. constructor( textureNode, parameters = {} ) {
  22611. super();
  22612. const {
  22613. target = new Object3D(),
  22614. resolution = 1,
  22615. generateMipmaps = false,
  22616. bounces = true,
  22617. depth = false
  22618. } = parameters;
  22619. /**
  22620. * Represents the rendered reflections as a texture node.
  22621. *
  22622. * @type {TextureNode}
  22623. */
  22624. this.textureNode = textureNode;
  22625. /**
  22626. * The 3D object the reflector is linked to.
  22627. *
  22628. * @type {Object3D}
  22629. * @default {new Object3D()}
  22630. */
  22631. this.target = target;
  22632. /**
  22633. * The resolution scale.
  22634. *
  22635. * @type {number}
  22636. * @default {1}
  22637. */
  22638. this.resolution = resolution;
  22639. /**
  22640. * Whether mipmaps should be generated or not.
  22641. *
  22642. * @type {boolean}
  22643. * @default {false}
  22644. */
  22645. this.generateMipmaps = generateMipmaps;
  22646. /**
  22647. * Whether reflectors can render other reflector nodes or not.
  22648. *
  22649. * @type {boolean}
  22650. * @default {true}
  22651. */
  22652. this.bounces = bounces;
  22653. /**
  22654. * Whether depth data should be generated or not.
  22655. *
  22656. * @type {boolean}
  22657. * @default {false}
  22658. */
  22659. this.depth = depth;
  22660. /**
  22661. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` when {@link ReflectorBaseNode#bounces}
  22662. * is `true`. Otherwise it's `NodeUpdateType.FRAME`.
  22663. *
  22664. * @type {string}
  22665. * @default 'render'
  22666. */
  22667. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  22668. /**
  22669. * Weak map for managing virtual cameras.
  22670. *
  22671. * @type {WeakMap<Camera, Camera>}
  22672. */
  22673. this.virtualCameras = new WeakMap();
  22674. /**
  22675. * Weak map for managing render targets.
  22676. *
  22677. * @type {Map<Camera, RenderTarget>}
  22678. */
  22679. this.renderTargets = new Map();
  22680. /**
  22681. * Force render even if reflector is facing away from camera.
  22682. *
  22683. * @type {boolean}
  22684. * @default {false}
  22685. */
  22686. this.forceUpdate = false;
  22687. /**
  22688. * Whether the reflector has been rendered or not.
  22689. *
  22690. * When the reflector is facing away from the camera,
  22691. * this flag is set to `false` and the texture will be empty(black).
  22692. *
  22693. * @type {boolean}
  22694. * @default {false}
  22695. */
  22696. this.hasOutput = false;
  22697. }
  22698. /**
  22699. * Updates the resolution of the internal render target.
  22700. *
  22701. * @private
  22702. * @param {RenderTarget} renderTarget - The render target to resize.
  22703. * @param {Renderer} renderer - The renderer that is used to determine the new size.
  22704. */
  22705. _updateResolution( renderTarget, renderer ) {
  22706. const resolution = this.resolution;
  22707. renderer.getDrawingBufferSize( _size$2 );
  22708. renderTarget.setSize( Math.round( _size$2.width * resolution ), Math.round( _size$2.height * resolution ) );
  22709. }
  22710. setup( builder ) {
  22711. this._updateResolution( _defaultRT, builder.renderer );
  22712. return super.setup( builder );
  22713. }
  22714. /**
  22715. * Frees internal resources. Should be called when the node is no longer in use.
  22716. */
  22717. dispose() {
  22718. super.dispose();
  22719. for ( const renderTarget of this.renderTargets.values() ) {
  22720. renderTarget.dispose();
  22721. }
  22722. }
  22723. /**
  22724. * Returns a virtual camera for the given camera. The virtual camera is used to
  22725. * render the scene from the reflector's view so correct reflections can be produced.
  22726. *
  22727. * @param {Camera} camera - The scene's camera.
  22728. * @return {Camera} The corresponding virtual camera.
  22729. */
  22730. getVirtualCamera( camera ) {
  22731. let virtualCamera = this.virtualCameras.get( camera );
  22732. if ( virtualCamera === undefined ) {
  22733. virtualCamera = camera.clone();
  22734. this.virtualCameras.set( camera, virtualCamera );
  22735. }
  22736. return virtualCamera;
  22737. }
  22738. /**
  22739. * Returns a render target for the given camera. The reflections are rendered
  22740. * into this render target.
  22741. *
  22742. * @param {Camera} camera - The scene's camera.
  22743. * @return {RenderTarget} The render target.
  22744. */
  22745. getRenderTarget( camera ) {
  22746. let renderTarget = this.renderTargets.get( camera );
  22747. if ( renderTarget === undefined ) {
  22748. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType } );
  22749. if ( this.generateMipmaps === true ) {
  22750. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  22751. renderTarget.texture.generateMipmaps = true;
  22752. }
  22753. if ( this.depth === true ) {
  22754. renderTarget.depthTexture = new DepthTexture();
  22755. }
  22756. this.renderTargets.set( camera, renderTarget );
  22757. }
  22758. return renderTarget;
  22759. }
  22760. updateBefore( frame ) {
  22761. if ( this.bounces === false && _inReflector ) return false;
  22762. _inReflector = true;
  22763. const { scene, camera, renderer, material } = frame;
  22764. const { target } = this;
  22765. const virtualCamera = this.getVirtualCamera( camera );
  22766. const renderTarget = this.getRenderTarget( virtualCamera );
  22767. renderer.getDrawingBufferSize( _size$2 );
  22768. this._updateResolution( renderTarget, renderer );
  22769. //
  22770. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  22771. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  22772. _rotationMatrix.extractRotation( target.matrixWorld );
  22773. _normal.set( 0, 0, 1 );
  22774. _normal.applyMatrix4( _rotationMatrix );
  22775. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  22776. // Avoid rendering when reflector is facing away unless forcing an update
  22777. const isFacingAway = _view.dot( _normal ) > 0;
  22778. let needsClear = false;
  22779. if ( isFacingAway === true && this.forceUpdate === false ) {
  22780. if ( this.hasOutput === false ) {
  22781. _inReflector = false;
  22782. return;
  22783. }
  22784. needsClear = true;
  22785. }
  22786. _view.reflect( _normal ).negate();
  22787. _view.add( _reflectorWorldPosition );
  22788. _rotationMatrix.extractRotation( camera.matrixWorld );
  22789. _lookAtPosition.set( 0, 0, -1 );
  22790. _lookAtPosition.applyMatrix4( _rotationMatrix );
  22791. _lookAtPosition.add( _cameraWorldPosition );
  22792. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  22793. _target.reflect( _normal ).negate();
  22794. _target.add( _reflectorWorldPosition );
  22795. //
  22796. virtualCamera.coordinateSystem = camera.coordinateSystem;
  22797. virtualCamera.position.copy( _view );
  22798. virtualCamera.up.set( 0, 1, 0 );
  22799. virtualCamera.up.applyMatrix4( _rotationMatrix );
  22800. virtualCamera.up.reflect( _normal );
  22801. virtualCamera.lookAt( _target );
  22802. virtualCamera.near = camera.near;
  22803. virtualCamera.far = camera.far;
  22804. virtualCamera.updateMatrixWorld();
  22805. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  22806. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  22807. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  22808. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  22809. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  22810. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  22811. const projectionMatrix = virtualCamera.projectionMatrix;
  22812. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  22813. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  22814. _q.z = -1;
  22815. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  22816. // Calculate the scaled plane vector
  22817. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  22818. const clipBias = 0;
  22819. // Replacing the third row of the projection matrix
  22820. projectionMatrix.elements[ 2 ] = clipPlane.x;
  22821. projectionMatrix.elements[ 6 ] = clipPlane.y;
  22822. projectionMatrix.elements[ 10 ] = ( renderer.coordinateSystem === WebGPUCoordinateSystem ) ? ( clipPlane.z - clipBias ) : ( clipPlane.z + 1.0 - clipBias );
  22823. projectionMatrix.elements[ 14 ] = clipPlane.w;
  22824. //
  22825. this.textureNode.value = renderTarget.texture;
  22826. if ( this.depth === true ) {
  22827. this.textureNode.getDepthNode().value = renderTarget.depthTexture;
  22828. }
  22829. material.visible = false;
  22830. const currentRenderTarget = renderer.getRenderTarget();
  22831. const currentMRT = renderer.getMRT();
  22832. const currentAutoClear = renderer.autoClear;
  22833. renderer.setMRT( null );
  22834. renderer.setRenderTarget( renderTarget );
  22835. renderer.autoClear = true;
  22836. if ( needsClear ) {
  22837. renderer.clear();
  22838. this.hasOutput = false;
  22839. } else {
  22840. renderer.render( scene, virtualCamera );
  22841. this.hasOutput = true;
  22842. }
  22843. renderer.setMRT( currentMRT );
  22844. renderer.setRenderTarget( currentRenderTarget );
  22845. renderer.autoClear = currentAutoClear;
  22846. material.visible = true;
  22847. _inReflector = false;
  22848. this.forceUpdate = false;
  22849. }
  22850. }
  22851. /**
  22852. * TSL function for creating a reflector node.
  22853. *
  22854. * @tsl
  22855. * @function
  22856. * @param {Object} [parameters={}] - An object holding configuration parameters.
  22857. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  22858. * @param {number} [parameters.resolution=1] - The resolution scale.
  22859. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  22860. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  22861. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  22862. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  22863. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  22864. * @returns {ReflectorNode}
  22865. */
  22866. const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) );
  22867. const _camera = /*@__PURE__*/ new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  22868. /**
  22869. * The purpose of this special geometry is to fill the entire viewport with a single triangle.
  22870. *
  22871. * Reference: {@link https://github.com/mrdoob/three.js/pull/21358}
  22872. *
  22873. * @private
  22874. * @augments BufferGeometry
  22875. */
  22876. class QuadGeometry extends BufferGeometry {
  22877. /**
  22878. * Constructs a new quad geometry.
  22879. *
  22880. * @param {boolean} [flipY=false] - Whether the uv coordinates should be flipped along the vertical axis or not.
  22881. */
  22882. constructor( flipY = false ) {
  22883. super();
  22884. const uv = flipY === false ? [ 0, -1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  22885. this.setAttribute( 'position', new Float32BufferAttribute( [ -1, 3, 0, -1, -1, 0, 3, -1, 0 ], 3 ) );
  22886. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  22887. }
  22888. }
  22889. const _geometry = /*@__PURE__*/ new QuadGeometry();
  22890. /**
  22891. * This module is a helper for passes which need to render a full
  22892. * screen effect which is quite common in context of post processing.
  22893. *
  22894. * The intended usage is to reuse a single quad mesh for rendering
  22895. * subsequent passes by just reassigning the `material` reference.
  22896. *
  22897. * Note: This module can only be used with `WebGPURenderer`.
  22898. *
  22899. * @augments Mesh
  22900. */
  22901. class QuadMesh extends Mesh {
  22902. /**
  22903. * Constructs a new quad mesh.
  22904. *
  22905. * @param {?Material} [material=null] - The material to render the quad mesh with.
  22906. */
  22907. constructor( material = null ) {
  22908. super( _geometry, material );
  22909. /**
  22910. * The camera to render the quad mesh with.
  22911. *
  22912. * @type {OrthographicCamera}
  22913. * @readonly
  22914. */
  22915. this.camera = _camera;
  22916. /**
  22917. * This flag can be used for type testing.
  22918. *
  22919. * @type {boolean}
  22920. * @readonly
  22921. * @default true
  22922. */
  22923. this.isQuadMesh = true;
  22924. }
  22925. /**
  22926. * Async version of `render()`.
  22927. *
  22928. * @async
  22929. * @param {Renderer} renderer - The renderer.
  22930. * @return {Promise} A Promise that resolves when the render has been finished.
  22931. */
  22932. async renderAsync( renderer ) {
  22933. return renderer.renderAsync( this, _camera );
  22934. }
  22935. /**
  22936. * Renders the quad mesh
  22937. *
  22938. * @param {Renderer} renderer - The renderer.
  22939. */
  22940. render( renderer ) {
  22941. renderer.render( this, _camera );
  22942. }
  22943. }
  22944. const _size$1 = /*@__PURE__*/ new Vector2();
  22945. /**
  22946. * `RTTNode` takes another node and uses it with a `QuadMesh` to render into a texture (RTT).
  22947. * This module is especially relevant in context of post processing where certain nodes require
  22948. * texture input for their effects. With the helper function `convertToTexture()` which is based
  22949. * on this module, the node system can automatically ensure texture input if required.
  22950. *
  22951. * @augments TextureNode
  22952. */
  22953. class RTTNode extends TextureNode {
  22954. static get type() {
  22955. return 'RTTNode';
  22956. }
  22957. /**
  22958. * Constructs a new RTT node.
  22959. *
  22960. * @param {Node} node - The node to render a texture with.
  22961. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  22962. * @param {?number} [height=null] - The height of the internal render target.
  22963. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  22964. */
  22965. constructor( node, width = null, height = null, options = { type: HalfFloatType } ) {
  22966. const renderTarget = new RenderTarget( width, height, options );
  22967. super( renderTarget.texture, uv() );
  22968. /**
  22969. * The node to render a texture with.
  22970. *
  22971. * @type {Node}
  22972. */
  22973. this.node = node;
  22974. /**
  22975. * The width of the internal render target.
  22976. * If not width is applied, the render target is automatically resized.
  22977. *
  22978. * @type {?number}
  22979. * @default null
  22980. */
  22981. this.width = width;
  22982. /**
  22983. * The height of the internal render target.
  22984. *
  22985. * @type {?number}
  22986. * @default null
  22987. */
  22988. this.height = height;
  22989. /**
  22990. * The pixel ratio
  22991. *
  22992. * @type {number}
  22993. * @default 1
  22994. */
  22995. this.pixelRatio = 1;
  22996. /**
  22997. * The render target
  22998. *
  22999. * @type {RenderTarget}
  23000. */
  23001. this.renderTarget = renderTarget;
  23002. /**
  23003. * Whether the texture requires an update or not.
  23004. *
  23005. * @type {boolean}
  23006. * @default true
  23007. */
  23008. this.textureNeedsUpdate = true;
  23009. /**
  23010. * Whether the texture should automatically be updated or not.
  23011. *
  23012. * @type {boolean}
  23013. * @default true
  23014. */
  23015. this.autoUpdate = true;
  23016. /**
  23017. * The node which is used with the quad mesh for RTT.
  23018. *
  23019. * @private
  23020. * @type {Node}
  23021. * @default null
  23022. */
  23023. this._rttNode = null;
  23024. /**
  23025. * The internal quad mesh for RTT.
  23026. *
  23027. * @private
  23028. * @type {QuadMesh}
  23029. */
  23030. this._quadMesh = new QuadMesh( new NodeMaterial() );
  23031. /**
  23032. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  23033. * the texture once per render in its {@link RTTNode#updateBefore} method.
  23034. *
  23035. * @type {string}
  23036. * @default 'render'
  23037. */
  23038. this.updateBeforeType = NodeUpdateType.RENDER;
  23039. }
  23040. /**
  23041. * Whether the internal render target should automatically be resized or not.
  23042. *
  23043. * @type {boolean}
  23044. * @readonly
  23045. * @default true
  23046. */
  23047. get autoSize() {
  23048. return this.width === null;
  23049. }
  23050. setup( builder ) {
  23051. this._rttNode = this.node.context( builder.getSharedContext() );
  23052. this._quadMesh.material.name = 'RTT';
  23053. this._quadMesh.material.needsUpdate = true;
  23054. return super.setup( builder );
  23055. }
  23056. /**
  23057. * Sets the size of the internal render target
  23058. *
  23059. * @param {number} width - The width to set.
  23060. * @param {number} height - The width to set.
  23061. */
  23062. setSize( width, height ) {
  23063. this.width = width;
  23064. this.height = height;
  23065. const effectiveWidth = width * this.pixelRatio;
  23066. const effectiveHeight = height * this.pixelRatio;
  23067. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  23068. this.textureNeedsUpdate = true;
  23069. }
  23070. /**
  23071. * Sets the pixel ratio. This will also resize the render target.
  23072. *
  23073. * @param {number} pixelRatio - The pixel ratio to set.
  23074. */
  23075. setPixelRatio( pixelRatio ) {
  23076. this.pixelRatio = pixelRatio;
  23077. this.setSize( this.width, this.height );
  23078. }
  23079. updateBefore( { renderer } ) {
  23080. if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return;
  23081. this.textureNeedsUpdate = false;
  23082. //
  23083. if ( this.autoSize === true ) {
  23084. this.pixelRatio = renderer.getPixelRatio();
  23085. const size = renderer.getSize( _size$1 );
  23086. this.setSize( size.width, size.height );
  23087. }
  23088. //
  23089. this._quadMesh.material.fragmentNode = this._rttNode;
  23090. //
  23091. const currentRenderTarget = renderer.getRenderTarget();
  23092. renderer.setRenderTarget( this.renderTarget );
  23093. this._quadMesh.render( renderer );
  23094. renderer.setRenderTarget( currentRenderTarget );
  23095. }
  23096. clone() {
  23097. const newNode = new TextureNode( this.value, this.uvNode, this.levelNode );
  23098. newNode.sampler = this.sampler;
  23099. newNode.referenceNode = this;
  23100. return newNode;
  23101. }
  23102. }
  23103. /**
  23104. * TSL function for creating a RTT node.
  23105. *
  23106. * @tsl
  23107. * @function
  23108. * @param {Node} node - The node to render a texture with.
  23109. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  23110. * @param {?number} [height=null] - The height of the internal render target.
  23111. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  23112. * @returns {RTTNode}
  23113. */
  23114. const rtt = ( node, ...params ) => nodeObject( new RTTNode( nodeObject( node ), ...params ) );
  23115. /**
  23116. * TSL function for converting nodes to textures nodes.
  23117. *
  23118. * @tsl
  23119. * @function
  23120. * @param {Node} node - The node to render a texture with.
  23121. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  23122. * @param {?number} [height=null] - The height of the internal render target.
  23123. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  23124. * @returns {RTTNode}
  23125. */
  23126. const convertToTexture = ( node, ...params ) => {
  23127. if ( node.isTextureNode ) return node;
  23128. if ( node.isPassNode ) return node.getTextureNode();
  23129. return rtt( node, ...params );
  23130. };
  23131. /**
  23132. * Computes a position in view space based on a fragment's screen position expressed as uv coordinates, the fragments
  23133. * depth value and the camera's inverse projection matrix.
  23134. *
  23135. * @tsl
  23136. * @function
  23137. * @param {Node<vec2>} screenPosition - The fragment's screen position expressed as uv coordinates.
  23138. * @param {Node<float>} depth - The fragment's depth value.
  23139. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  23140. * @return {Node<vec3>} The fragments position in view space.
  23141. */
  23142. const getViewPosition = /*@__PURE__*/ Fn( ( [ screenPosition, depth, projectionMatrixInverse ], builder ) => {
  23143. let clipSpacePosition;
  23144. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  23145. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  23146. clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  23147. } else {
  23148. clipSpacePosition = vec4( vec3( screenPosition.x, screenPosition.y.oneMinus(), depth ).mul( 2.0 ).sub( 1.0 ), 1.0 );
  23149. }
  23150. const viewSpacePosition = vec4( projectionMatrixInverse.mul( clipSpacePosition ) );
  23151. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  23152. } );
  23153. /**
  23154. * Computes a screen position expressed as uv coordinates based on a fragment's position in view space
  23155. * and the camera's projection matrix
  23156. *
  23157. * @tsl
  23158. * @function
  23159. * @param {Node<vec3>} viewPosition - The fragments position in view space.
  23160. * @param {Node<mat4>} projectionMatrix - The camera's projection matrix.
  23161. * @return {Node<vec2>} The fragment's screen position expressed as uv coordinates.
  23162. */
  23163. const getScreenPosition = /*@__PURE__*/ Fn( ( [ viewPosition, projectionMatrix ] ) => {
  23164. const sampleClipPos = projectionMatrix.mul( vec4( viewPosition, 1.0 ) );
  23165. const sampleUv = sampleClipPos.xy.div( sampleClipPos.w ).mul( 0.5 ).add( 0.5 ).toVar();
  23166. return vec2( sampleUv.x, sampleUv.y.oneMinus() );
  23167. } );
  23168. /**
  23169. * Computes a normal vector based on depth data. Can be used as a fallback when no normal render
  23170. * target is available or if flat surface normals are required.
  23171. *
  23172. * @tsl
  23173. * @function
  23174. * @param {Node<vec2>} uv - The texture coordinate.
  23175. * @param {DepthTexture} depthTexture - The depth texture.
  23176. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  23177. * @return {Node<vec3>} The computed normal vector.
  23178. */
  23179. const getNormalFromDepth = /*@__PURE__*/ Fn( ( [ uv, depthTexture, projectionMatrixInverse ] ) => {
  23180. const size = textureSize( textureLoad( depthTexture ) );
  23181. const p = ivec2( uv.mul( size ) ).toVar();
  23182. const c0 = textureLoad( depthTexture, p ).toVar();
  23183. const l2 = textureLoad( depthTexture, p.sub( ivec2( 2, 0 ) ) ).toVar();
  23184. const l1 = textureLoad( depthTexture, p.sub( ivec2( 1, 0 ) ) ).toVar();
  23185. const r1 = textureLoad( depthTexture, p.add( ivec2( 1, 0 ) ) ).toVar();
  23186. const r2 = textureLoad( depthTexture, p.add( ivec2( 2, 0 ) ) ).toVar();
  23187. const b2 = textureLoad( depthTexture, p.add( ivec2( 0, 2 ) ) ).toVar();
  23188. const b1 = textureLoad( depthTexture, p.add( ivec2( 0, 1 ) ) ).toVar();
  23189. const t1 = textureLoad( depthTexture, p.sub( ivec2( 0, 1 ) ) ).toVar();
  23190. const t2 = textureLoad( depthTexture, p.sub( ivec2( 0, 2 ) ) ).toVar();
  23191. const dl = abs( sub( float( 2 ).mul( l1 ).sub( l2 ), c0 ) ).toVar();
  23192. const dr = abs( sub( float( 2 ).mul( r1 ).sub( r2 ), c0 ) ).toVar();
  23193. const db = abs( sub( float( 2 ).mul( b1 ).sub( b2 ), c0 ) ).toVar();
  23194. const dt = abs( sub( float( 2 ).mul( t1 ).sub( t2 ), c0 ) ).toVar();
  23195. const ce = getViewPosition( uv, c0, projectionMatrixInverse ).toVar();
  23196. 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 ) ) );
  23197. 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 ) ) );
  23198. return normalize( cross( dpdx, dpdy ) );
  23199. } );
  23200. /**
  23201. * This special type of instanced buffer attribute is intended for compute shaders.
  23202. * In earlier three.js versions it was only possible to update attribute data
  23203. * on the CPU via JavaScript and then upload the data to the GPU. With the
  23204. * new material system and renderer it is now possible to use compute shaders
  23205. * to compute the data for an attribute more efficiently on the GPU.
  23206. *
  23207. * The idea is to create an instance of this class and provide it as an input
  23208. * to {@link StorageBufferNode}.
  23209. *
  23210. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  23211. *
  23212. * @augments InstancedBufferAttribute
  23213. */
  23214. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  23215. /**
  23216. * Constructs a new storage instanced buffer attribute.
  23217. *
  23218. * @param {number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  23219. * The subsequent parameters are then obsolete.
  23220. * @param {number} itemSize - The item size.
  23221. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  23222. */
  23223. constructor( count, itemSize, typeClass = Float32Array ) {
  23224. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  23225. super( array, itemSize );
  23226. /**
  23227. * This flag can be used for type testing.
  23228. *
  23229. * @type {boolean}
  23230. * @readonly
  23231. * @default true
  23232. */
  23233. this.isStorageInstancedBufferAttribute = true;
  23234. }
  23235. }
  23236. /**
  23237. * This special type of buffer attribute is intended for compute shaders.
  23238. * In earlier three.js versions it was only possible to update attribute data
  23239. * on the CPU via JavaScript and then upload the data to the GPU. With the
  23240. * new material system and renderer it is now possible to use compute shaders
  23241. * to compute the data for an attribute more efficiently on the GPU.
  23242. *
  23243. * The idea is to create an instance of this class and provide it as an input
  23244. * to {@link StorageBufferNode}.
  23245. *
  23246. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  23247. *
  23248. * @augments BufferAttribute
  23249. */
  23250. class StorageBufferAttribute extends BufferAttribute {
  23251. /**
  23252. * Constructs a new storage buffer attribute.
  23253. *
  23254. * @param {number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  23255. * The subsequent parameters are then obsolete.
  23256. * @param {number} itemSize - The item size.
  23257. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  23258. */
  23259. constructor( count, itemSize, typeClass = Float32Array ) {
  23260. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  23261. super( array, itemSize );
  23262. /**
  23263. * This flag can be used for type testing.
  23264. *
  23265. * @type {boolean}
  23266. * @readonly
  23267. * @default true
  23268. */
  23269. this.isStorageBufferAttribute = true;
  23270. }
  23271. }
  23272. /**
  23273. * TSL function for creating a storage buffer node with a configured `StorageBufferAttribute`.
  23274. *
  23275. * @tsl
  23276. * @function
  23277. * @param {number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  23278. * @param {string|Struct} [type='float'] - The data type.
  23279. * @returns {StorageBufferNode}
  23280. */
  23281. const attributeArray = ( count, type = 'float' ) => {
  23282. let itemSize, typedArray;
  23283. if ( type.isStruct === true ) {
  23284. itemSize = type.layout.getLength();
  23285. typedArray = getTypedArrayFromType( 'float' );
  23286. } else {
  23287. itemSize = getLengthFromType( type );
  23288. typedArray = getTypedArrayFromType( type );
  23289. }
  23290. const buffer = new StorageBufferAttribute( count, itemSize, typedArray );
  23291. const node = storage( buffer, type, count );
  23292. return node;
  23293. };
  23294. /**
  23295. * TSL function for creating a storage buffer node with a configured `StorageInstancedBufferAttribute`.
  23296. *
  23297. * @tsl
  23298. * @function
  23299. * @param {number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  23300. * @param {string|Struct} [type='float'] - The data type.
  23301. * @returns {StorageBufferNode}
  23302. */
  23303. const instancedArray = ( count, type = 'float' ) => {
  23304. let itemSize, typedArray;
  23305. if ( type.isStruct === true ) {
  23306. itemSize = type.layout.getLength();
  23307. typedArray = getTypedArrayFromType( 'float' );
  23308. } else {
  23309. itemSize = getLengthFromType( type );
  23310. typedArray = getTypedArrayFromType( type );
  23311. }
  23312. const buffer = new StorageInstancedBufferAttribute( count, itemSize, typedArray );
  23313. const node = storage( buffer, type, count );
  23314. return node;
  23315. };
  23316. /**
  23317. * A node for representing the uv coordinates of points.
  23318. *
  23319. * Can only be used with a WebGL backend. In WebGPU, point
  23320. * primitives always have the size of one pixel and can thus
  23321. * can't be used as sprite-like objects that display textures.
  23322. *
  23323. * @augments Node
  23324. */
  23325. class PointUVNode extends Node {
  23326. static get type() {
  23327. return 'PointUVNode';
  23328. }
  23329. /**
  23330. * Constructs a new point uv node.
  23331. */
  23332. constructor() {
  23333. super( 'vec2' );
  23334. /**
  23335. * This flag can be used for type testing.
  23336. *
  23337. * @type {boolean}
  23338. * @readonly
  23339. * @default true
  23340. */
  23341. this.isPointUVNode = true;
  23342. }
  23343. generate( /*builder*/ ) {
  23344. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  23345. }
  23346. }
  23347. /**
  23348. * TSL object that represents the uv coordinates of points.
  23349. *
  23350. * @tsl
  23351. * @type {PointUVNode}
  23352. */
  23353. const pointUV = /*@__PURE__*/ nodeImmutable( PointUVNode );
  23354. const _e1 = /*@__PURE__*/ new Euler();
  23355. const _m1 = /*@__PURE__*/ new Matrix4();
  23356. /**
  23357. * This module allows access to a collection of scene properties. The following predefined TSL objects
  23358. * are available for easier use:
  23359. *
  23360. * - `backgroundBlurriness`: A node that represents the scene's background blurriness.
  23361. * - `backgroundIntensity`: A node that represents the scene's background intensity.
  23362. * - `backgroundRotation`: A node that represents the scene's background rotation.
  23363. *
  23364. * @augments Node
  23365. */
  23366. class SceneNode extends Node {
  23367. static get type() {
  23368. return 'SceneNode';
  23369. }
  23370. /**
  23371. * Constructs a new scene node.
  23372. *
  23373. * @param {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')} scope - The scope defines the type of scene property that is accessed.
  23374. * @param {?Scene} [scene=null] - A reference to the scene.
  23375. */
  23376. constructor( scope = SceneNode.BACKGROUND_BLURRINESS, scene = null ) {
  23377. super();
  23378. /**
  23379. * The scope defines the type of scene property that is accessed.
  23380. *
  23381. * @type {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')}
  23382. */
  23383. this.scope = scope;
  23384. /**
  23385. * A reference to the scene that is going to be accessed.
  23386. *
  23387. * @type {?Scene}
  23388. * @default null
  23389. */
  23390. this.scene = scene;
  23391. }
  23392. /**
  23393. * Depending on the scope, the method returns a different type of node that represents
  23394. * the respective scene property.
  23395. *
  23396. * @param {NodeBuilder} builder - The current node builder.
  23397. * @return {Node} The output node.
  23398. */
  23399. setup( builder ) {
  23400. const scope = this.scope;
  23401. const scene = this.scene !== null ? this.scene : builder.scene;
  23402. let output;
  23403. if ( scope === SceneNode.BACKGROUND_BLURRINESS ) {
  23404. output = reference( 'backgroundBlurriness', 'float', scene );
  23405. } else if ( scope === SceneNode.BACKGROUND_INTENSITY ) {
  23406. output = reference( 'backgroundIntensity', 'float', scene );
  23407. } else if ( scope === SceneNode.BACKGROUND_ROTATION ) {
  23408. output = uniform( 'mat4' ).label( 'backgroundRotation' ).setGroup( renderGroup ).onRenderUpdate( () => {
  23409. const background = scene.background;
  23410. if ( background !== null && background.isTexture && background.mapping !== UVMapping ) {
  23411. _e1.copy( scene.backgroundRotation );
  23412. // accommodate left-handed frame
  23413. _e1.x *= -1; _e1.y *= -1; _e1.z *= -1;
  23414. _m1.makeRotationFromEuler( _e1 );
  23415. } else {
  23416. _m1.identity();
  23417. }
  23418. return _m1;
  23419. } );
  23420. } else {
  23421. console.error( 'THREE.SceneNode: Unknown scope:', scope );
  23422. }
  23423. return output;
  23424. }
  23425. }
  23426. SceneNode.BACKGROUND_BLURRINESS = 'backgroundBlurriness';
  23427. SceneNode.BACKGROUND_INTENSITY = 'backgroundIntensity';
  23428. SceneNode.BACKGROUND_ROTATION = 'backgroundRotation';
  23429. /**
  23430. * TSL object that represents the scene's background blurriness.
  23431. *
  23432. * @tsl
  23433. * @type {SceneNode}
  23434. */
  23435. const backgroundBlurriness = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_BLURRINESS );
  23436. /**
  23437. * TSL object that represents the scene's background intensity.
  23438. *
  23439. * @tsl
  23440. * @type {SceneNode}
  23441. */
  23442. const backgroundIntensity = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_INTENSITY );
  23443. /**
  23444. * TSL object that represents the scene's background rotation.
  23445. *
  23446. * @tsl
  23447. * @type {SceneNode}
  23448. */
  23449. const backgroundRotation = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_ROTATION );
  23450. /**
  23451. * This special version of a texture node can be used to
  23452. * write data into a storage texture with a compute shader.
  23453. *
  23454. * ```js
  23455. * const storageTexture = new THREE.StorageTexture( width, height );
  23456. *
  23457. * const computeTexture = Fn( ( { storageTexture } ) => {
  23458. *
  23459. * const posX = instanceIndex.mod( width );
  23460. * const posY = instanceIndex.div( width );
  23461. * const indexUV = uvec2( posX, posY );
  23462. *
  23463. * // generate RGB values
  23464. *
  23465. * const r = 1;
  23466. * const g = 1;
  23467. * const b = 1;
  23468. *
  23469. * textureStore( storageTexture, indexUV, vec4( r, g, b, 1 ) ).toWriteOnly();
  23470. *
  23471. * } );
  23472. *
  23473. * const computeNode = computeTexture( { storageTexture } ).compute( width * height );
  23474. * renderer.computeAsync( computeNode );
  23475. * ```
  23476. *
  23477. * This node can only be used with a WebGPU backend.
  23478. *
  23479. * @augments TextureNode
  23480. */
  23481. class StorageTextureNode extends TextureNode {
  23482. static get type() {
  23483. return 'StorageTextureNode';
  23484. }
  23485. /**
  23486. * Constructs a new storage texture node.
  23487. *
  23488. * @param {StorageTexture} value - The storage texture.
  23489. * @param {Node<vec2|vec3>} uvNode - The uv node.
  23490. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  23491. */
  23492. constructor( value, uvNode, storeNode = null ) {
  23493. super( value, uvNode );
  23494. /**
  23495. * The value node that should be stored in the texture.
  23496. *
  23497. * @type {?Node}
  23498. * @default null
  23499. */
  23500. this.storeNode = storeNode;
  23501. /**
  23502. * This flag can be used for type testing.
  23503. *
  23504. * @type {boolean}
  23505. * @readonly
  23506. * @default true
  23507. */
  23508. this.isStorageTextureNode = true;
  23509. /**
  23510. * The access type of the texture node.
  23511. *
  23512. * @type {string}
  23513. * @default 'writeOnly'
  23514. */
  23515. this.access = NodeAccess.WRITE_ONLY;
  23516. }
  23517. /**
  23518. * Overwrites the default implementation to return a fixed value `'storageTexture'`.
  23519. *
  23520. * @param {NodeBuilder} builder - The current node builder.
  23521. * @return {string} The input type.
  23522. */
  23523. getInputType( /*builder*/ ) {
  23524. return 'storageTexture';
  23525. }
  23526. setup( builder ) {
  23527. super.setup( builder );
  23528. const properties = builder.getNodeProperties( this );
  23529. properties.storeNode = this.storeNode;
  23530. return properties;
  23531. }
  23532. /**
  23533. * Defines the node access.
  23534. *
  23535. * @param {string} value - The node access.
  23536. * @return {StorageTextureNode} A reference to this node.
  23537. */
  23538. setAccess( value ) {
  23539. this.access = value;
  23540. return this;
  23541. }
  23542. /**
  23543. * Generates the code snippet of the storage node. If no `storeNode`
  23544. * is defined, the texture node is generated as normal texture.
  23545. *
  23546. * @param {NodeBuilder} builder - The current node builder.
  23547. * @param {string} output - The current output.
  23548. * @return {string} The generated code snippet.
  23549. */
  23550. generate( builder, output ) {
  23551. let snippet;
  23552. if ( this.storeNode !== null ) {
  23553. snippet = this.generateStore( builder );
  23554. } else {
  23555. snippet = super.generate( builder, output );
  23556. }
  23557. return snippet;
  23558. }
  23559. /**
  23560. * Convenience method for configuring a read/write node access.
  23561. *
  23562. * @return {StorageTextureNode} A reference to this node.
  23563. */
  23564. toReadWrite() {
  23565. return this.setAccess( NodeAccess.READ_WRITE );
  23566. }
  23567. /**
  23568. * Convenience method for configuring a read-only node access.
  23569. *
  23570. * @return {StorageTextureNode} A reference to this node.
  23571. */
  23572. toReadOnly() {
  23573. return this.setAccess( NodeAccess.READ_ONLY );
  23574. }
  23575. /**
  23576. * Convenience method for configuring a write-only node access.
  23577. *
  23578. * @return {StorageTextureNode} A reference to this node.
  23579. */
  23580. toWriteOnly() {
  23581. return this.setAccess( NodeAccess.WRITE_ONLY );
  23582. }
  23583. /**
  23584. * Generates the code snippet of the storage texture node.
  23585. *
  23586. * @param {NodeBuilder} builder - The current node builder.
  23587. */
  23588. generateStore( builder ) {
  23589. const properties = builder.getNodeProperties( this );
  23590. const { uvNode, storeNode, depthNode } = properties;
  23591. const textureProperty = super.generate( builder, 'property' );
  23592. const uvSnippet = uvNode.build( builder, 'uvec2' );
  23593. const storeSnippet = storeNode.build( builder, 'vec4' );
  23594. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  23595. const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, depthSnippet, storeSnippet );
  23596. builder.addLineFlowCode( snippet, this );
  23597. }
  23598. clone() {
  23599. const newNode = super.clone();
  23600. newNode.storeNode = this.storeNode;
  23601. return newNode;
  23602. }
  23603. }
  23604. /**
  23605. * TSL function for creating a storage texture node.
  23606. *
  23607. * @tsl
  23608. * @function
  23609. * @param {StorageTexture} value - The storage texture.
  23610. * @param {?Node<vec2|vec3>} uvNode - The uv node.
  23611. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  23612. * @returns {StorageTextureNode}
  23613. */
  23614. const storageTexture = /*@__PURE__*/ nodeProxy( StorageTextureNode ).setParameterLength( 1, 3 );
  23615. /**
  23616. * TODO: Explain difference to `storageTexture()`.
  23617. *
  23618. * @tsl
  23619. * @function
  23620. * @param {StorageTexture} value - The storage texture.
  23621. * @param {Node<vec2|vec3>} uvNode - The uv node.
  23622. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  23623. * @returns {StorageTextureNode}
  23624. */
  23625. const textureStore = ( value, uvNode, storeNode ) => {
  23626. const node = storageTexture( value, uvNode, storeNode );
  23627. if ( storeNode !== null ) node.toStack();
  23628. return node;
  23629. };
  23630. const normal = Fn( ( { texture, uv } ) => {
  23631. const epsilon = 0.0001;
  23632. const ret = vec3().toVar();
  23633. If( uv.x.lessThan( epsilon ), () => {
  23634. ret.assign( vec3( 1, 0, 0 ) );
  23635. } ).ElseIf( uv.y.lessThan( epsilon ), () => {
  23636. ret.assign( vec3( 0, 1, 0 ) );
  23637. } ).ElseIf( uv.z.lessThan( epsilon ), () => {
  23638. ret.assign( vec3( 0, 0, 1 ) );
  23639. } ).ElseIf( uv.x.greaterThan( 1 - epsilon ), () => {
  23640. ret.assign( vec3( -1, 0, 0 ) );
  23641. } ).ElseIf( uv.y.greaterThan( 1 - epsilon ), () => {
  23642. ret.assign( vec3( 0, -1, 0 ) );
  23643. } ).ElseIf( uv.z.greaterThan( 1 - epsilon ), () => {
  23644. ret.assign( vec3( 0, 0, -1 ) );
  23645. } ).Else( () => {
  23646. const step = 0.01;
  23647. const x = texture.sample( uv.add( vec3( -0.01, 0.0, 0.0 ) ) ).r.sub( texture.sample( uv.add( vec3( step, 0.0, 0.0 ) ) ).r );
  23648. const y = texture.sample( uv.add( vec3( 0.0, -0.01, 0.0 ) ) ).r.sub( texture.sample( uv.add( vec3( 0.0, step, 0.0 ) ) ).r );
  23649. const z = texture.sample( uv.add( vec3( 0.0, 0.0, -0.01 ) ) ).r.sub( texture.sample( uv.add( vec3( 0.0, 0.0, step ) ) ).r );
  23650. ret.assign( vec3( x, y, z ) );
  23651. } );
  23652. return ret.normalize();
  23653. } );
  23654. /**
  23655. * This type of uniform node represents a 3D texture.
  23656. *
  23657. * @augments TextureNode
  23658. */
  23659. class Texture3DNode extends TextureNode {
  23660. static get type() {
  23661. return 'Texture3DNode';
  23662. }
  23663. /**
  23664. * Constructs a new 3D texture node.
  23665. *
  23666. * @param {Data3DTexture} value - The 3D texture.
  23667. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  23668. * @param {?Node<int>} [levelNode=null] - The level node.
  23669. */
  23670. constructor( value, uvNode = null, levelNode = null ) {
  23671. super( value, uvNode, levelNode );
  23672. /**
  23673. * This flag can be used for type testing.
  23674. *
  23675. * @type {boolean}
  23676. * @readonly
  23677. * @default true
  23678. */
  23679. this.isTexture3DNode = true;
  23680. }
  23681. /**
  23682. * Overwrites the default implementation to return a fixed value `'texture3D'`.
  23683. *
  23684. * @param {NodeBuilder} builder - The current node builder.
  23685. * @return {string} The input type.
  23686. */
  23687. getInputType( /*builder*/ ) {
  23688. return 'texture3D';
  23689. }
  23690. /**
  23691. * Returns a default uv node which is in context of 3D textures a three-dimensional
  23692. * uv node.
  23693. *
  23694. * @return {Node<vec3>} The default uv node.
  23695. */
  23696. getDefaultUV() {
  23697. return vec3( 0.5, 0.5, 0.5 );
  23698. }
  23699. /**
  23700. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  23701. * for 3D textures. The uv transformation matrix is not applied to 3D textures.
  23702. *
  23703. * @param {boolean} value - The update toggle.
  23704. */
  23705. setUpdateMatrix( /*value*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  23706. /**
  23707. * Overwrites the default implementation to return the unmodified uv node.
  23708. *
  23709. * @param {NodeBuilder} builder - The current node builder.
  23710. * @param {Node} uvNode - The uv node to setup.
  23711. * @return {Node} The unmodified uv node.
  23712. */
  23713. setupUV( builder, uvNode ) {
  23714. const texture = this.value;
  23715. if ( builder.isFlipY() && ( texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true ) ) {
  23716. if ( this.sampler ) {
  23717. uvNode = uvNode.flipY();
  23718. } else {
  23719. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  23720. }
  23721. }
  23722. return uvNode;
  23723. }
  23724. /**
  23725. * Generates the uv code snippet.
  23726. *
  23727. * @param {NodeBuilder} builder - The current node builder.
  23728. * @param {Node} uvNode - The uv node to generate code for.
  23729. * @return {string} The generated code snippet.
  23730. */
  23731. generateUV( builder, uvNode ) {
  23732. return uvNode.build( builder, 'vec3' );
  23733. }
  23734. /**
  23735. * TODO.
  23736. *
  23737. * @param {Node<vec3>} uvNode - The uv node .
  23738. * @return {Node<vec3>} TODO.
  23739. */
  23740. normal( uvNode ) {
  23741. return normal( { texture: this, uv: uvNode } );
  23742. }
  23743. }
  23744. /**
  23745. * TSL function for creating a 3D texture node.
  23746. *
  23747. * @tsl
  23748. * @function
  23749. * @param {Data3DTexture} value - The 3D texture.
  23750. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  23751. * @param {?Node<int>} [levelNode=null] - The level node.
  23752. * @returns {Texture3DNode}
  23753. */
  23754. const texture3D = /*@__PURE__*/ nodeProxy( Texture3DNode ).setParameterLength( 1, 3 );
  23755. /**
  23756. * A special type of reference node that allows to link values in
  23757. * `userData` fields to node objects.
  23758. * ```js
  23759. * sprite.userData.rotation = 1; // stores individual rotation per sprite
  23760. *
  23761. * const material = new THREE.SpriteNodeMaterial();
  23762. * material.rotationNode = userData( 'rotation', 'float' );
  23763. * ```
  23764. * Since `UserDataNode` is extended from {@link ReferenceNode}, the node value
  23765. * will automatically be updated when the `rotation` user data field changes.
  23766. *
  23767. * @augments ReferenceNode
  23768. */
  23769. class UserDataNode extends ReferenceNode {
  23770. static get type() {
  23771. return 'UserDataNode';
  23772. }
  23773. /**
  23774. * Constructs a new user data node.
  23775. *
  23776. * @param {string} property - The property name that should be referenced by the node.
  23777. * @param {string} inputType - The node data type of the reference.
  23778. * @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.
  23779. */
  23780. constructor( property, inputType, userData = null ) {
  23781. super( property, inputType, userData );
  23782. /**
  23783. * A reference to the `userData` object. If not provided, the `userData`
  23784. * property of the 3D object that uses the node material is evaluated.
  23785. *
  23786. * @type {?Object}
  23787. * @default null
  23788. */
  23789. this.userData = userData;
  23790. }
  23791. /**
  23792. * Overwritten to make sure {@link ReferenceNode#reference} points to the correct
  23793. * `userData` field.
  23794. *
  23795. * @param {(NodeFrame|NodeBuilder)} state - The current state to evaluate.
  23796. * @return {Object} A reference to the `userData` field.
  23797. */
  23798. updateReference( state ) {
  23799. this.reference = this.userData !== null ? this.userData : state.object.userData;
  23800. return this.reference;
  23801. }
  23802. }
  23803. /**
  23804. * TSL function for creating a user data node.
  23805. *
  23806. * @tsl
  23807. * @function
  23808. * @param {string} name - The property name that should be referenced by the node.
  23809. * @param {string} inputType - The node data type of the reference.
  23810. * @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.
  23811. * @returns {UserDataNode}
  23812. */
  23813. const userData = ( name, inputType, userData ) => nodeObject( new UserDataNode( name, inputType, userData ) );
  23814. const _objectData = new WeakMap();
  23815. /**
  23816. * A node for representing motion or velocity vectors. Foundation
  23817. * for advanced post processing effects like motion blur or TRAA.
  23818. *
  23819. * The node keeps track of the model, view and projection matrices
  23820. * of the previous frame and uses them to compute offsets in NDC space.
  23821. * These offsets represent the final velocity.
  23822. *
  23823. * @augments TempNode
  23824. */
  23825. class VelocityNode extends TempNode {
  23826. static get type() {
  23827. return 'VelocityNode';
  23828. }
  23829. /**
  23830. * Constructs a new vertex color node.
  23831. */
  23832. constructor() {
  23833. super( 'vec2' );
  23834. /**
  23835. * The current projection matrix.
  23836. *
  23837. * @type {?Matrix4}
  23838. * @default null
  23839. */
  23840. this.projectionMatrix = null;
  23841. /**
  23842. * Overwritten since velocity nodes are updated per object.
  23843. *
  23844. * @type {string}
  23845. * @default 'object'
  23846. */
  23847. this.updateType = NodeUpdateType.OBJECT;
  23848. /**
  23849. * Overwritten since velocity nodes save data after the update.
  23850. *
  23851. * @type {string}
  23852. * @default 'object'
  23853. */
  23854. this.updateAfterType = NodeUpdateType.OBJECT;
  23855. /**
  23856. * Uniform node representing the previous model matrix in world space.
  23857. *
  23858. * @type {UniformNode<mat4>}
  23859. * @default null
  23860. */
  23861. this.previousModelWorldMatrix = uniform( new Matrix4() );
  23862. /**
  23863. * Uniform node representing the previous projection matrix.
  23864. *
  23865. * @type {UniformNode<mat4>}
  23866. * @default null
  23867. */
  23868. this.previousProjectionMatrix = uniform( new Matrix4() ).setGroup( renderGroup );
  23869. /**
  23870. * Uniform node representing the previous view matrix.
  23871. *
  23872. * @type {UniformNode<mat4>}
  23873. * @default null
  23874. */
  23875. this.previousCameraViewMatrix = uniform( new Matrix4() );
  23876. }
  23877. /**
  23878. * Sets the given projection matrix.
  23879. *
  23880. * @param {Matrix4} projectionMatrix - The projection matrix to set.
  23881. */
  23882. setProjectionMatrix( projectionMatrix ) {
  23883. this.projectionMatrix = projectionMatrix;
  23884. }
  23885. /**
  23886. * Updates velocity specific uniforms.
  23887. *
  23888. * @param {NodeFrame} frame - A reference to the current node frame.
  23889. */
  23890. update( { frameId, camera, object } ) {
  23891. const previousModelMatrix = getPreviousMatrix( object );
  23892. this.previousModelWorldMatrix.value.copy( previousModelMatrix );
  23893. //
  23894. const cameraData = getData( camera );
  23895. if ( cameraData.frameId !== frameId ) {
  23896. cameraData.frameId = frameId;
  23897. if ( cameraData.previousProjectionMatrix === undefined ) {
  23898. cameraData.previousProjectionMatrix = new Matrix4();
  23899. cameraData.previousCameraViewMatrix = new Matrix4();
  23900. cameraData.currentProjectionMatrix = new Matrix4();
  23901. cameraData.currentCameraViewMatrix = new Matrix4();
  23902. cameraData.previousProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  23903. cameraData.previousCameraViewMatrix.copy( camera.matrixWorldInverse );
  23904. } else {
  23905. cameraData.previousProjectionMatrix.copy( cameraData.currentProjectionMatrix );
  23906. cameraData.previousCameraViewMatrix.copy( cameraData.currentCameraViewMatrix );
  23907. }
  23908. cameraData.currentProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  23909. cameraData.currentCameraViewMatrix.copy( camera.matrixWorldInverse );
  23910. this.previousProjectionMatrix.value.copy( cameraData.previousProjectionMatrix );
  23911. this.previousCameraViewMatrix.value.copy( cameraData.previousCameraViewMatrix );
  23912. }
  23913. }
  23914. /**
  23915. * Overwritten to updated velocity specific uniforms.
  23916. *
  23917. * @param {NodeFrame} frame - A reference to the current node frame.
  23918. */
  23919. updateAfter( { object } ) {
  23920. getPreviousMatrix( object ).copy( object.matrixWorld );
  23921. }
  23922. /**
  23923. * Implements the velocity computation based on the previous and current vertex data.
  23924. *
  23925. * @param {NodeBuilder} builder - A reference to the current node builder.
  23926. * @return {Node<vec2>} The motion vector.
  23927. */
  23928. setup( /*builder*/ ) {
  23929. const projectionMatrix = ( this.projectionMatrix === null ) ? cameraProjectionMatrix : uniform( this.projectionMatrix );
  23930. const previousModelViewMatrix = this.previousCameraViewMatrix.mul( this.previousModelWorldMatrix );
  23931. const clipPositionCurrent = projectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  23932. const clipPositionPrevious = this.previousProjectionMatrix.mul( previousModelViewMatrix ).mul( positionPrevious );
  23933. const ndcPositionCurrent = clipPositionCurrent.xy.div( clipPositionCurrent.w );
  23934. const ndcPositionPrevious = clipPositionPrevious.xy.div( clipPositionPrevious.w );
  23935. const velocity = sub( ndcPositionCurrent, ndcPositionPrevious );
  23936. return velocity;
  23937. }
  23938. }
  23939. function getData( object ) {
  23940. let objectData = _objectData.get( object );
  23941. if ( objectData === undefined ) {
  23942. objectData = {};
  23943. _objectData.set( object, objectData );
  23944. }
  23945. return objectData;
  23946. }
  23947. function getPreviousMatrix( object, index = 0 ) {
  23948. const objectData = getData( object );
  23949. let matrix = objectData[ index ];
  23950. if ( matrix === undefined ) {
  23951. objectData[ index ] = matrix = new Matrix4();
  23952. objectData[ index ].copy( object.matrixWorld );
  23953. }
  23954. return matrix;
  23955. }
  23956. /**
  23957. * TSL object that represents the velocity of a render pass.
  23958. *
  23959. * @tsl
  23960. * @type {VelocityNode}
  23961. */
  23962. const velocity = /*@__PURE__*/ nodeImmutable( VelocityNode );
  23963. /**
  23964. * Represents a "Color Burn" blend mode.
  23965. *
  23966. * It's designed to darken the base layer's colors based on the color of the blend layer.
  23967. * It significantly increases the contrast of the base layer, making the colors more vibrant and saturated.
  23968. * The darker the color in the blend layer, the stronger the darkening and contrast effect on the base layer.
  23969. *
  23970. * @tsl
  23971. * @function
  23972. * @param {Node<vec3>} base - The base color.
  23973. * @param {Node<vec3>} blend - The blend color. A white (#ffffff) blend color does not alter the base color.
  23974. * @return {Node<vec3>} The result.
  23975. */
  23976. const blendBurn = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  23977. return min$1( 1.0, base.oneMinus().div( blend ) ).oneMinus();
  23978. } ).setLayout( {
  23979. name: 'blendBurn',
  23980. type: 'vec3',
  23981. inputs: [
  23982. { name: 'base', type: 'vec3' },
  23983. { name: 'blend', type: 'vec3' }
  23984. ]
  23985. } );
  23986. /**
  23987. * Represents a "Color Dodge" blend mode.
  23988. *
  23989. * It's designed to lighten the base layer's colors based on the color of the blend layer.
  23990. * It significantly increases the brightness of the base layer, making the colors lighter and more vibrant.
  23991. * The brighter the color in the blend layer, the stronger the lightening and contrast effect on the base layer.
  23992. *
  23993. * @tsl
  23994. * @function
  23995. * @param {Node<vec3>} base - The base color.
  23996. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  23997. * @return {Node<vec3>} The result.
  23998. */
  23999. const blendDodge = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  24000. return min$1( base.div( blend.oneMinus() ), 1.0 );
  24001. } ).setLayout( {
  24002. name: 'blendDodge',
  24003. type: 'vec3',
  24004. inputs: [
  24005. { name: 'base', type: 'vec3' },
  24006. { name: 'blend', type: 'vec3' }
  24007. ]
  24008. } );
  24009. /**
  24010. * Represents a "Screen" blend mode.
  24011. *
  24012. * Similar to `blendDodge()`, this mode also lightens the base layer's colors based on the color of the blend layer.
  24013. * The "Screen" blend mode is better for general brightening whereas the "Dodge" results in more subtle and nuanced
  24014. * effects.
  24015. *
  24016. * @tsl
  24017. * @function
  24018. * @param {Node<vec3>} base - The base color.
  24019. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  24020. * @return {Node<vec3>} The result.
  24021. */
  24022. const blendScreen = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  24023. return base.oneMinus().mul( blend.oneMinus() ).oneMinus();
  24024. } ).setLayout( {
  24025. name: 'blendScreen',
  24026. type: 'vec3',
  24027. inputs: [
  24028. { name: 'base', type: 'vec3' },
  24029. { name: 'blend', type: 'vec3' }
  24030. ]
  24031. } );
  24032. /**
  24033. * Represents a "Overlay" blend mode.
  24034. *
  24035. * It's designed to increase the contrast of the base layer based on the color of the blend layer.
  24036. * It amplifies the existing colors and contrast in the base layer, making lighter areas lighter and darker areas darker.
  24037. * The color of the blend layer significantly influences the resulting contrast and color shift in the base layer.
  24038. *
  24039. * @tsl
  24040. * @function
  24041. * @param {Node<vec3>} base - The base color.
  24042. * @param {Node<vec3>} blend - The blend color
  24043. * @return {Node<vec3>} The result.
  24044. */
  24045. const blendOverlay = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  24046. return mix( base.mul( 2.0 ).mul( blend ), base.oneMinus().mul( 2.0 ).mul( blend.oneMinus() ).oneMinus(), step( 0.5, base ) );
  24047. } ).setLayout( {
  24048. name: 'blendOverlay',
  24049. type: 'vec3',
  24050. inputs: [
  24051. { name: 'base', type: 'vec3' },
  24052. { name: 'blend', type: 'vec3' }
  24053. ]
  24054. } );
  24055. /**
  24056. * This function blends two color based on their alpha values by replicating the behavior of `THREE.NormalBlending`.
  24057. * It assumes both input colors have non-premultiplied alpha.
  24058. *
  24059. * @tsl
  24060. * @function
  24061. * @param {Node<vec4>} base - The base color.
  24062. * @param {Node<vec4>} blend - The blend color
  24063. * @return {Node<vec4>} The result.
  24064. */
  24065. const blendColor = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  24066. const outAlpha = blend.a.add( base.a.mul( blend.a.oneMinus() ) );
  24067. return vec4( blend.rgb.mul( blend.a ).add( base.rgb.mul( base.a ).mul( blend.a.oneMinus() ) ).div( outAlpha ), outAlpha );
  24068. } ).setLayout( {
  24069. name: 'blendColor',
  24070. type: 'vec4',
  24071. inputs: [
  24072. { name: 'base', type: 'vec4' },
  24073. { name: 'blend', type: 'vec4' }
  24074. ]
  24075. } );
  24076. /**
  24077. * Premultiplies the RGB channels of a color by its alpha channel.
  24078. *
  24079. * This function is useful for converting a non-premultiplied alpha color
  24080. * into a premultiplied alpha format, where the RGB values are scaled
  24081. * by the alpha value. Premultiplied alpha is often used in graphics
  24082. * rendering for certain operations, such as compositing and image processing.
  24083. *
  24084. * @tsl
  24085. * @function
  24086. * @param {Node<vec4>} color - The input color with non-premultiplied alpha.
  24087. * @return {Node<vec4>} The color with premultiplied alpha.
  24088. */
  24089. const premult = /*@__PURE__*/ Fn( ( [ color ] ) => {
  24090. return vec4( color.rgb.mul( color.a ), color.a );
  24091. }, { color: 'vec4', return: 'vec4' } );
  24092. /**
  24093. * Unpremultiplies the RGB channels of a color by its alpha channel.
  24094. *
  24095. * This function is useful for converting a premultiplied alpha color
  24096. * back into a non-premultiplied alpha format, where the RGB values are
  24097. * divided by the alpha value. Unpremultiplied alpha is often used in graphics
  24098. * rendering for certain operations, such as compositing and image processing.
  24099. *
  24100. * @tsl
  24101. * @function
  24102. * @param {Node<vec4>} color - The input color with premultiplied alpha.
  24103. * @return {Node<vec4>} The color with non-premultiplied alpha.
  24104. */
  24105. const unpremult = /*@__PURE__*/ Fn( ( [ color ] ) => {
  24106. If( color.a.equal( 0.0 ), () => vec4( 0.0 ) );
  24107. return vec4( color.rgb.div( color.a ), color.a );
  24108. }, { color: 'vec4', return: 'vec4' } );
  24109. // Deprecated
  24110. /**
  24111. * @tsl
  24112. * @function
  24113. * @deprecated since r171. Use {@link blendBurn} instead.
  24114. *
  24115. * @param {...any} params
  24116. * @returns {Function}
  24117. */
  24118. const burn = ( ...params ) => { // @deprecated, r171
  24119. console.warn( 'THREE.TSL: "burn" has been renamed. Use "blendBurn" instead.' );
  24120. return blendBurn( params );
  24121. };
  24122. /**
  24123. * @tsl
  24124. * @function
  24125. * @deprecated since r171. Use {@link blendDodge} instead.
  24126. *
  24127. * @param {...any} params
  24128. * @returns {Function}
  24129. */
  24130. const dodge = ( ...params ) => { // @deprecated, r171
  24131. console.warn( 'THREE.TSL: "dodge" has been renamed. Use "blendDodge" instead.' );
  24132. return blendDodge( params );
  24133. };
  24134. /**
  24135. * @tsl
  24136. * @function
  24137. * @deprecated since r171. Use {@link blendScreen} instead.
  24138. *
  24139. * @param {...any} params
  24140. * @returns {Function}
  24141. */
  24142. const screen = ( ...params ) => { // @deprecated, r171
  24143. console.warn( 'THREE.TSL: "screen" has been renamed. Use "blendScreen" instead.' );
  24144. return blendScreen( params );
  24145. };
  24146. /**
  24147. * @tsl
  24148. * @function
  24149. * @deprecated since r171. Use {@link blendOverlay} instead.
  24150. *
  24151. * @param {...any} params
  24152. * @returns {Function}
  24153. */
  24154. const overlay = ( ...params ) => { // @deprecated, r171
  24155. console.warn( 'THREE.TSL: "overlay" has been renamed. Use "blendOverlay" instead.' );
  24156. return blendOverlay( params );
  24157. };
  24158. /**
  24159. * Computes a grayscale value for the given RGB color value.
  24160. *
  24161. * @tsl
  24162. * @function
  24163. * @param {Node<vec3>} color - The color value to compute the grayscale for.
  24164. * @return {Node<vec3>} The grayscale color.
  24165. */
  24166. const grayscale = /*@__PURE__*/ Fn( ( [ color ] ) => {
  24167. return luminance( color.rgb );
  24168. } );
  24169. /**
  24170. * Super-saturates or desaturates the given RGB color.
  24171. *
  24172. * @tsl
  24173. * @function
  24174. * @param {Node<vec3>} color - The input color.
  24175. * @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.
  24176. * @return {Node<vec3>} The saturated color.
  24177. */
  24178. const saturation = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  24179. return adjustment.mix( luminance( color.rgb ), color.rgb );
  24180. } );
  24181. /**
  24182. * Selectively enhance the intensity of less saturated RGB colors. Can result
  24183. * in a more natural and visually appealing image with enhanced color depth
  24184. * compared to {@link ColorAdjustment#saturation}.
  24185. *
  24186. * @tsl
  24187. * @function
  24188. * @param {Node<vec3>} color - The input color.
  24189. * @param {Node<float>} [adjustment=1] - Controls the intensity of the vibrance effect.
  24190. * @return {Node<vec3>} The updated color.
  24191. */
  24192. const vibrance = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  24193. const average = add( color.r, color.g, color.b ).div( 3.0 );
  24194. const mx = color.r.max( color.g.max( color.b ) );
  24195. const amt = mx.sub( average ).mul( adjustment ).mul( -3 );
  24196. return mix( color.rgb, mx, amt );
  24197. } );
  24198. /**
  24199. * Updates the hue component of the given RGB color while preserving its luminance and saturation.
  24200. *
  24201. * @tsl
  24202. * @function
  24203. * @param {Node<vec3>} color - The input color.
  24204. * @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.
  24205. * @return {Node<vec3>} The updated color.
  24206. */
  24207. const hue = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  24208. const k = vec3( 0.57735, 0.57735, 0.57735 );
  24209. const cosAngle = adjustment.cos();
  24210. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) );
  24211. } );
  24212. /**
  24213. * Computes the luminance for the given RGB color value.
  24214. *
  24215. * @tsl
  24216. * @function
  24217. * @param {Node<vec3>} color - The color value to compute the luminance for.
  24218. * @param {?Node<vec3>} luminanceCoefficients - The luminance coefficients. By default predefined values of the current working color space are used.
  24219. * @return {Node<vec3>} The luminance.
  24220. */
  24221. const luminance = (
  24222. color,
  24223. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3() ) )
  24224. ) => dot( color, luminanceCoefficients );
  24225. /**
  24226. * Color Decision List (CDL) v1.2
  24227. *
  24228. * Compact representation of color grading information, defined by slope, offset, power, and
  24229. * saturation. The CDL should be typically be given input in a log space (such as LogC, ACEScc,
  24230. * or AgX Log), and will return output in the same space. Output may require clamping >=0.
  24231. *
  24232. * @tsl
  24233. * @function
  24234. * @param {Node<vec4>} color Input (-Infinity < input < +Infinity)
  24235. * @param {Node<vec3>} slope Slope (0 ≤ slope < +Infinity)
  24236. * @param {Node<vec3>} offset Offset (-Infinity < offset < +Infinity; typically -1 < offset < 1)
  24237. * @param {Node<vec3>} power Power (0 < power < +Infinity)
  24238. * @param {Node<float>} saturation Saturation (0 ≤ saturation < +Infinity; typically 0 ≤ saturation < 4)
  24239. * @param {Node<vec3>} luminanceCoefficients Luminance coefficients for saturation term, typically Rec. 709
  24240. * @return {Node<vec4>} Output, -Infinity < output < +Infinity
  24241. *
  24242. * References:
  24243. * - ASC CDL v1.2
  24244. * - {@link https://blender.stackexchange.com/a/55239/43930}
  24245. * - {@link https://docs.acescentral.com/specifications/acescc/}
  24246. */
  24247. const cdl = /*@__PURE__*/ Fn( ( [
  24248. color,
  24249. slope = vec3( 1 ),
  24250. offset = vec3( 0 ),
  24251. power = vec3( 1 ),
  24252. saturation = float( 1 ),
  24253. // ASC CDL v1.2 explicitly requires Rec. 709 luminance coefficients.
  24254. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3(), LinearSRGBColorSpace ) )
  24255. ] ) => {
  24256. // NOTE: The ASC CDL v1.2 defines a [0, 1] clamp on the slope+offset term, and another on the
  24257. // saturation term. Per the ACEScc specification and Filament, limits may be omitted to support
  24258. // values outside [0, 1], requiring a workaround for negative values in the power expression.
  24259. const luma = color.rgb.dot( vec3( luminanceCoefficients ) );
  24260. const v = max$1( color.rgb.mul( slope ).add( offset ), 0.0 ).toVar();
  24261. const pv = v.pow( power ).toVar();
  24262. If( v.r.greaterThan( 0.0 ), () => { v.r.assign( pv.r ); } ); // eslint-disable-line
  24263. If( v.g.greaterThan( 0.0 ), () => { v.g.assign( pv.g ); } ); // eslint-disable-line
  24264. If( v.b.greaterThan( 0.0 ), () => { v.b.assign( pv.b ); } ); // eslint-disable-line
  24265. v.assign( luma.add( v.sub( luma ).mul( saturation ) ) );
  24266. return vec4( v.rgb, color.a );
  24267. } );
  24268. /**
  24269. * Represents a posterize effect which reduces the number of colors
  24270. * in an image, resulting in a more blocky and stylized appearance.
  24271. *
  24272. * @augments TempNode
  24273. */
  24274. class PosterizeNode extends TempNode {
  24275. static get type() {
  24276. return 'PosterizeNode';
  24277. }
  24278. /**
  24279. * Constructs a new posterize node.
  24280. *
  24281. * @param {Node} sourceNode - The input color.
  24282. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  24283. */
  24284. constructor( sourceNode, stepsNode ) {
  24285. super();
  24286. /**
  24287. * The input color.
  24288. *
  24289. * @type {Node}
  24290. */
  24291. this.sourceNode = sourceNode;
  24292. /**
  24293. * Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  24294. *
  24295. * @type {Node}
  24296. */
  24297. this.stepsNode = stepsNode;
  24298. }
  24299. setup() {
  24300. const { sourceNode, stepsNode } = this;
  24301. return sourceNode.mul( stepsNode ).floor().div( stepsNode );
  24302. }
  24303. }
  24304. /**
  24305. * TSL function for creating a posterize node.
  24306. *
  24307. * @tsl
  24308. * @function
  24309. * @param {Node} sourceNode - The input color.
  24310. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  24311. * @returns {PosterizeNode}
  24312. */
  24313. const posterize = /*@__PURE__*/ nodeProxy( PosterizeNode ).setParameterLength( 2 );
  24314. const _size = /*@__PURE__*/ new Vector2();
  24315. /**
  24316. * Represents the texture of a pass node.
  24317. *
  24318. * @augments TextureNode
  24319. */
  24320. class PassTextureNode extends TextureNode {
  24321. static get type() {
  24322. return 'PassTextureNode';
  24323. }
  24324. /**
  24325. * Constructs a new pass texture node.
  24326. *
  24327. * @param {PassNode} passNode - The pass node.
  24328. * @param {Texture} texture - The output texture.
  24329. */
  24330. constructor( passNode, texture ) {
  24331. super( texture );
  24332. /**
  24333. * A reference to the pass node.
  24334. *
  24335. * @type {PassNode}
  24336. */
  24337. this.passNode = passNode;
  24338. this.setUpdateMatrix( false );
  24339. }
  24340. setup( builder ) {
  24341. if ( builder.object.isQuadMesh ) this.passNode.build( builder );
  24342. return super.setup( builder );
  24343. }
  24344. clone() {
  24345. return new this.constructor( this.passNode, this.value );
  24346. }
  24347. }
  24348. /**
  24349. * An extension of `PassTextureNode` which allows to manage more than one
  24350. * internal texture. Relevant for the `getPreviousTexture()` related API.
  24351. *
  24352. * @augments PassTextureNode
  24353. */
  24354. class PassMultipleTextureNode extends PassTextureNode {
  24355. static get type() {
  24356. return 'PassMultipleTextureNode';
  24357. }
  24358. /**
  24359. * Constructs a new pass texture node.
  24360. *
  24361. * @param {PassNode} passNode - The pass node.
  24362. * @param {string} textureName - The output texture name.
  24363. * @param {boolean} [previousTexture=false] - Whether previous frame data should be used or not.
  24364. */
  24365. constructor( passNode, textureName, previousTexture = false ) {
  24366. // null is passed to the super call since this class does not
  24367. // use an external texture for rendering pass data into. Instead
  24368. // the texture is managed by the pass node itself
  24369. super( passNode, null );
  24370. /**
  24371. * The output texture name.
  24372. *
  24373. * @type {string}
  24374. */
  24375. this.textureName = textureName;
  24376. /**
  24377. * Whether previous frame data should be used or not.
  24378. *
  24379. * @type {boolean}
  24380. */
  24381. this.previousTexture = previousTexture;
  24382. }
  24383. /**
  24384. * Updates the texture reference of this node.
  24385. */
  24386. updateTexture() {
  24387. this.value = this.previousTexture ? this.passNode.getPreviousTexture( this.textureName ) : this.passNode.getTexture( this.textureName );
  24388. }
  24389. setup( builder ) {
  24390. this.updateTexture();
  24391. return super.setup( builder );
  24392. }
  24393. clone() {
  24394. return new this.constructor( this.passNode, this.textureName, this.previousTexture );
  24395. }
  24396. }
  24397. /**
  24398. * Represents a render pass (sometimes called beauty pass) in context of post processing.
  24399. * This pass produces a render for the given scene and camera and can provide multiple outputs
  24400. * via MRT for further processing.
  24401. *
  24402. * ```js
  24403. * const postProcessing = new PostProcessing( renderer );
  24404. *
  24405. * const scenePass = pass( scene, camera );
  24406. *
  24407. * postProcessing.outputNode = scenePass;
  24408. * ```
  24409. *
  24410. * @augments TempNode
  24411. */
  24412. class PassNode extends TempNode {
  24413. static get type() {
  24414. return 'PassNode';
  24415. }
  24416. /**
  24417. * Constructs a new pass node.
  24418. *
  24419. * @param {('color'|'depth')} scope - The scope of the pass. The scope determines whether the node outputs color or depth.
  24420. * @param {Scene} scene - A reference to the scene.
  24421. * @param {Camera} camera - A reference to the camera.
  24422. * @param {Object} options - Options for the internal render target.
  24423. */
  24424. constructor( scope, scene, camera, options = {} ) {
  24425. super( 'vec4' );
  24426. /**
  24427. * The scope of the pass. The scope determines whether the node outputs color or depth.
  24428. *
  24429. * @type {('color'|'depth')}
  24430. */
  24431. this.scope = scope;
  24432. /**
  24433. * A reference to the scene.
  24434. *
  24435. * @type {Scene}
  24436. */
  24437. this.scene = scene;
  24438. /**
  24439. * A reference to the camera.
  24440. *
  24441. * @type {Camera}
  24442. */
  24443. this.camera = camera;
  24444. /**
  24445. * Options for the internal render target.
  24446. *
  24447. * @type {Object}
  24448. */
  24449. this.options = options;
  24450. /**
  24451. * The pass's pixel ratio. Will be kept automatically kept in sync with the renderer's pixel ratio.
  24452. *
  24453. * @private
  24454. * @type {number}
  24455. * @default 1
  24456. */
  24457. this._pixelRatio = 1;
  24458. /**
  24459. * The pass's pixel width. Will be kept automatically kept in sync with the renderer's width.
  24460. * @private
  24461. * @type {number}
  24462. * @default 1
  24463. */
  24464. this._width = 1;
  24465. /**
  24466. * The pass's pixel height. Will be kept automatically kept in sync with the renderer's height.
  24467. * @private
  24468. * @type {number}
  24469. * @default 1
  24470. */
  24471. this._height = 1;
  24472. const depthTexture = new DepthTexture();
  24473. depthTexture.isRenderTargetTexture = true;
  24474. //depthTexture.type = FloatType;
  24475. depthTexture.name = 'depth';
  24476. const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType, ...options, } );
  24477. renderTarget.texture.name = 'output';
  24478. renderTarget.depthTexture = depthTexture;
  24479. /**
  24480. * The pass's render target.
  24481. *
  24482. * @type {RenderTarget}
  24483. */
  24484. this.renderTarget = renderTarget;
  24485. /**
  24486. * A dictionary holding the internal result textures.
  24487. *
  24488. * @private
  24489. * @type {Object<string, Texture>}
  24490. */
  24491. this._textures = {
  24492. output: renderTarget.texture,
  24493. depth: depthTexture
  24494. };
  24495. /**
  24496. * A dictionary holding the internal texture nodes.
  24497. *
  24498. * @private
  24499. * @type {Object<string, TextureNode>}
  24500. */
  24501. this._textureNodes = {};
  24502. /**
  24503. * A dictionary holding the internal depth nodes.
  24504. *
  24505. * @private
  24506. * @type {Object}
  24507. */
  24508. this._linearDepthNodes = {};
  24509. /**
  24510. * A dictionary holding the internal viewZ nodes.
  24511. *
  24512. * @private
  24513. * @type {Object}
  24514. */
  24515. this._viewZNodes = {};
  24516. /**
  24517. * A dictionary holding the texture data of the previous frame.
  24518. * Used for computing velocity/motion vectors.
  24519. *
  24520. * @private
  24521. * @type {Object<string, Texture>}
  24522. */
  24523. this._previousTextures = {};
  24524. /**
  24525. * A dictionary holding the texture nodes of the previous frame.
  24526. * Used for computing velocity/motion vectors.
  24527. *
  24528. * @private
  24529. * @type {Object<string, TextureNode>}
  24530. */
  24531. this._previousTextureNodes = {};
  24532. /**
  24533. * The `near` property of the camera as a uniform.
  24534. *
  24535. * @private
  24536. * @type {UniformNode}
  24537. */
  24538. this._cameraNear = uniform( 0 );
  24539. /**
  24540. * The `far` property of the camera as a uniform.
  24541. *
  24542. * @private
  24543. * @type {UniformNode}
  24544. */
  24545. this._cameraFar = uniform( 0 );
  24546. /**
  24547. * A MRT node configuring the MRT settings.
  24548. *
  24549. * @private
  24550. * @type {?MRTNode}
  24551. * @default null
  24552. */
  24553. this._mrt = null;
  24554. this._layers = null;
  24555. this._resolution = 1;
  24556. /**
  24557. * This flag can be used for type testing.
  24558. *
  24559. * @type {boolean}
  24560. * @readonly
  24561. * @default true
  24562. */
  24563. this.isPassNode = true;
  24564. /**
  24565. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  24566. * scene once per frame in its {@link PassNode#updateBefore} method.
  24567. *
  24568. * @type {string}
  24569. * @default 'frame'
  24570. */
  24571. this.updateBeforeType = NodeUpdateType.FRAME;
  24572. /**
  24573. * This flag is used for global cache.
  24574. *
  24575. * @type {boolean}
  24576. * @default true
  24577. */
  24578. this.global = true;
  24579. }
  24580. /**
  24581. * Sets the resolution for the pass.
  24582. * The resolution is a factor that is multiplied with the renderer's width and height.
  24583. *
  24584. * @param {number} resolution - The resolution to set. A value of `1` means full resolution.
  24585. * @return {PassNode} A reference to this pass.
  24586. */
  24587. setResolution( resolution ) {
  24588. this._resolution = resolution;
  24589. return this;
  24590. }
  24591. /**
  24592. * Gets the current resolution of the pass.
  24593. *
  24594. * @return {number} The current resolution. A value of `1` means full resolution.
  24595. * @default 1
  24596. */
  24597. getResolution() {
  24598. return this._resolution;
  24599. }
  24600. setLayers( layers ) {
  24601. this._layers = layers;
  24602. return this;
  24603. }
  24604. getLayers() {
  24605. return this._layers;
  24606. }
  24607. /**
  24608. * Sets the given MRT node to setup MRT for this pass.
  24609. *
  24610. * @param {MRTNode} mrt - The MRT object.
  24611. * @return {PassNode} A reference to this pass.
  24612. */
  24613. setMRT( mrt ) {
  24614. this._mrt = mrt;
  24615. return this;
  24616. }
  24617. /**
  24618. * Returns the current MRT node.
  24619. *
  24620. * @return {MRTNode} The current MRT node.
  24621. */
  24622. getMRT() {
  24623. return this._mrt;
  24624. }
  24625. /**
  24626. * Returns the texture for the given output name.
  24627. *
  24628. * @param {string} name - The output name to get the texture for.
  24629. * @return {Texture} The texture.
  24630. */
  24631. getTexture( name ) {
  24632. let texture = this._textures[ name ];
  24633. if ( texture === undefined ) {
  24634. const refTexture = this.renderTarget.texture;
  24635. texture = refTexture.clone();
  24636. texture.name = name;
  24637. this._textures[ name ] = texture;
  24638. this.renderTarget.textures.push( texture );
  24639. }
  24640. return texture;
  24641. }
  24642. /**
  24643. * Returns the texture holding the data of the previous frame for the given output name.
  24644. *
  24645. * @param {string} name - The output name to get the texture for.
  24646. * @return {Texture} The texture holding the data of the previous frame.
  24647. */
  24648. getPreviousTexture( name ) {
  24649. let texture = this._previousTextures[ name ];
  24650. if ( texture === undefined ) {
  24651. texture = this.getTexture( name ).clone();
  24652. this._previousTextures[ name ] = texture;
  24653. }
  24654. return texture;
  24655. }
  24656. /**
  24657. * Switches current and previous textures for the given output name.
  24658. *
  24659. * @param {string} name - The output name.
  24660. */
  24661. toggleTexture( name ) {
  24662. const prevTexture = this._previousTextures[ name ];
  24663. if ( prevTexture !== undefined ) {
  24664. const texture = this._textures[ name ];
  24665. const index = this.renderTarget.textures.indexOf( texture );
  24666. this.renderTarget.textures[ index ] = prevTexture;
  24667. this._textures[ name ] = prevTexture;
  24668. this._previousTextures[ name ] = texture;
  24669. this._textureNodes[ name ].updateTexture();
  24670. this._previousTextureNodes[ name ].updateTexture();
  24671. }
  24672. }
  24673. /**
  24674. * Returns the texture node for the given output name.
  24675. *
  24676. * @param {string} [name='output'] - The output name to get the texture node for.
  24677. * @return {TextureNode} The texture node.
  24678. */
  24679. getTextureNode( name = 'output' ) {
  24680. let textureNode = this._textureNodes[ name ];
  24681. if ( textureNode === undefined ) {
  24682. textureNode = nodeObject( new PassMultipleTextureNode( this, name ) );
  24683. textureNode.updateTexture();
  24684. this._textureNodes[ name ] = textureNode;
  24685. }
  24686. return textureNode;
  24687. }
  24688. /**
  24689. * Returns the previous texture node for the given output name.
  24690. *
  24691. * @param {string} [name='output'] - The output name to get the previous texture node for.
  24692. * @return {TextureNode} The previous texture node.
  24693. */
  24694. getPreviousTextureNode( name = 'output' ) {
  24695. let textureNode = this._previousTextureNodes[ name ];
  24696. if ( textureNode === undefined ) {
  24697. if ( this._textureNodes[ name ] === undefined ) this.getTextureNode( name );
  24698. textureNode = nodeObject( new PassMultipleTextureNode( this, name, true ) );
  24699. textureNode.updateTexture();
  24700. this._previousTextureNodes[ name ] = textureNode;
  24701. }
  24702. return textureNode;
  24703. }
  24704. /**
  24705. * Returns a viewZ node of this pass.
  24706. *
  24707. * @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.
  24708. * @return {Node} The viewZ node.
  24709. */
  24710. getViewZNode( name = 'depth' ) {
  24711. let viewZNode = this._viewZNodes[ name ];
  24712. if ( viewZNode === undefined ) {
  24713. const cameraNear = this._cameraNear;
  24714. const cameraFar = this._cameraFar;
  24715. this._viewZNodes[ name ] = viewZNode = perspectiveDepthToViewZ( this.getTextureNode( name ), cameraNear, cameraFar );
  24716. }
  24717. return viewZNode;
  24718. }
  24719. /**
  24720. * Returns a linear depth node of this pass.
  24721. *
  24722. * @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.
  24723. * @return {Node} The linear depth node.
  24724. */
  24725. getLinearDepthNode( name = 'depth' ) {
  24726. let linearDepthNode = this._linearDepthNodes[ name ];
  24727. if ( linearDepthNode === undefined ) {
  24728. const cameraNear = this._cameraNear;
  24729. const cameraFar = this._cameraFar;
  24730. const viewZNode = this.getViewZNode( name );
  24731. // TODO: just if ( builder.camera.isPerspectiveCamera )
  24732. this._linearDepthNodes[ name ] = linearDepthNode = viewZToOrthographicDepth( viewZNode, cameraNear, cameraFar );
  24733. }
  24734. return linearDepthNode;
  24735. }
  24736. setup( { renderer } ) {
  24737. this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples;
  24738. // TODO: Disable MSAA for WebGL backend for now
  24739. if ( renderer.backend.isWebGLBackend === true ) {
  24740. this.renderTarget.samples = 0;
  24741. }
  24742. this.renderTarget.texture.type = renderer.getColorBufferType();
  24743. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  24744. }
  24745. updateBefore( frame ) {
  24746. const { renderer } = frame;
  24747. const { scene } = this;
  24748. let camera;
  24749. let pixelRatio;
  24750. const outputRenderTarget = renderer.getOutputRenderTarget();
  24751. if ( outputRenderTarget && outputRenderTarget.isXRRenderTarget === true ) {
  24752. pixelRatio = 1;
  24753. camera = renderer.xr.getCamera();
  24754. renderer.xr.updateCamera( camera );
  24755. _size.set( outputRenderTarget.width, outputRenderTarget.height );
  24756. } else {
  24757. camera = this.camera;
  24758. pixelRatio = renderer.getPixelRatio();
  24759. renderer.getSize( _size );
  24760. }
  24761. this._pixelRatio = pixelRatio;
  24762. this.setSize( _size.width, _size.height );
  24763. const currentRenderTarget = renderer.getRenderTarget();
  24764. const currentMRT = renderer.getMRT();
  24765. const currentMask = camera.layers.mask;
  24766. this._cameraNear.value = camera.near;
  24767. this._cameraFar.value = camera.far;
  24768. if ( this._layers !== null ) {
  24769. camera.layers.mask = this._layers.mask;
  24770. }
  24771. for ( const name in this._previousTextures ) {
  24772. this.toggleTexture( name );
  24773. }
  24774. renderer.setRenderTarget( this.renderTarget );
  24775. renderer.setMRT( this._mrt );
  24776. renderer.render( scene, camera );
  24777. renderer.setRenderTarget( currentRenderTarget );
  24778. renderer.setMRT( currentMRT );
  24779. camera.layers.mask = currentMask;
  24780. }
  24781. /**
  24782. * Sets the size of the pass's render target. Honors the pixel ratio.
  24783. *
  24784. * @param {number} width - The width to set.
  24785. * @param {number} height - The height to set.
  24786. */
  24787. setSize( width, height ) {
  24788. this._width = width;
  24789. this._height = height;
  24790. const effectiveWidth = this._width * this._pixelRatio * this._resolution;
  24791. const effectiveHeight = this._height * this._pixelRatio * this._resolution;
  24792. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  24793. }
  24794. /**
  24795. * Sets the pixel ratio the pass's render target and updates the size.
  24796. *
  24797. * @param {number} pixelRatio - The pixel ratio to set.
  24798. */
  24799. setPixelRatio( pixelRatio ) {
  24800. this._pixelRatio = pixelRatio;
  24801. this.setSize( this._width, this._height );
  24802. }
  24803. /**
  24804. * Frees internal resources. Should be called when the node is no longer in use.
  24805. */
  24806. dispose() {
  24807. this.renderTarget.dispose();
  24808. }
  24809. }
  24810. /**
  24811. * @static
  24812. * @type {'color'}
  24813. * @default 'color'
  24814. */
  24815. PassNode.COLOR = 'color';
  24816. /**
  24817. * @static
  24818. * @type {'depth'}
  24819. * @default 'depth'
  24820. */
  24821. PassNode.DEPTH = 'depth';
  24822. /**
  24823. * TSL function for creating a pass node.
  24824. *
  24825. * @tsl
  24826. * @function
  24827. * @param {Scene} scene - A reference to the scene.
  24828. * @param {Camera} camera - A reference to the camera.
  24829. * @param {Object} options - Options for the internal render target.
  24830. * @returns {PassNode}
  24831. */
  24832. const pass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera, options ) );
  24833. /**
  24834. * TSL function for creating a pass texture node.
  24835. *
  24836. * @tsl
  24837. * @function
  24838. * @param {PassNode} pass - The pass node.
  24839. * @param {Texture} texture - The output texture.
  24840. * @returns {PassTextureNode}
  24841. */
  24842. const passTexture = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) );
  24843. /**
  24844. * TSL function for creating a depth pass node.
  24845. *
  24846. * @tsl
  24847. * @function
  24848. * @param {Scene} scene - A reference to the scene.
  24849. * @param {Camera} camera - A reference to the camera.
  24850. * @param {Object} options - Options for the internal render target.
  24851. * @returns {PassNode}
  24852. */
  24853. const depthPass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera, options ) );
  24854. /**
  24855. * Represents a render pass for producing a toon outline effect on compatible objects.
  24856. * Only 3D objects with materials of type `MeshToonMaterial` and `MeshToonNodeMaterial`
  24857. * will receive the outline.
  24858. *
  24859. * ```js
  24860. * const postProcessing = new PostProcessing( renderer );
  24861. *
  24862. * const scenePass = toonOutlinePass( scene, camera );
  24863. *
  24864. * postProcessing.outputNode = scenePass;
  24865. * ```
  24866. * @augments PassNode
  24867. */
  24868. class ToonOutlinePassNode extends PassNode {
  24869. static get type() {
  24870. return 'ToonOutlinePassNode';
  24871. }
  24872. /**
  24873. * Constructs a new outline pass node.
  24874. *
  24875. * @param {Scene} scene - A reference to the scene.
  24876. * @param {Camera} camera - A reference to the camera.
  24877. * @param {Node} colorNode - Defines the outline's color.
  24878. * @param {Node} thicknessNode - Defines the outline's thickness.
  24879. * @param {Node} alphaNode - Defines the outline's alpha.
  24880. */
  24881. constructor( scene, camera, colorNode, thicknessNode, alphaNode ) {
  24882. super( PassNode.COLOR, scene, camera );
  24883. /**
  24884. * Defines the outline's color.
  24885. *
  24886. * @type {Node}
  24887. */
  24888. this.colorNode = colorNode;
  24889. /**
  24890. * Defines the outline's thickness.
  24891. *
  24892. * @type {Node}
  24893. */
  24894. this.thicknessNode = thicknessNode;
  24895. /**
  24896. * Defines the outline's alpha.
  24897. *
  24898. * @type {Node}
  24899. */
  24900. this.alphaNode = alphaNode;
  24901. /**
  24902. * An internal material cache.
  24903. *
  24904. * @private
  24905. * @type {WeakMap<Material, NodeMaterial>}
  24906. */
  24907. this._materialCache = new WeakMap();
  24908. }
  24909. updateBefore( frame ) {
  24910. const { renderer } = frame;
  24911. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  24912. renderer.setRenderObjectFunction( ( object, scene, camera, geometry, material, group, lightsNode, clippingContext ) => {
  24913. // only render outline for supported materials
  24914. if ( material.isMeshToonMaterial || material.isMeshToonNodeMaterial ) {
  24915. if ( material.wireframe === false ) {
  24916. const outlineMaterial = this._getOutlineMaterial( material );
  24917. renderer.renderObject( object, scene, camera, geometry, outlineMaterial, group, lightsNode, clippingContext );
  24918. }
  24919. }
  24920. // default
  24921. renderer.renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext );
  24922. } );
  24923. super.updateBefore( frame );
  24924. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  24925. }
  24926. /**
  24927. * Creates the material used for outline rendering.
  24928. *
  24929. * @private
  24930. * @return {NodeMaterial} The outline material.
  24931. */
  24932. _createMaterial() {
  24933. const material = new NodeMaterial();
  24934. material.isMeshToonOutlineMaterial = true;
  24935. material.name = 'Toon_Outline';
  24936. material.side = BackSide;
  24937. // vertex node
  24938. const outlineNormal = normalLocal.negate();
  24939. const mvp = cameraProjectionMatrix.mul( modelViewMatrix );
  24940. const ratio = float( 1.0 ); // TODO: support outline thickness ratio for each vertex
  24941. const pos = mvp.mul( vec4( positionLocal, 1.0 ) );
  24942. const pos2 = mvp.mul( vec4( positionLocal.add( outlineNormal ), 1.0 ) );
  24943. const norm = normalize( pos.sub( pos2 ) ); // NOTE: subtract pos2 from pos because BackSide objectNormal is negative
  24944. material.vertexNode = pos.add( norm.mul( this.thicknessNode ).mul( pos.w ).mul( ratio ) );
  24945. // color node
  24946. material.colorNode = vec4( this.colorNode, this.alphaNode );
  24947. return material;
  24948. }
  24949. /**
  24950. * For the given toon material, this method returns a corresponding
  24951. * outline material.
  24952. *
  24953. * @private
  24954. * @param {(MeshToonMaterial|MeshToonNodeMaterial)} originalMaterial - The toon material.
  24955. * @return {NodeMaterial} The outline material.
  24956. */
  24957. _getOutlineMaterial( originalMaterial ) {
  24958. let outlineMaterial = this._materialCache.get( originalMaterial );
  24959. if ( outlineMaterial === undefined ) {
  24960. outlineMaterial = this._createMaterial();
  24961. this._materialCache.set( originalMaterial, outlineMaterial );
  24962. }
  24963. return outlineMaterial;
  24964. }
  24965. }
  24966. /**
  24967. * TSL function for creating a toon outline pass node.
  24968. *
  24969. * @tsl
  24970. * @function
  24971. * @param {Scene} scene - A reference to the scene.
  24972. * @param {Camera} camera - A reference to the camera.
  24973. * @param {Color} color - Defines the outline's color.
  24974. * @param {number} [thickness=0.003] - Defines the outline's thickness.
  24975. * @param {number} [alpha=1] - Defines the outline's alpha.
  24976. * @returns {ToonOutlinePassNode}
  24977. */
  24978. 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 ) ) );
  24979. /**
  24980. * Linear tone mapping, exposure only.
  24981. *
  24982. * @tsl
  24983. * @function
  24984. * @param {Node<vec3>} color - The color that should be tone mapped.
  24985. * @param {Node<float>} exposure - The exposure.
  24986. * @return {Node<vec3>} The tone mapped color.
  24987. */
  24988. const linearToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  24989. return color.mul( exposure ).clamp();
  24990. } ).setLayout( {
  24991. name: 'linearToneMapping',
  24992. type: 'vec3',
  24993. inputs: [
  24994. { name: 'color', type: 'vec3' },
  24995. { name: 'exposure', type: 'float' }
  24996. ]
  24997. } );
  24998. /**
  24999. * Reinhard tone mapping.
  25000. *
  25001. * Reference: {@link https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf}
  25002. *
  25003. * @tsl
  25004. * @function
  25005. * @param {Node<vec3>} color - The color that should be tone mapped.
  25006. * @param {Node<float>} exposure - The exposure.
  25007. * @return {Node<vec3>} The tone mapped color.
  25008. */
  25009. const reinhardToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  25010. color = color.mul( exposure );
  25011. return color.div( color.add( 1.0 ) ).clamp();
  25012. } ).setLayout( {
  25013. name: 'reinhardToneMapping',
  25014. type: 'vec3',
  25015. inputs: [
  25016. { name: 'color', type: 'vec3' },
  25017. { name: 'exposure', type: 'float' }
  25018. ]
  25019. } );
  25020. /**
  25021. * Cineon tone mapping.
  25022. *
  25023. * Reference: {@link http://filmicworlds.com/blog/filmic-tonemapping-operators/}
  25024. *
  25025. * @tsl
  25026. * @function
  25027. * @param {Node<vec3>} color - The color that should be tone mapped.
  25028. * @param {Node<float>} exposure - The exposure.
  25029. * @return {Node<vec3>} The tone mapped color.
  25030. */
  25031. const cineonToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  25032. // filmic operator by Jim Hejl and Richard Burgess-Dawson
  25033. color = color.mul( exposure );
  25034. color = color.sub( 0.004 ).max( 0.0 );
  25035. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  25036. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  25037. return a.div( b ).pow( 2.2 );
  25038. } ).setLayout( {
  25039. name: 'cineonToneMapping',
  25040. type: 'vec3',
  25041. inputs: [
  25042. { name: 'color', type: 'vec3' },
  25043. { name: 'exposure', type: 'float' }
  25044. ]
  25045. } );
  25046. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  25047. const RRTAndODTFit = /*@__PURE__*/ Fn( ( [ color ] ) => {
  25048. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  25049. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  25050. return a.div( b );
  25051. } );
  25052. /**
  25053. * ACESFilmic tone mapping.
  25054. *
  25055. * Reference: {@link https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs}
  25056. *
  25057. * @tsl
  25058. * @function
  25059. * @param {Node<vec3>} color - The color that should be tone mapped.
  25060. * @param {Node<float>} exposure - The exposure.
  25061. * @return {Node<vec3>} The tone mapped color.
  25062. */
  25063. const acesFilmicToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  25064. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  25065. const ACESInputMat = mat3(
  25066. 0.59719, 0.35458, 0.04823,
  25067. 0.07600, 0.90834, 0.01566,
  25068. 0.02840, 0.13383, 0.83777
  25069. );
  25070. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  25071. const ACESOutputMat = mat3(
  25072. 1.60475, -0.53108, -0.07367,
  25073. -0.10208, 1.10813, -605e-5,
  25074. -327e-5, -0.07276, 1.07602
  25075. );
  25076. color = color.mul( exposure ).div( 0.6 );
  25077. color = ACESInputMat.mul( color );
  25078. // Apply RRT and ODT
  25079. color = RRTAndODTFit( color );
  25080. color = ACESOutputMat.mul( color );
  25081. // Clamp to [0, 1]
  25082. return color.clamp();
  25083. } ).setLayout( {
  25084. name: 'acesFilmicToneMapping',
  25085. type: 'vec3',
  25086. inputs: [
  25087. { name: 'color', type: 'vec3' },
  25088. { name: 'exposure', type: 'float' }
  25089. ]
  25090. } );
  25091. 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 ) );
  25092. 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 ) );
  25093. const agxDefaultContrastApprox = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  25094. const x = vec3( x_immutable ).toVar();
  25095. const x2 = vec3( x.mul( x ) ).toVar();
  25096. const x4 = vec3( x2.mul( x2 ) ).toVar();
  25097. 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 ) ) ) );
  25098. } );
  25099. /**
  25100. * AgX tone mapping.
  25101. *
  25102. * @tsl
  25103. * @function
  25104. * @param {Node<vec3>} color - The color that should be tone mapped.
  25105. * @param {Node<float>} exposure - The exposure.
  25106. * @return {Node<vec3>} The tone mapped color.
  25107. */
  25108. const agxToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  25109. const colortone = vec3( color ).toVar();
  25110. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  25111. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, -0.1413297634984383, -0.14132976349843826 ), vec3( -0.11060664309660323, 1.157823702216272, -0.11060664309660294 ), vec3( -0.016493938717834573, -0.016493938717834257, 1.2519364065950405 ) );
  25112. const AgxMinEv = float( -12.47393 );
  25113. const AgxMaxEv = float( 4.026069 );
  25114. colortone.mulAssign( exposure );
  25115. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  25116. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  25117. colortone.assign( max$1( colortone, 1e-10 ) );
  25118. colortone.assign( log2( colortone ) );
  25119. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  25120. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  25121. colortone.assign( agxDefaultContrastApprox( colortone ) );
  25122. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  25123. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  25124. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  25125. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  25126. return colortone;
  25127. } ).setLayout( {
  25128. name: 'agxToneMapping',
  25129. type: 'vec3',
  25130. inputs: [
  25131. { name: 'color', type: 'vec3' },
  25132. { name: 'exposure', type: 'float' }
  25133. ]
  25134. } );
  25135. /**
  25136. * Neutral tone mapping.
  25137. *
  25138. * Reference: {@link https://modelviewer.dev/examples/tone-mapping}
  25139. *
  25140. * @tsl
  25141. * @function
  25142. * @param {Node<vec3>} color - The color that should be tone mapped.
  25143. * @param {Node<float>} exposure - The exposure.
  25144. * @return {Node<vec3>} The tone mapped color.
  25145. */
  25146. const neutralToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  25147. const StartCompression = float( 0.8 - 0.04 );
  25148. const Desaturation = float( 0.15 );
  25149. color = color.mul( exposure );
  25150. const x = min$1( color.r, min$1( color.g, color.b ) );
  25151. const offset = select( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  25152. color.subAssign( offset );
  25153. const peak = max$1( color.r, max$1( color.g, color.b ) );
  25154. If( peak.lessThan( StartCompression ), () => {
  25155. return color;
  25156. } );
  25157. const d = sub( 1, StartCompression );
  25158. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  25159. color.mulAssign( newPeak.div( peak ) );
  25160. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  25161. return mix( color, vec3( newPeak ), g );
  25162. } ).setLayout( {
  25163. name: 'neutralToneMapping',
  25164. type: 'vec3',
  25165. inputs: [
  25166. { name: 'color', type: 'vec3' },
  25167. { name: 'exposure', type: 'float' }
  25168. ]
  25169. } );
  25170. /**
  25171. * This class represents native code sections. It is the base
  25172. * class for modules like {@link FunctionNode} which allows to implement
  25173. * functions with native shader languages.
  25174. *
  25175. * @augments Node
  25176. */
  25177. class CodeNode extends Node {
  25178. static get type() {
  25179. return 'CodeNode';
  25180. }
  25181. /**
  25182. * Constructs a new code node.
  25183. *
  25184. * @param {string} [code=''] - The native code.
  25185. * @param {Array<Node>} [includes=[]] - An array of includes.
  25186. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  25187. */
  25188. constructor( code = '', includes = [], language = '' ) {
  25189. super( 'code' );
  25190. /**
  25191. * This flag can be used for type testing.
  25192. *
  25193. * @type {boolean}
  25194. * @readonly
  25195. * @default true
  25196. */
  25197. this.isCodeNode = true;
  25198. /**
  25199. * This flag is used for global cache.
  25200. *
  25201. * @type {boolean}
  25202. * @default true
  25203. */
  25204. this.global = true;
  25205. /**
  25206. * The native code.
  25207. *
  25208. * @type {string}
  25209. * @default ''
  25210. */
  25211. this.code = code;
  25212. /**
  25213. * An array of includes
  25214. *
  25215. * @type {Array<Node>}
  25216. * @default []
  25217. */
  25218. this.includes = includes;
  25219. /**
  25220. * The used language.
  25221. *
  25222. * @type {('js'|'wgsl'|'glsl')}
  25223. * @default ''
  25224. */
  25225. this.language = language;
  25226. }
  25227. /**
  25228. * Sets the includes of this code node.
  25229. *
  25230. * @param {Array<Node>} includes - The includes to set.
  25231. * @return {CodeNode} A reference to this node.
  25232. */
  25233. setIncludes( includes ) {
  25234. this.includes = includes;
  25235. return this;
  25236. }
  25237. /**
  25238. * Returns the includes of this code node.
  25239. *
  25240. * @param {NodeBuilder} builder - The current node builder.
  25241. * @return {Array<Node>} The includes.
  25242. */
  25243. getIncludes( /*builder*/ ) {
  25244. return this.includes;
  25245. }
  25246. generate( builder ) {
  25247. const includes = this.getIncludes( builder );
  25248. for ( const include of includes ) {
  25249. include.build( builder );
  25250. }
  25251. const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) );
  25252. nodeCode.code = this.code;
  25253. return nodeCode.code;
  25254. }
  25255. serialize( data ) {
  25256. super.serialize( data );
  25257. data.code = this.code;
  25258. data.language = this.language;
  25259. }
  25260. deserialize( data ) {
  25261. super.deserialize( data );
  25262. this.code = data.code;
  25263. this.language = data.language;
  25264. }
  25265. }
  25266. /**
  25267. * TSL function for creating a code node.
  25268. *
  25269. * @tsl
  25270. * @function
  25271. * @param {string} [code] - The native code.
  25272. * @param {?Array<Node>} [includes=[]] - An array of includes.
  25273. * @param {?('js'|'wgsl'|'glsl')} [language=''] - The used language.
  25274. * @returns {CodeNode}
  25275. */
  25276. const code = /*@__PURE__*/ nodeProxy( CodeNode ).setParameterLength( 1, 3 );
  25277. /**
  25278. * TSL function for creating a JS code node.
  25279. *
  25280. * @tsl
  25281. * @function
  25282. * @param {string} src - The native code.
  25283. * @param {Array<Node>} includes - An array of includes.
  25284. * @returns {CodeNode}
  25285. */
  25286. const js = ( src, includes ) => code( src, includes, 'js' );
  25287. /**
  25288. * TSL function for creating a WGSL code node.
  25289. *
  25290. * @tsl
  25291. * @function
  25292. * @param {string} src - The native code.
  25293. * @param {Array<Node>} includes - An array of includes.
  25294. * @returns {CodeNode}
  25295. */
  25296. const wgsl = ( src, includes ) => code( src, includes, 'wgsl' );
  25297. /**
  25298. * TSL function for creating a GLSL code node.
  25299. *
  25300. * @tsl
  25301. * @function
  25302. * @param {string} src - The native code.
  25303. * @param {Array<Node>} includes - An array of includes.
  25304. * @returns {CodeNode}
  25305. */
  25306. const glsl = ( src, includes ) => code( src, includes, 'glsl' );
  25307. /**
  25308. * This class represents a native shader function. It can be used to implement
  25309. * certain aspects of a node material with native shader code. There are two predefined
  25310. * TSL functions for easier usage.
  25311. *
  25312. * - `wgslFn`: Creates a WGSL function node.
  25313. * - `glslFn`: Creates a GLSL function node.
  25314. *
  25315. * A basic example with one include looks like so:
  25316. *
  25317. * ```js
  25318. * const desaturateWGSLFn = wgslFn( `
  25319. * fn desaturate( color:vec3<f32> ) -> vec3<f32> {
  25320. * let lum = vec3<f32>( 0.299, 0.587, 0.114 );
  25321. * return vec3<f32>( dot( lum, color ) );
  25322. * }`
  25323. *);
  25324. * const someWGSLFn = wgslFn( `
  25325. * fn someFn( color:vec3<f32> ) -> vec3<f32> {
  25326. * return desaturate( color );
  25327. * }
  25328. * `, [ desaturateWGSLFn ] );
  25329. * material.colorNode = someWGSLFn( { color: texture( map ) } );
  25330. *```
  25331. * @augments CodeNode
  25332. */
  25333. class FunctionNode extends CodeNode {
  25334. static get type() {
  25335. return 'FunctionNode';
  25336. }
  25337. /**
  25338. * Constructs a new function node.
  25339. *
  25340. * @param {string} [code=''] - The native code.
  25341. * @param {Array<Node>} [includes=[]] - An array of includes.
  25342. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  25343. */
  25344. constructor( code = '', includes = [], language = '' ) {
  25345. super( code, includes, language );
  25346. }
  25347. getNodeType( builder ) {
  25348. return this.getNodeFunction( builder ).type;
  25349. }
  25350. /**
  25351. * Returns the inputs of this function node.
  25352. *
  25353. * @param {NodeBuilder} builder - The current node builder.
  25354. * @return {Array<NodeFunctionInput>} The inputs.
  25355. */
  25356. getInputs( builder ) {
  25357. return this.getNodeFunction( builder ).inputs;
  25358. }
  25359. /**
  25360. * Returns the node function for this function node.
  25361. *
  25362. * @param {NodeBuilder} builder - The current node builder.
  25363. * @return {NodeFunction} The node function.
  25364. */
  25365. getNodeFunction( builder ) {
  25366. const nodeData = builder.getDataFromNode( this );
  25367. let nodeFunction = nodeData.nodeFunction;
  25368. if ( nodeFunction === undefined ) {
  25369. nodeFunction = builder.parser.parseFunction( this.code );
  25370. nodeData.nodeFunction = nodeFunction;
  25371. }
  25372. return nodeFunction;
  25373. }
  25374. generate( builder, output ) {
  25375. super.generate( builder );
  25376. const nodeFunction = this.getNodeFunction( builder );
  25377. const name = nodeFunction.name;
  25378. const type = nodeFunction.type;
  25379. const nodeCode = builder.getCodeFromNode( this, type );
  25380. if ( name !== '' ) {
  25381. // use a custom property name
  25382. nodeCode.name = name;
  25383. }
  25384. const propertyName = builder.getPropertyName( nodeCode );
  25385. const code = this.getNodeFunction( builder ).getCode( propertyName );
  25386. nodeCode.code = code + '\n';
  25387. if ( output === 'property' ) {
  25388. return propertyName;
  25389. } else {
  25390. return builder.format( `${ propertyName }()`, type, output );
  25391. }
  25392. }
  25393. }
  25394. const nativeFn = ( code, includes = [], language = '' ) => {
  25395. for ( let i = 0; i < includes.length; i ++ ) {
  25396. const include = includes[ i ];
  25397. // TSL Function: glslFn, wgslFn
  25398. if ( typeof include === 'function' ) {
  25399. includes[ i ] = include.functionNode;
  25400. }
  25401. }
  25402. const functionNode = nodeObject( new FunctionNode( code, includes, language ) );
  25403. const fn = ( ...params ) => functionNode.call( ...params );
  25404. fn.functionNode = functionNode;
  25405. return fn;
  25406. };
  25407. const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' );
  25408. const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' );
  25409. /**
  25410. * `ScriptableNode` uses this class to manage script inputs and outputs.
  25411. *
  25412. * @augments Node
  25413. */
  25414. class ScriptableValueNode extends Node {
  25415. static get type() {
  25416. return 'ScriptableValueNode';
  25417. }
  25418. /**
  25419. * Constructs a new scriptable node.
  25420. *
  25421. * @param {any} [value=null] - The value.
  25422. */
  25423. constructor( value = null ) {
  25424. super();
  25425. /**
  25426. * A reference to the value.
  25427. *
  25428. * @private
  25429. * @default null
  25430. */
  25431. this._value = value;
  25432. /**
  25433. * Depending on the type of `_value`, this property might cache parsed data.
  25434. *
  25435. * @private
  25436. * @default null
  25437. */
  25438. this._cache = null;
  25439. /**
  25440. * If this node represents an input, this property represents the input type.
  25441. *
  25442. * @type {?string}
  25443. * @default null
  25444. */
  25445. this.inputType = null;
  25446. /**
  25447. * If this node represents an output, this property represents the output type.
  25448. *
  25449. * @type {?string}
  25450. * @default null
  25451. */
  25452. this.outputType = null;
  25453. /**
  25454. * An event dispatcher for managing events.
  25455. *
  25456. * @type {EventDispatcher}
  25457. */
  25458. this.events = new EventDispatcher();
  25459. /**
  25460. * This flag can be used for type testing.
  25461. *
  25462. * @type {boolean}
  25463. * @readonly
  25464. * @default true
  25465. */
  25466. this.isScriptableValueNode = true;
  25467. }
  25468. /**
  25469. * Whether this node represents an output or not.
  25470. *
  25471. * @type {boolean}
  25472. * @readonly
  25473. * @default true
  25474. */
  25475. get isScriptableOutputNode() {
  25476. return this.outputType !== null;
  25477. }
  25478. set value( val ) {
  25479. if ( this._value === val ) return;
  25480. if ( this._cache && this.inputType === 'URL' && this.value.value instanceof ArrayBuffer ) {
  25481. URL.revokeObjectURL( this._cache );
  25482. this._cache = null;
  25483. }
  25484. this._value = val;
  25485. this.events.dispatchEvent( { type: 'change' } );
  25486. this.refresh();
  25487. }
  25488. /**
  25489. * The node's value.
  25490. *
  25491. * @type {any}
  25492. */
  25493. get value() {
  25494. return this._value;
  25495. }
  25496. /**
  25497. * Dispatches the `refresh` event.
  25498. */
  25499. refresh() {
  25500. this.events.dispatchEvent( { type: 'refresh' } );
  25501. }
  25502. /**
  25503. * The `value` property usually represents a node or even binary data in form of array buffers.
  25504. * In this case, this method tries to return the actual value behind the complex type.
  25505. *
  25506. * @return {any} The value.
  25507. */
  25508. getValue() {
  25509. const value = this.value;
  25510. if ( value && this._cache === null && this.inputType === 'URL' && value.value instanceof ArrayBuffer ) {
  25511. this._cache = URL.createObjectURL( new Blob( [ value.value ] ) );
  25512. } else if ( value && value.value !== null && value.value !== undefined && (
  25513. ( ( this.inputType === 'URL' || this.inputType === 'String' ) && typeof value.value === 'string' ) ||
  25514. ( this.inputType === 'Number' && typeof value.value === 'number' ) ||
  25515. ( this.inputType === 'Vector2' && value.value.isVector2 ) ||
  25516. ( this.inputType === 'Vector3' && value.value.isVector3 ) ||
  25517. ( this.inputType === 'Vector4' && value.value.isVector4 ) ||
  25518. ( this.inputType === 'Color' && value.value.isColor ) ||
  25519. ( this.inputType === 'Matrix3' && value.value.isMatrix3 ) ||
  25520. ( this.inputType === 'Matrix4' && value.value.isMatrix4 )
  25521. ) ) {
  25522. return value.value;
  25523. }
  25524. return this._cache || value;
  25525. }
  25526. /**
  25527. * Overwritten since the node type is inferred from the value.
  25528. *
  25529. * @param {NodeBuilder} builder - The current node builder.
  25530. * @return {string} The node type.
  25531. */
  25532. getNodeType( builder ) {
  25533. return this.value && this.value.isNode ? this.value.getNodeType( builder ) : 'float';
  25534. }
  25535. setup() {
  25536. return this.value && this.value.isNode ? this.value : float();
  25537. }
  25538. serialize( data ) {
  25539. super.serialize( data );
  25540. if ( this.value !== null ) {
  25541. if ( this.inputType === 'ArrayBuffer' ) {
  25542. data.value = arrayBufferToBase64( this.value );
  25543. } else {
  25544. data.value = this.value ? this.value.toJSON( data.meta ).uuid : null;
  25545. }
  25546. } else {
  25547. data.value = null;
  25548. }
  25549. data.inputType = this.inputType;
  25550. data.outputType = this.outputType;
  25551. }
  25552. deserialize( data ) {
  25553. super.deserialize( data );
  25554. let value = null;
  25555. if ( data.value !== null ) {
  25556. if ( data.inputType === 'ArrayBuffer' ) {
  25557. value = base64ToArrayBuffer( data.value );
  25558. } else if ( data.inputType === 'Texture' ) {
  25559. value = data.meta.textures[ data.value ];
  25560. } else {
  25561. value = data.meta.nodes[ data.value ] || null;
  25562. }
  25563. }
  25564. this.value = value;
  25565. this.inputType = data.inputType;
  25566. this.outputType = data.outputType;
  25567. }
  25568. }
  25569. /**
  25570. * TSL function for creating a scriptable value node.
  25571. *
  25572. * @tsl
  25573. * @function
  25574. * @param {any} [value] - The value.
  25575. * @returns {ScriptableValueNode}
  25576. */
  25577. const scriptableValue = /*@__PURE__*/ nodeProxy( ScriptableValueNode ).setParameterLength( 1 );
  25578. /**
  25579. * A Map-like data structure for managing resources of scriptable nodes.
  25580. *
  25581. * @augments Map
  25582. */
  25583. class Resources extends Map {
  25584. get( key, callback = null, ...params ) {
  25585. if ( this.has( key ) ) return super.get( key );
  25586. if ( callback !== null ) {
  25587. const value = callback( ...params );
  25588. this.set( key, value );
  25589. return value;
  25590. }
  25591. }
  25592. }
  25593. class Parameters {
  25594. constructor( scriptableNode ) {
  25595. this.scriptableNode = scriptableNode;
  25596. }
  25597. get parameters() {
  25598. return this.scriptableNode.parameters;
  25599. }
  25600. get layout() {
  25601. return this.scriptableNode.getLayout();
  25602. }
  25603. getInputLayout( id ) {
  25604. return this.scriptableNode.getInputLayout( id );
  25605. }
  25606. get( name ) {
  25607. const param = this.parameters[ name ];
  25608. const value = param ? param.getValue() : null;
  25609. return value;
  25610. }
  25611. }
  25612. /**
  25613. * Defines the resources (e.g. namespaces) of scriptable nodes.
  25614. *
  25615. * @type {Resources}
  25616. */
  25617. const ScriptableNodeResources = new Resources();
  25618. /**
  25619. * This type of node allows to implement nodes with custom scripts. The script
  25620. * section is represented as an instance of `CodeNode` written with JavaScript.
  25621. * The script itself must adhere to a specific structure.
  25622. *
  25623. * - main(): Executed once by default and every time `node.needsUpdate` is set.
  25624. * - layout: The layout object defines the script's interface (inputs and outputs).
  25625. *
  25626. * ```js
  25627. * ScriptableNodeResources.set( 'TSL', TSL );
  25628. *
  25629. * const scriptableNode = scriptable( js( `
  25630. * layout = {
  25631. * outputType: 'node',
  25632. * elements: [
  25633. * { name: 'source', inputType: 'node' },
  25634. * ]
  25635. * };
  25636. *
  25637. * const { mul, oscSine } = TSL;
  25638. *
  25639. * function main() {
  25640. * const source = parameters.get( 'source' ) || float();
  25641. * return mul( source, oscSine() ) );
  25642. * }
  25643. *
  25644. * ` ) );
  25645. *
  25646. * scriptableNode.setParameter( 'source', color( 1, 0, 0 ) );
  25647. *
  25648. * const material = new THREE.MeshBasicNodeMaterial();
  25649. * material.colorNode = scriptableNode;
  25650. * ```
  25651. *
  25652. * @augments Node
  25653. */
  25654. class ScriptableNode extends Node {
  25655. static get type() {
  25656. return 'ScriptableNode';
  25657. }
  25658. /**
  25659. * Constructs a new scriptable node.
  25660. *
  25661. * @param {?CodeNode} [codeNode=null] - The code node.
  25662. * @param {Object} [parameters={}] - The parameters definition.
  25663. */
  25664. constructor( codeNode = null, parameters = {} ) {
  25665. super();
  25666. /**
  25667. * The code node.
  25668. *
  25669. * @type {?CodeNode}
  25670. * @default null
  25671. */
  25672. this.codeNode = codeNode;
  25673. /**
  25674. * The parameters definition.
  25675. *
  25676. * @type {Object}
  25677. * @default {}
  25678. */
  25679. this.parameters = parameters;
  25680. this._local = new Resources();
  25681. this._output = scriptableValue( null );
  25682. this._outputs = {};
  25683. this._source = this.source;
  25684. this._method = null;
  25685. this._object = null;
  25686. this._value = null;
  25687. this._needsOutputUpdate = true;
  25688. this.onRefresh = this.onRefresh.bind( this );
  25689. /**
  25690. * This flag can be used for type testing.
  25691. *
  25692. * @type {boolean}
  25693. * @readonly
  25694. * @default true
  25695. */
  25696. this.isScriptableNode = true;
  25697. }
  25698. /**
  25699. * The source code of the scriptable node.
  25700. *
  25701. * @type {string}
  25702. */
  25703. get source() {
  25704. return this.codeNode ? this.codeNode.code : '';
  25705. }
  25706. /**
  25707. * Sets the reference of a local script variable.
  25708. *
  25709. * @param {string} name - The variable name.
  25710. * @param {Object} value - The reference to set.
  25711. * @return {Resources} The resource map
  25712. */
  25713. setLocal( name, value ) {
  25714. return this._local.set( name, value );
  25715. }
  25716. /**
  25717. * Gets the value of a local script variable.
  25718. *
  25719. * @param {string} name - The variable name.
  25720. * @return {Object} The value.
  25721. */
  25722. getLocal( name ) {
  25723. return this._local.get( name );
  25724. }
  25725. /**
  25726. * Event listener for the `refresh` event.
  25727. */
  25728. onRefresh() {
  25729. this._refresh();
  25730. }
  25731. /**
  25732. * Returns an input from the layout with the given id/name.
  25733. *
  25734. * @param {string} id - The id/name of the input.
  25735. * @return {Object} The element entry.
  25736. */
  25737. getInputLayout( id ) {
  25738. for ( const element of this.getLayout() ) {
  25739. if ( element.inputType && ( element.id === id || element.name === id ) ) {
  25740. return element;
  25741. }
  25742. }
  25743. }
  25744. /**
  25745. * Returns an output from the layout with the given id/name.
  25746. *
  25747. * @param {string} id - The id/name of the output.
  25748. * @return {Object} The element entry.
  25749. */
  25750. getOutputLayout( id ) {
  25751. for ( const element of this.getLayout() ) {
  25752. if ( element.outputType && ( element.id === id || element.name === id ) ) {
  25753. return element;
  25754. }
  25755. }
  25756. }
  25757. /**
  25758. * Defines a script output for the given name and value.
  25759. *
  25760. * @param {string} name - The name of the output.
  25761. * @param {Node} value - The node value.
  25762. * @return {ScriptableNode} A reference to this node.
  25763. */
  25764. setOutput( name, value ) {
  25765. const outputs = this._outputs;
  25766. if ( outputs[ name ] === undefined ) {
  25767. outputs[ name ] = scriptableValue( value );
  25768. } else {
  25769. outputs[ name ].value = value;
  25770. }
  25771. return this;
  25772. }
  25773. /**
  25774. * Returns a script output for the given name.
  25775. *
  25776. * @param {string} name - The name of the output.
  25777. * @return {ScriptableValueNode} The node value.
  25778. */
  25779. getOutput( name ) {
  25780. return this._outputs[ name ];
  25781. }
  25782. /**
  25783. * Returns a parameter for the given name
  25784. *
  25785. * @param {string} name - The name of the parameter.
  25786. * @return {ScriptableValueNode} The node value.
  25787. */
  25788. getParameter( name ) {
  25789. return this.parameters[ name ];
  25790. }
  25791. /**
  25792. * Sets a value for the given parameter name.
  25793. *
  25794. * @param {string} name - The parameter name.
  25795. * @param {any} value - The parameter value.
  25796. * @return {ScriptableNode} A reference to this node.
  25797. */
  25798. setParameter( name, value ) {
  25799. const parameters = this.parameters;
  25800. if ( value && value.isScriptableNode ) {
  25801. this.deleteParameter( name );
  25802. parameters[ name ] = value;
  25803. parameters[ name ].getDefaultOutput().events.addEventListener( 'refresh', this.onRefresh );
  25804. } else if ( value && value.isScriptableValueNode ) {
  25805. this.deleteParameter( name );
  25806. parameters[ name ] = value;
  25807. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  25808. } else if ( parameters[ name ] === undefined ) {
  25809. parameters[ name ] = scriptableValue( value );
  25810. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  25811. } else {
  25812. parameters[ name ].value = value;
  25813. }
  25814. return this;
  25815. }
  25816. /**
  25817. * Returns the value of this node which is the value of
  25818. * the default output.
  25819. *
  25820. * @return {Node} The value.
  25821. */
  25822. getValue() {
  25823. return this.getDefaultOutput().getValue();
  25824. }
  25825. /**
  25826. * Deletes a parameter from the script.
  25827. *
  25828. * @param {string} name - The parameter to remove.
  25829. * @return {ScriptableNode} A reference to this node.
  25830. */
  25831. deleteParameter( name ) {
  25832. let valueNode = this.parameters[ name ];
  25833. if ( valueNode ) {
  25834. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  25835. valueNode.events.removeEventListener( 'refresh', this.onRefresh );
  25836. }
  25837. return this;
  25838. }
  25839. /**
  25840. * Deletes all parameters from the script.
  25841. *
  25842. * @return {ScriptableNode} A reference to this node.
  25843. */
  25844. clearParameters() {
  25845. for ( const name of Object.keys( this.parameters ) ) {
  25846. this.deleteParameter( name );
  25847. }
  25848. this.needsUpdate = true;
  25849. return this;
  25850. }
  25851. /**
  25852. * Calls a function from the script.
  25853. *
  25854. * @param {string} name - The function name.
  25855. * @param {...any} params - A list of parameters.
  25856. * @return {any} The result of the function call.
  25857. */
  25858. call( name, ...params ) {
  25859. const object = this.getObject();
  25860. const method = object[ name ];
  25861. if ( typeof method === 'function' ) {
  25862. return method( ...params );
  25863. }
  25864. }
  25865. /**
  25866. * Asynchronously calls a function from the script.
  25867. *
  25868. * @param {string} name - The function name.
  25869. * @param {...any} params - A list of parameters.
  25870. * @return {Promise<any>} The result of the function call.
  25871. */
  25872. async callAsync( name, ...params ) {
  25873. const object = this.getObject();
  25874. const method = object[ name ];
  25875. if ( typeof method === 'function' ) {
  25876. return method.constructor.name === 'AsyncFunction' ? await method( ...params ) : method( ...params );
  25877. }
  25878. }
  25879. /**
  25880. * Overwritten since the node types is inferred from the script's output.
  25881. *
  25882. * @param {NodeBuilder} builder - The current node builder
  25883. * @return {string} The node type.
  25884. */
  25885. getNodeType( builder ) {
  25886. return this.getDefaultOutputNode().getNodeType( builder );
  25887. }
  25888. /**
  25889. * Refreshes the script node.
  25890. *
  25891. * @param {?string} [output=null] - An optional output.
  25892. */
  25893. refresh( output = null ) {
  25894. if ( output !== null ) {
  25895. this.getOutput( output ).refresh();
  25896. } else {
  25897. this._refresh();
  25898. }
  25899. }
  25900. /**
  25901. * Returns an object representation of the script.
  25902. *
  25903. * @return {Object} The result object.
  25904. */
  25905. getObject() {
  25906. if ( this.needsUpdate ) this.dispose();
  25907. if ( this._object !== null ) return this._object;
  25908. //
  25909. const refresh = () => this.refresh();
  25910. const setOutput = ( id, value ) => this.setOutput( id, value );
  25911. const parameters = new Parameters( this );
  25912. const THREE = ScriptableNodeResources.get( 'THREE' );
  25913. const TSL = ScriptableNodeResources.get( 'TSL' );
  25914. const method = this.getMethod();
  25915. const params = [ parameters, this._local, ScriptableNodeResources, refresh, setOutput, THREE, TSL ];
  25916. this._object = method( ...params );
  25917. const layout = this._object.layout;
  25918. if ( layout ) {
  25919. if ( layout.cache === false ) {
  25920. this._local.clear();
  25921. }
  25922. // default output
  25923. this._output.outputType = layout.outputType || null;
  25924. if ( Array.isArray( layout.elements ) ) {
  25925. for ( const element of layout.elements ) {
  25926. const id = element.id || element.name;
  25927. if ( element.inputType ) {
  25928. if ( this.getParameter( id ) === undefined ) this.setParameter( id, null );
  25929. this.getParameter( id ).inputType = element.inputType;
  25930. }
  25931. if ( element.outputType ) {
  25932. if ( this.getOutput( id ) === undefined ) this.setOutput( id, null );
  25933. this.getOutput( id ).outputType = element.outputType;
  25934. }
  25935. }
  25936. }
  25937. }
  25938. return this._object;
  25939. }
  25940. deserialize( data ) {
  25941. super.deserialize( data );
  25942. for ( const name in this.parameters ) {
  25943. let valueNode = this.parameters[ name ];
  25944. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  25945. valueNode.events.addEventListener( 'refresh', this.onRefresh );
  25946. }
  25947. }
  25948. /**
  25949. * Returns the layout of the script.
  25950. *
  25951. * @return {Object} The script's layout.
  25952. */
  25953. getLayout() {
  25954. return this.getObject().layout;
  25955. }
  25956. /**
  25957. * Returns default node output of the script.
  25958. *
  25959. * @return {Node} The default node output.
  25960. */
  25961. getDefaultOutputNode() {
  25962. const output = this.getDefaultOutput().value;
  25963. if ( output && output.isNode ) {
  25964. return output;
  25965. }
  25966. return float();
  25967. }
  25968. /**
  25969. * Returns default output of the script.
  25970. *
  25971. * @return {ScriptableValueNode} The default output.
  25972. */
  25973. getDefaultOutput() {
  25974. return this._exec()._output;
  25975. }
  25976. /**
  25977. * Returns a function created from the node's script.
  25978. *
  25979. * @return {Function} The function representing the node's code.
  25980. */
  25981. getMethod() {
  25982. if ( this.needsUpdate ) this.dispose();
  25983. if ( this._method !== null ) return this._method;
  25984. //
  25985. const parametersProps = [ 'parameters', 'local', 'global', 'refresh', 'setOutput', 'THREE', 'TSL' ];
  25986. const interfaceProps = [ 'layout', 'init', 'main', 'dispose' ];
  25987. const properties = interfaceProps.join( ', ' );
  25988. const declarations = 'var ' + properties + '; var output = {};\n';
  25989. const returns = '\nreturn { ...output, ' + properties + ' };';
  25990. const code = declarations + this.codeNode.code + returns;
  25991. //
  25992. this._method = new Function( ...parametersProps, code );
  25993. return this._method;
  25994. }
  25995. /**
  25996. * Frees all internal resources.
  25997. */
  25998. dispose() {
  25999. if ( this._method === null ) return;
  26000. if ( this._object && typeof this._object.dispose === 'function' ) {
  26001. this._object.dispose();
  26002. }
  26003. this._method = null;
  26004. this._object = null;
  26005. this._source = null;
  26006. this._value = null;
  26007. this._needsOutputUpdate = true;
  26008. this._output.value = null;
  26009. this._outputs = {};
  26010. }
  26011. setup() {
  26012. return this.getDefaultOutputNode();
  26013. }
  26014. getCacheKey( force ) {
  26015. const values = [ hashString( this.source ), this.getDefaultOutputNode().getCacheKey( force ) ];
  26016. for ( const param in this.parameters ) {
  26017. values.push( this.parameters[ param ].getCacheKey( force ) );
  26018. }
  26019. return hashArray( values );
  26020. }
  26021. set needsUpdate( value ) {
  26022. if ( value === true ) this.dispose();
  26023. }
  26024. get needsUpdate() {
  26025. return this.source !== this._source;
  26026. }
  26027. /**
  26028. * Executes the `main` function of the script.
  26029. *
  26030. * @private
  26031. * @return {ScriptableNode} A reference to this node.
  26032. */
  26033. _exec() {
  26034. if ( this.codeNode === null ) return this;
  26035. if ( this._needsOutputUpdate === true ) {
  26036. this._value = this.call( 'main' );
  26037. this._needsOutputUpdate = false;
  26038. }
  26039. this._output.value = this._value;
  26040. return this;
  26041. }
  26042. /**
  26043. * Executes the refresh.
  26044. *
  26045. * @private
  26046. */
  26047. _refresh() {
  26048. this.needsUpdate = true;
  26049. this._exec();
  26050. this._output.refresh();
  26051. }
  26052. }
  26053. /**
  26054. * TSL function for creating a scriptable node.
  26055. *
  26056. * @tsl
  26057. * @function
  26058. * @param {CodeNode} [codeNode] - The code node.
  26059. * @param {?Object} [parameters={}] - The parameters definition.
  26060. * @returns {ScriptableNode}
  26061. */
  26062. const scriptable = /*@__PURE__*/ nodeProxy( ScriptableNode ).setParameterLength( 1, 2 );
  26063. /**
  26064. * Returns a node that represents the `z` coordinate in view space
  26065. * for the current fragment. It's a different representation of the
  26066. * default depth value.
  26067. *
  26068. * This value can be part of a computation that defines how the fog
  26069. * density increases when moving away from the camera.
  26070. *
  26071. * @param {NodeBuilder} builder - The current node builder.
  26072. * @return {Node} The viewZ node.
  26073. */
  26074. function getViewZNode( builder ) {
  26075. let viewZ;
  26076. const getViewZ = builder.context.getViewZ;
  26077. if ( getViewZ !== undefined ) {
  26078. viewZ = getViewZ( this );
  26079. }
  26080. return ( viewZ || positionView.z ).negate();
  26081. }
  26082. /**
  26083. * Constructs a new range factor node.
  26084. *
  26085. * @tsl
  26086. * @function
  26087. * @param {Node} near - Defines the near value.
  26088. * @param {Node} far - Defines the far value.
  26089. */
  26090. const rangeFogFactor = Fn( ( [ near, far ], builder ) => {
  26091. const viewZ = getViewZNode( builder );
  26092. return smoothstep( near, far, viewZ );
  26093. } );
  26094. /**
  26095. * Represents an exponential squared fog. This type of fog gives
  26096. * a clear view near the camera and a faster than exponentially
  26097. * densening fog farther from the camera.
  26098. *
  26099. * @tsl
  26100. * @function
  26101. * @param {Node} density - Defines the fog density.
  26102. */
  26103. const densityFogFactor = Fn( ( [ density ], builder ) => {
  26104. const viewZ = getViewZNode( builder );
  26105. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  26106. } );
  26107. /**
  26108. * This class can be used to configure a fog for the scene.
  26109. * Nodes of this type are assigned to `Scene.fogNode`.
  26110. *
  26111. * @tsl
  26112. * @function
  26113. * @param {Node} color - Defines the color of the fog.
  26114. * @param {Node} factor - Defines how the fog is factored in the scene.
  26115. */
  26116. const fog = Fn( ( [ color, factor ] ) => {
  26117. return vec4( factor.toFloat().mix( output.rgb, color.toVec3() ), output.a );
  26118. } );
  26119. // Deprecated
  26120. /**
  26121. * @tsl
  26122. * @function
  26123. * @deprecated since r171. Use `fog( color, rangeFogFactor( near, far ) )` instead.
  26124. *
  26125. * @param {Node} color
  26126. * @param {Node} near
  26127. * @param {Node} far
  26128. * @returns {Function}
  26129. */
  26130. function rangeFog( color, near, far ) { // @deprecated, r171
  26131. console.warn( 'THREE.TSL: "rangeFog( color, near, far )" is deprecated. Use "fog( color, rangeFogFactor( near, far ) )" instead.' );
  26132. return fog( color, rangeFogFactor( near, far ) );
  26133. }
  26134. /**
  26135. * @tsl
  26136. * @function
  26137. * @deprecated since r171. Use `fog( color, densityFogFactor( density ) )` instead.
  26138. *
  26139. * @param {Node} color
  26140. * @param {Node} density
  26141. * @returns {Function}
  26142. */
  26143. function densityFog( color, density ) { // @deprecated, r171
  26144. console.warn( 'THREE.TSL: "densityFog( color, density )" is deprecated. Use "fog( color, densityFogFactor( density ) )" instead.' );
  26145. return fog( color, densityFogFactor( density ) );
  26146. }
  26147. let min = null;
  26148. let max = null;
  26149. /**
  26150. * `RangeNode` generates random instanced attribute data in a defined range.
  26151. * An exemplary use case for this utility node is to generate random per-instance
  26152. * colors:
  26153. * ```js
  26154. * const material = new MeshBasicNodeMaterial();
  26155. * material.colorNode = range( new Color( 0x000000 ), new Color( 0xFFFFFF ) );
  26156. * const mesh = new InstancedMesh( geometry, material, count );
  26157. * ```
  26158. * @augments Node
  26159. */
  26160. class RangeNode extends Node {
  26161. static get type() {
  26162. return 'RangeNode';
  26163. }
  26164. /**
  26165. * Constructs a new range node.
  26166. *
  26167. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  26168. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  26169. */
  26170. constructor( minNode = float(), maxNode = float() ) {
  26171. super();
  26172. /**
  26173. * A node defining the lower bound of the range.
  26174. *
  26175. * @type {Node<any>}
  26176. * @default float()
  26177. */
  26178. this.minNode = minNode;
  26179. /**
  26180. * A node defining the upper bound of the range.
  26181. *
  26182. * @type {Node<any>}
  26183. * @default float()
  26184. */
  26185. this.maxNode = maxNode;
  26186. }
  26187. /**
  26188. * Returns the vector length which is computed based on the range definition.
  26189. *
  26190. * @param {NodeBuilder} builder - The current node builder.
  26191. * @return {number} The vector length.
  26192. */
  26193. getVectorLength( builder ) {
  26194. const minLength = builder.getTypeLength( getValueType( this.minNode.value ) );
  26195. const maxLength = builder.getTypeLength( getValueType( this.maxNode.value ) );
  26196. return minLength > maxLength ? minLength : maxLength;
  26197. }
  26198. /**
  26199. * This method is overwritten since the node type is inferred from range definition.
  26200. *
  26201. * @param {NodeBuilder} builder - The current node builder.
  26202. * @return {string} The node type.
  26203. */
  26204. getNodeType( builder ) {
  26205. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  26206. }
  26207. setup( builder ) {
  26208. const object = builder.object;
  26209. let output = null;
  26210. if ( object.count > 1 ) {
  26211. const minValue = this.minNode.value;
  26212. const maxValue = this.maxNode.value;
  26213. const minLength = builder.getTypeLength( getValueType( minValue ) );
  26214. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  26215. min = min || new Vector4();
  26216. max = max || new Vector4();
  26217. min.setScalar( 0 );
  26218. max.setScalar( 0 );
  26219. if ( minLength === 1 ) min.setScalar( minValue );
  26220. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b, 1 );
  26221. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  26222. if ( maxLength === 1 ) max.setScalar( maxValue );
  26223. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b, 1 );
  26224. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  26225. const stride = 4;
  26226. const length = stride * object.count;
  26227. const array = new Float32Array( length );
  26228. for ( let i = 0; i < length; i ++ ) {
  26229. const index = i % stride;
  26230. const minElementValue = min.getComponent( index );
  26231. const maxElementValue = max.getComponent( index );
  26232. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  26233. }
  26234. const nodeType = this.getNodeType( builder );
  26235. if ( object.count <= 4096 ) {
  26236. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  26237. } else {
  26238. // TODO: Improve anonymous buffer attribute creation removing this part
  26239. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  26240. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  26241. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  26242. }
  26243. } else {
  26244. output = float( 0 );
  26245. }
  26246. return output;
  26247. }
  26248. }
  26249. /**
  26250. * TSL function for creating a range node.
  26251. *
  26252. * @tsl
  26253. * @function
  26254. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  26255. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  26256. * @returns {RangeNode}
  26257. */
  26258. const range = /*@__PURE__*/ nodeProxy( RangeNode ).setParameterLength( 2 );
  26259. /**
  26260. * `ComputeBuiltinNode` represents a compute-scope builtin value that expose information
  26261. * about the currently running dispatch and/or the device it is running on.
  26262. *
  26263. * This node can only be used with a WebGPU backend.
  26264. *
  26265. * @augments Node
  26266. */
  26267. class ComputeBuiltinNode extends Node {
  26268. static get type() {
  26269. return 'ComputeBuiltinNode';
  26270. }
  26271. /**
  26272. * Constructs a new compute builtin node.
  26273. *
  26274. * @param {string} builtinName - The built-in name.
  26275. * @param {string} nodeType - The node type.
  26276. */
  26277. constructor( builtinName, nodeType ) {
  26278. super( nodeType );
  26279. /**
  26280. * The built-in name.
  26281. *
  26282. * @private
  26283. * @type {string}
  26284. */
  26285. this._builtinName = builtinName;
  26286. }
  26287. /**
  26288. * This method is overwritten since hash is derived from the built-in name.
  26289. *
  26290. * @param {NodeBuilder} builder - The current node builder.
  26291. * @return {string} The hash.
  26292. */
  26293. getHash( builder ) {
  26294. return this.getBuiltinName( builder );
  26295. }
  26296. /**
  26297. * This method is overwritten since the node type is simply derived from `nodeType`..
  26298. *
  26299. * @param {NodeBuilder} builder - The current node builder.
  26300. * @return {string} The node type.
  26301. */
  26302. getNodeType( /*builder*/ ) {
  26303. return this.nodeType;
  26304. }
  26305. /**
  26306. * Sets the builtin name.
  26307. *
  26308. * @param {string} builtinName - The built-in name.
  26309. * @return {ComputeBuiltinNode} A reference to this node.
  26310. */
  26311. setBuiltinName( builtinName ) {
  26312. this._builtinName = builtinName;
  26313. return this;
  26314. }
  26315. /**
  26316. * Returns the builtin name.
  26317. *
  26318. * @param {NodeBuilder} builder - The current node builder.
  26319. * @return {string} The builtin name.
  26320. */
  26321. getBuiltinName( /*builder*/ ) {
  26322. return this._builtinName;
  26323. }
  26324. /**
  26325. * Whether the current node builder has the builtin or not.
  26326. *
  26327. * @param {NodeBuilder} builder - The current node builder.
  26328. * @return {boolean} Whether the builder has the builtin or not.
  26329. */
  26330. hasBuiltin( builder ) {
  26331. return builder.hasBuiltin( this._builtinName );
  26332. }
  26333. generate( builder, output ) {
  26334. const builtinName = this.getBuiltinName( builder );
  26335. const nodeType = this.getNodeType( builder );
  26336. if ( builder.shaderStage === 'compute' ) {
  26337. return builder.format( builtinName, nodeType, output );
  26338. } else {
  26339. console.warn( `ComputeBuiltinNode: Compute built-in value ${builtinName} can not be accessed in the ${builder.shaderStage} stage` );
  26340. return builder.generateConst( nodeType );
  26341. }
  26342. }
  26343. serialize( data ) {
  26344. super.serialize( data );
  26345. data.global = this.global;
  26346. data._builtinName = this._builtinName;
  26347. }
  26348. deserialize( data ) {
  26349. super.deserialize( data );
  26350. this.global = data.global;
  26351. this._builtinName = data._builtinName;
  26352. }
  26353. }
  26354. /**
  26355. * TSL function for creating a compute builtin node.
  26356. *
  26357. * @tsl
  26358. * @function
  26359. * @param {string} name - The built-in name.
  26360. * @param {string} nodeType - The node type.
  26361. * @returns {ComputeBuiltinNode}
  26362. */
  26363. const computeBuiltin = ( name, nodeType ) => nodeObject( new ComputeBuiltinNode( name, nodeType ) );
  26364. /**
  26365. * Represents the number of workgroups dispatched by the compute shader.
  26366. * ```js
  26367. * // Run 512 invocations/threads with a workgroup size of 128.
  26368. * const computeFn = Fn(() => {
  26369. *
  26370. * // numWorkgroups.x = 4
  26371. * storageBuffer.element(0).assign(numWorkgroups.x)
  26372. *
  26373. * })().compute(512, [128]);
  26374. *
  26375. * // Run 512 invocations/threads with the default workgroup size of 64.
  26376. * const computeFn = Fn(() => {
  26377. *
  26378. * // numWorkgroups.x = 8
  26379. * storageBuffer.element(0).assign(numWorkgroups.x)
  26380. *
  26381. * })().compute(512);
  26382. * ```
  26383. *
  26384. * @tsl
  26385. * @type {ComputeBuiltinNode<uvec3>}
  26386. */
  26387. const numWorkgroups = /*@__PURE__*/ computeBuiltin( 'numWorkgroups', 'uvec3' );
  26388. /**
  26389. * Represents the 3-dimensional index of the workgroup the current compute invocation belongs to.
  26390. * ```js
  26391. * // Execute 12 compute threads with a workgroup size of 3.
  26392. * const computeFn = Fn( () => {
  26393. *
  26394. * If( workgroupId.x.mod( 2 ).equal( 0 ), () => {
  26395. *
  26396. * storageBuffer.element( instanceIndex ).assign( instanceIndex );
  26397. *
  26398. * } ).Else( () => {
  26399. *
  26400. * storageBuffer.element( instanceIndex ).assign( 0 );
  26401. *
  26402. * } );
  26403. *
  26404. * } )().compute( 12, [ 3 ] );
  26405. *
  26406. * // workgroupId.x = [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3];
  26407. * // Buffer Output = [0, 1, 2, 0, 0, 0, 6, 7, 8, 0, 0, 0];
  26408. * ```
  26409. *
  26410. * @tsl
  26411. * @type {ComputeBuiltinNode<uvec3>}
  26412. */
  26413. const workgroupId = /*@__PURE__*/ computeBuiltin( 'workgroupId', 'uvec3' );
  26414. /**
  26415. * A non-linearized 3-dimensional representation of the current invocation's position within a 3D global grid.
  26416. *
  26417. * @tsl
  26418. * @type {ComputeBuiltinNode<uvec3>}
  26419. */
  26420. const globalId = /*@__PURE__*/ computeBuiltin( 'globalId', 'uvec3' );
  26421. /**
  26422. * A non-linearized 3-dimensional representation of the current invocation's position within a 3D workgroup grid.
  26423. *
  26424. * @tsl
  26425. * @type {ComputeBuiltinNode<uvec3>}
  26426. */
  26427. const localId = /*@__PURE__*/ computeBuiltin( 'localId', 'uvec3' );
  26428. /**
  26429. * A device dependent variable that exposes the size of the current invocation's subgroup.
  26430. *
  26431. * @tsl
  26432. * @type {ComputeBuiltinNode<uint>}
  26433. */
  26434. const subgroupSize = /*@__PURE__*/ computeBuiltin( 'subgroupSize', 'uint' );
  26435. /**
  26436. * Represents a GPU control barrier that synchronizes compute operations within a given scope.
  26437. *
  26438. * This node can only be used with a WebGPU backend.
  26439. *
  26440. * @augments Node
  26441. */
  26442. class BarrierNode extends Node {
  26443. /**
  26444. * Constructs a new barrier node.
  26445. *
  26446. * @param {string} scope - The scope defines the behavior of the node.
  26447. */
  26448. constructor( scope ) {
  26449. super();
  26450. this.scope = scope;
  26451. }
  26452. generate( builder ) {
  26453. const { scope } = this;
  26454. const { renderer } = builder;
  26455. if ( renderer.backend.isWebGLBackend === true ) {
  26456. builder.addFlowCode( `\t// ${scope}Barrier \n` );
  26457. } else {
  26458. builder.addLineFlowCode( `${scope}Barrier()`, this );
  26459. }
  26460. }
  26461. }
  26462. /**
  26463. * TSL function for creating a barrier node.
  26464. *
  26465. * @tsl
  26466. * @function
  26467. * @param {string} scope - The scope defines the behavior of the node..
  26468. * @returns {BarrierNode}
  26469. */
  26470. const barrier = nodeProxy( BarrierNode );
  26471. /**
  26472. * TSL function for creating a workgroup barrier. All compute shader
  26473. * invocations must wait for each invocation within a workgroup to
  26474. * complete before the barrier can be surpassed.
  26475. *
  26476. * @tsl
  26477. * @function
  26478. * @returns {BarrierNode}
  26479. */
  26480. const workgroupBarrier = () => barrier( 'workgroup' ).toStack();
  26481. /**
  26482. * TSL function for creating a storage barrier. All invocations must
  26483. * wait for each access to variables within the 'storage' address space
  26484. * to complete before the barrier can be passed.
  26485. *
  26486. * @tsl
  26487. * @function
  26488. * @returns {BarrierNode}
  26489. */
  26490. const storageBarrier = () => barrier( 'storage' ).toStack();
  26491. /**
  26492. * TSL function for creating a texture barrier. All invocations must
  26493. * wait for each access to variables within the 'texture' address space
  26494. * to complete before the barrier can be passed.
  26495. *
  26496. * @tsl
  26497. * @function
  26498. * @returns {BarrierNode}
  26499. */
  26500. const textureBarrier = () => barrier( 'texture' ).toStack();
  26501. /**
  26502. * Represents an element of a 'workgroup' scoped buffer.
  26503. *
  26504. * @augments ArrayElementNode
  26505. */
  26506. class WorkgroupInfoElementNode extends ArrayElementNode {
  26507. /**
  26508. * Constructs a new workgroup info element node.
  26509. *
  26510. * @param {Node} workgroupInfoNode - The workgroup info node.
  26511. * @param {Node} indexNode - The index node that defines the element access.
  26512. */
  26513. constructor( workgroupInfoNode, indexNode ) {
  26514. super( workgroupInfoNode, indexNode );
  26515. /**
  26516. * This flag can be used for type testing.
  26517. *
  26518. * @type {boolean}
  26519. * @readonly
  26520. * @default true
  26521. */
  26522. this.isWorkgroupInfoElementNode = true;
  26523. }
  26524. generate( builder, output ) {
  26525. let snippet;
  26526. const isAssignContext = builder.context.assign;
  26527. snippet = super.generate( builder );
  26528. if ( isAssignContext !== true ) {
  26529. const type = this.getNodeType( builder );
  26530. snippet = builder.format( snippet, type, output );
  26531. }
  26532. // TODO: Possibly activate clip distance index on index access rather than from clipping context
  26533. return snippet;
  26534. }
  26535. }
  26536. /**
  26537. * A node allowing the user to create a 'workgroup' scoped buffer within the
  26538. * context of a compute shader. Typically, workgroup scoped buffers are
  26539. * created to hold data that is transferred from a global storage scope into
  26540. * a local workgroup scope. For invocations within a workgroup, data
  26541. * access speeds on 'workgroup' scoped buffers can be significantly faster
  26542. * than similar access operations on globally accessible storage buffers.
  26543. *
  26544. * This node can only be used with a WebGPU backend.
  26545. *
  26546. * @augments Node
  26547. */
  26548. class WorkgroupInfoNode extends Node {
  26549. /**
  26550. * Constructs a new buffer scoped to type scope.
  26551. *
  26552. * @param {string} scope - TODO.
  26553. * @param {string} bufferType - The data type of a 'workgroup' scoped buffer element.
  26554. * @param {number} [bufferCount=0] - The number of elements in the buffer.
  26555. */
  26556. constructor( scope, bufferType, bufferCount = 0 ) {
  26557. super( bufferType );
  26558. /**
  26559. * The buffer type.
  26560. *
  26561. * @type {string}
  26562. */
  26563. this.bufferType = bufferType;
  26564. /**
  26565. * The buffer count.
  26566. *
  26567. * @type {number}
  26568. * @default 0
  26569. */
  26570. this.bufferCount = bufferCount;
  26571. /**
  26572. * This flag can be used for type testing.
  26573. *
  26574. * @type {boolean}
  26575. * @readonly
  26576. * @default true
  26577. */
  26578. this.isWorkgroupInfoNode = true;
  26579. /**
  26580. * The data type of the array buffer.
  26581. *
  26582. * @type {string}
  26583. */
  26584. this.elementType = bufferType;
  26585. /**
  26586. * TODO.
  26587. *
  26588. * @type {string}
  26589. */
  26590. this.scope = scope;
  26591. }
  26592. /**
  26593. * Sets the name/label of this node.
  26594. *
  26595. * @param {string} name - The name to set.
  26596. * @return {WorkgroupInfoNode} A reference to this node.
  26597. */
  26598. label( name ) {
  26599. this.name = name;
  26600. return this;
  26601. }
  26602. /**
  26603. * Sets the scope of this node.
  26604. *
  26605. * @param {string} scope - The scope to set.
  26606. * @return {WorkgroupInfoNode} A reference to this node.
  26607. */
  26608. setScope( scope ) {
  26609. this.scope = scope;
  26610. return this;
  26611. }
  26612. /**
  26613. * The data type of the array buffer.
  26614. *
  26615. * @return {string} The element type.
  26616. */
  26617. getElementType() {
  26618. return this.elementType;
  26619. }
  26620. /**
  26621. * Overwrites the default implementation since the input type
  26622. * is inferred from the scope.
  26623. *
  26624. * @param {NodeBuilder} builder - The current node builder.
  26625. * @return {string} The input type.
  26626. */
  26627. getInputType( /*builder*/ ) {
  26628. return `${this.scope}Array`;
  26629. }
  26630. /**
  26631. * This method can be used to access elements via an index node.
  26632. *
  26633. * @param {IndexNode} indexNode - indexNode.
  26634. * @return {WorkgroupInfoElementNode} A reference to an element.
  26635. */
  26636. element( indexNode ) {
  26637. return nodeObject( new WorkgroupInfoElementNode( this, indexNode ) );
  26638. }
  26639. generate( builder ) {
  26640. return builder.getScopedArray( this.name || `${this.scope}Array_${this.id}`, this.scope.toLowerCase(), this.bufferType, this.bufferCount );
  26641. }
  26642. }
  26643. /**
  26644. * TSL function for creating a workgroup info node.
  26645. * Creates a new 'workgroup' scoped array buffer.
  26646. *
  26647. * @tsl
  26648. * @function
  26649. * @param {string} type - The data type of a 'workgroup' scoped buffer element.
  26650. * @param {number} [count=0] - The number of elements in the buffer.
  26651. * @returns {WorkgroupInfoNode}
  26652. */
  26653. const workgroupArray = ( type, count ) => nodeObject( new WorkgroupInfoNode( 'Workgroup', type, count ) );
  26654. /**
  26655. * `AtomicFunctionNode` represents any function that can operate on atomic variable types
  26656. * within a shader. In an atomic function, any modification to an atomic variable will
  26657. * occur as an indivisible step with a defined order relative to other modifications.
  26658. * Accordingly, even if multiple atomic functions are modifying an atomic variable at once
  26659. * atomic operations will not interfere with each other.
  26660. *
  26661. * This node can only be used with a WebGPU backend.
  26662. *
  26663. * @augments Node
  26664. */
  26665. class AtomicFunctionNode extends Node {
  26666. static get type() {
  26667. return 'AtomicFunctionNode';
  26668. }
  26669. /**
  26670. * Constructs a new atomic function node.
  26671. *
  26672. * @param {string} method - The signature of the atomic function to construct.
  26673. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  26674. * @param {Node} valueNode - The value that mutates the atomic variable.
  26675. */
  26676. constructor( method, pointerNode, valueNode ) {
  26677. super( 'uint' );
  26678. /**
  26679. * The signature of the atomic function to construct.
  26680. *
  26681. * @type {string}
  26682. */
  26683. this.method = method;
  26684. /**
  26685. * An atomic variable or element of an atomic buffer.
  26686. *
  26687. * @type {Node}
  26688. */
  26689. this.pointerNode = pointerNode;
  26690. /**
  26691. * A value that modifies the atomic variable.
  26692. *
  26693. * @type {Node}
  26694. */
  26695. this.valueNode = valueNode;
  26696. /**
  26697. * Creates a list of the parents for this node for detecting if the node needs to return a value.
  26698. *
  26699. * @type {boolean}
  26700. * @default true
  26701. */
  26702. this.parents = true;
  26703. }
  26704. /**
  26705. * Overwrites the default implementation to return the type of
  26706. * the pointer node.
  26707. *
  26708. * @param {NodeBuilder} builder - The current node builder.
  26709. * @return {string} The input type.
  26710. */
  26711. getInputType( builder ) {
  26712. return this.pointerNode.getNodeType( builder );
  26713. }
  26714. /**
  26715. * Overwritten since the node type is inferred from the input type.
  26716. *
  26717. * @param {NodeBuilder} builder - The current node builder.
  26718. * @return {string} The node type.
  26719. */
  26720. getNodeType( builder ) {
  26721. return this.getInputType( builder );
  26722. }
  26723. generate( builder ) {
  26724. const properties = builder.getNodeProperties( this );
  26725. const parents = properties.parents;
  26726. const method = this.method;
  26727. const type = this.getNodeType( builder );
  26728. const inputType = this.getInputType( builder );
  26729. const a = this.pointerNode;
  26730. const b = this.valueNode;
  26731. const params = [];
  26732. params.push( `&${ a.build( builder, inputType ) }` );
  26733. if ( b !== null ) {
  26734. params.push( b.build( builder, inputType ) );
  26735. }
  26736. const methodSnippet = `${ builder.getMethod( method, type ) }( ${ params.join( ', ' ) } )`;
  26737. const isVoid = parents.length === 1 && parents[ 0 ].isStackNode === true;
  26738. if ( isVoid ) {
  26739. builder.addLineFlowCode( methodSnippet, this );
  26740. } else {
  26741. if ( properties.constNode === undefined ) {
  26742. properties.constNode = expression( methodSnippet, type ).toConst();
  26743. }
  26744. return properties.constNode.build( builder );
  26745. }
  26746. }
  26747. }
  26748. AtomicFunctionNode.ATOMIC_LOAD = 'atomicLoad';
  26749. AtomicFunctionNode.ATOMIC_STORE = 'atomicStore';
  26750. AtomicFunctionNode.ATOMIC_ADD = 'atomicAdd';
  26751. AtomicFunctionNode.ATOMIC_SUB = 'atomicSub';
  26752. AtomicFunctionNode.ATOMIC_MAX = 'atomicMax';
  26753. AtomicFunctionNode.ATOMIC_MIN = 'atomicMin';
  26754. AtomicFunctionNode.ATOMIC_AND = 'atomicAnd';
  26755. AtomicFunctionNode.ATOMIC_OR = 'atomicOr';
  26756. AtomicFunctionNode.ATOMIC_XOR = 'atomicXor';
  26757. /**
  26758. * TSL function for creating an atomic function node.
  26759. *
  26760. * @tsl
  26761. * @function
  26762. * @param {string} method - The signature of the atomic function to construct.
  26763. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  26764. * @param {Node} valueNode - The value that mutates the atomic variable.
  26765. * @returns {AtomicFunctionNode}
  26766. */
  26767. const atomicNode = nodeProxy( AtomicFunctionNode );
  26768. /**
  26769. * TSL function for appending an atomic function call into the programmatic flow of a compute shader.
  26770. *
  26771. * @tsl
  26772. * @function
  26773. * @param {string} method - The signature of the atomic function to construct.
  26774. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  26775. * @param {Node} valueNode - The value that mutates the atomic variable.
  26776. * @returns {AtomicFunctionNode}
  26777. */
  26778. const atomicFunc = ( method, pointerNode, valueNode ) => {
  26779. return atomicNode( method, pointerNode, valueNode ).toStack();
  26780. };
  26781. /**
  26782. * Loads the value stored in the atomic variable.
  26783. *
  26784. * @tsl
  26785. * @function
  26786. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  26787. * @returns {AtomicFunctionNode}
  26788. */
  26789. const atomicLoad = ( pointerNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_LOAD, pointerNode, null );
  26790. /**
  26791. * Stores a value in the atomic variable.
  26792. *
  26793. * @tsl
  26794. * @function
  26795. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  26796. * @param {Node} valueNode - The value that mutates the atomic variable.
  26797. * @returns {AtomicFunctionNode}
  26798. */
  26799. const atomicStore = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_STORE, pointerNode, valueNode );
  26800. /**
  26801. * Increments the value stored in the atomic variable.
  26802. *
  26803. * @tsl
  26804. * @function
  26805. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  26806. * @param {Node} valueNode - The value that mutates the atomic variable.
  26807. * @returns {AtomicFunctionNode}
  26808. */
  26809. const atomicAdd = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_ADD, pointerNode, valueNode );
  26810. /**
  26811. * Decrements the value stored in the atomic variable.
  26812. *
  26813. * @tsl
  26814. * @function
  26815. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  26816. * @param {Node} valueNode - The value that mutates the atomic variable.
  26817. * @returns {AtomicFunctionNode}
  26818. */
  26819. const atomicSub = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_SUB, pointerNode, valueNode );
  26820. /**
  26821. * Stores in an atomic variable the maximum between its current value and a parameter.
  26822. *
  26823. * @tsl
  26824. * @function
  26825. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  26826. * @param {Node} valueNode - The value that mutates the atomic variable.
  26827. * @returns {AtomicFunctionNode}
  26828. */
  26829. const atomicMax = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_MAX, pointerNode, valueNode );
  26830. /**
  26831. * Stores in an atomic variable the minimum between its current value and a parameter.
  26832. *
  26833. * @tsl
  26834. * @function
  26835. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  26836. * @param {Node} valueNode - The value that mutates the atomic variable.
  26837. * @returns {AtomicFunctionNode}
  26838. */
  26839. const atomicMin = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_MIN, pointerNode, valueNode );
  26840. /**
  26841. * Stores in an atomic variable the bitwise AND of its value with a parameter.
  26842. *
  26843. * @tsl
  26844. * @function
  26845. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  26846. * @param {Node} valueNode - The value that mutates the atomic variable.
  26847. * @returns {AtomicFunctionNode}
  26848. */
  26849. const atomicAnd = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_AND, pointerNode, valueNode );
  26850. /**
  26851. * Stores in an atomic variable the bitwise OR of its value with a parameter.
  26852. *
  26853. * @tsl
  26854. * @function
  26855. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  26856. * @param {Node} valueNode - The value that mutates the atomic variable.
  26857. * @returns {AtomicFunctionNode}
  26858. */
  26859. const atomicOr = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_OR, pointerNode, valueNode );
  26860. /**
  26861. * Stores in an atomic variable the bitwise XOR of its value with a parameter.
  26862. *
  26863. * @tsl
  26864. * @function
  26865. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  26866. * @param {Node} valueNode - The value that mutates the atomic variable.
  26867. * @returns {AtomicFunctionNode}
  26868. */
  26869. const atomicXor = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_XOR, pointerNode, valueNode );
  26870. let uniformsLib;
  26871. function getLightData( light ) {
  26872. uniformsLib = uniformsLib || new WeakMap();
  26873. let uniforms = uniformsLib.get( light );
  26874. if ( uniforms === undefined ) uniformsLib.set( light, uniforms = {} );
  26875. return uniforms;
  26876. }
  26877. /**
  26878. * TSL function for getting a shadow matrix uniform node for the given light.
  26879. *
  26880. * @tsl
  26881. * @function
  26882. * @param {Light} light -The light source.
  26883. * @returns {UniformNode<mat4>} The shadow matrix uniform node.
  26884. */
  26885. function lightShadowMatrix( light ) {
  26886. const data = getLightData( light );
  26887. return data.shadowMatrix || ( data.shadowMatrix = uniform( 'mat4' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => {
  26888. if ( light.castShadow !== true || frame.renderer.shadowMap.enabled === false ) {
  26889. light.shadow.updateMatrices( light );
  26890. }
  26891. return light.shadow.matrix;
  26892. } ) );
  26893. }
  26894. /**
  26895. * TSL function for getting projected uv coordinates for the given light.
  26896. * Relevant when using maps with spot lights.
  26897. *
  26898. * @tsl
  26899. * @function
  26900. * @param {Light} light -The light source.
  26901. * @param {Node<vec3>} [position=positionWorld] -The position to project.
  26902. * @returns {Node<vec3>} The projected uvs.
  26903. */
  26904. function lightProjectionUV( light, position = positionWorld ) {
  26905. const spotLightCoord = lightShadowMatrix( light ).mul( position );
  26906. const projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  26907. return projectionUV;
  26908. }
  26909. /**
  26910. * TSL function for getting the position in world space for the given light.
  26911. *
  26912. * @tsl
  26913. * @function
  26914. * @param {Light} light -The light source.
  26915. * @returns {UniformNode<vec3>} The light's position in world space.
  26916. */
  26917. function lightPosition( light ) {
  26918. const data = getLightData( light );
  26919. return data.position || ( data.position = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.matrixWorld ) ) );
  26920. }
  26921. /**
  26922. * TSL function for getting the light target position in world space for the given light.
  26923. *
  26924. * @tsl
  26925. * @function
  26926. * @param {Light} light -The light source.
  26927. * @returns {UniformNode<vec3>} The light target position in world space.
  26928. */
  26929. function lightTargetPosition( light ) {
  26930. const data = getLightData( light );
  26931. return data.targetPosition || ( data.targetPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.target.matrixWorld ) ) );
  26932. }
  26933. /**
  26934. * TSL function for getting the position in view space for the given light.
  26935. *
  26936. * @tsl
  26937. * @function
  26938. * @param {Light} light - The light source.
  26939. * @returns {UniformNode<vec3>} The light's position in view space.
  26940. */
  26941. function lightViewPosition( light ) {
  26942. const data = getLightData( light );
  26943. return data.viewPosition || ( data.viewPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => {
  26944. self.value = self.value || new Vector3();
  26945. self.value.setFromMatrixPosition( light.matrixWorld );
  26946. self.value.applyMatrix4( camera.matrixWorldInverse );
  26947. } ) );
  26948. }
  26949. /**
  26950. * TSL function for getting the light target direction for the given light.
  26951. *
  26952. * @tsl
  26953. * @function
  26954. * @param {Light} light -The light source.
  26955. * @returns {Node<vec3>} The light's target direction.
  26956. */
  26957. const lightTargetDirection = ( light ) => cameraViewMatrix.transformDirection( lightPosition( light ).sub( lightTargetPosition( light ) ) );
  26958. const sortLights = ( lights ) => {
  26959. return lights.sort( ( a, b ) => a.id - b.id );
  26960. };
  26961. const getLightNodeById = ( id, lightNodes ) => {
  26962. for ( const lightNode of lightNodes ) {
  26963. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  26964. return lightNode;
  26965. }
  26966. }
  26967. return null;
  26968. };
  26969. const _lightsNodeRef = /*@__PURE__*/ new WeakMap();
  26970. const _hashData = [];
  26971. /**
  26972. * This node represents the scene's lighting and manages the lighting model's life cycle
  26973. * for the current build 3D object. It is responsible for computing the total outgoing
  26974. * light in a given lighting context.
  26975. *
  26976. * @augments Node
  26977. */
  26978. class LightsNode extends Node {
  26979. static get type() {
  26980. return 'LightsNode';
  26981. }
  26982. /**
  26983. * Constructs a new lights node.
  26984. */
  26985. constructor() {
  26986. super( 'vec3' );
  26987. /**
  26988. * A node representing the total diffuse light.
  26989. *
  26990. * @type {Node<vec3>}
  26991. */
  26992. this.totalDiffuseNode = vec3().toVar();
  26993. /**
  26994. * A node representing the total specular light.
  26995. *
  26996. * @type {Node<vec3>}
  26997. */
  26998. this.totalSpecularNode = vec3().toVar();
  26999. /**
  27000. * A node representing the outgoing light.
  27001. *
  27002. * @type {Node<vec3>}
  27003. */
  27004. this.outgoingLightNode = vec3().toVar();
  27005. /**
  27006. * An array representing the lights in the scene.
  27007. *
  27008. * @private
  27009. * @type {Array<Light>}
  27010. */
  27011. this._lights = [];
  27012. /**
  27013. * For each light in the scene, this node will create a
  27014. * corresponding light node.
  27015. *
  27016. * @private
  27017. * @type {?Array<LightingNode>}
  27018. * @default null
  27019. */
  27020. this._lightNodes = null;
  27021. /**
  27022. * A hash for identifying the current light nodes setup.
  27023. *
  27024. * @private
  27025. * @type {?string}
  27026. * @default null
  27027. */
  27028. this._lightNodesHash = null;
  27029. /**
  27030. * `LightsNode` sets this property to `true` by default.
  27031. *
  27032. * @type {boolean}
  27033. * @default true
  27034. */
  27035. this.global = true;
  27036. }
  27037. /**
  27038. * Overwrites the default {@link Node#customCacheKey} implementation by including
  27039. * light data into the cache key.
  27040. *
  27041. * @return {number} The custom cache key.
  27042. */
  27043. customCacheKey() {
  27044. const lights = this._lights;
  27045. for ( let i = 0; i < lights.length; i ++ ) {
  27046. const light = lights[ i ];
  27047. _hashData.push( light.id );
  27048. _hashData.push( light.castShadow ? 1 : 0 );
  27049. if ( light.isSpotLight === true ) {
  27050. const hashMap = ( light.map !== null ) ? light.map.id : -1;
  27051. const hashColorNode = ( light.colorNode ) ? light.colorNode.getCacheKey() : -1;
  27052. _hashData.push( hashMap, hashColorNode );
  27053. }
  27054. }
  27055. const cacheKey = hashArray( _hashData );
  27056. _hashData.length = 0;
  27057. return cacheKey;
  27058. }
  27059. /**
  27060. * Computes a hash value for identifying the current light nodes setup.
  27061. *
  27062. * @param {NodeBuilder} builder - A reference to the current node builder.
  27063. * @return {string} The computed hash.
  27064. */
  27065. getHash( builder ) {
  27066. if ( this._lightNodesHash === null ) {
  27067. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  27068. const hash = [];
  27069. for ( const lightNode of this._lightNodes ) {
  27070. hash.push( lightNode.getSelf().getHash() );
  27071. }
  27072. this._lightNodesHash = 'lights-' + hash.join( ',' );
  27073. }
  27074. return this._lightNodesHash;
  27075. }
  27076. analyze( builder ) {
  27077. const properties = builder.getNodeProperties( this );
  27078. for ( const node of properties.nodes ) {
  27079. node.build( builder );
  27080. }
  27081. properties.outputNode.build( builder );
  27082. }
  27083. /**
  27084. * Creates lighting nodes for each scene light. This makes it possible to further
  27085. * process lights in the node system.
  27086. *
  27087. * @param {NodeBuilder} builder - A reference to the current node builder.
  27088. */
  27089. setupLightsNode( builder ) {
  27090. const lightNodes = [];
  27091. const previousLightNodes = this._lightNodes;
  27092. const lights = sortLights( this._lights );
  27093. const nodeLibrary = builder.renderer.library;
  27094. for ( const light of lights ) {
  27095. if ( light.isNode ) {
  27096. lightNodes.push( nodeObject( light ) );
  27097. } else {
  27098. let lightNode = null;
  27099. if ( previousLightNodes !== null ) {
  27100. lightNode = getLightNodeById( light.id, previousLightNodes ); // reuse existing light node
  27101. }
  27102. if ( lightNode === null ) {
  27103. // find the corresponding node type for a given light
  27104. const lightNodeClass = nodeLibrary.getLightNodeClass( light.constructor );
  27105. if ( lightNodeClass === null ) {
  27106. console.warn( `LightsNode.setupNodeLights: Light node not found for ${ light.constructor.name }` );
  27107. continue;
  27108. }
  27109. let lightNode = null;
  27110. if ( ! _lightsNodeRef.has( light ) ) {
  27111. lightNode = nodeObject( new lightNodeClass( light ) );
  27112. _lightsNodeRef.set( light, lightNode );
  27113. } else {
  27114. lightNode = _lightsNodeRef.get( light );
  27115. }
  27116. lightNodes.push( lightNode );
  27117. }
  27118. }
  27119. }
  27120. this._lightNodes = lightNodes;
  27121. }
  27122. /**
  27123. * Sets up a direct light in the lighting model.
  27124. *
  27125. * @param {Object} builder - The builder object containing the context and stack.
  27126. * @param {Object} lightNode - The light node.
  27127. * @param {Object} lightData - The light object containing color and direction properties.
  27128. */
  27129. setupDirectLight( builder, lightNode, lightData ) {
  27130. const { lightingModel, reflectedLight } = builder.context;
  27131. lightingModel.direct( {
  27132. ...lightData,
  27133. lightNode,
  27134. reflectedLight
  27135. }, builder );
  27136. }
  27137. setupDirectRectAreaLight( builder, lightNode, lightData ) {
  27138. const { lightingModel, reflectedLight } = builder.context;
  27139. lightingModel.directRectArea( {
  27140. ...lightData,
  27141. lightNode,
  27142. reflectedLight
  27143. }, builder );
  27144. }
  27145. /**
  27146. * Setups the internal lights by building all respective
  27147. * light nodes.
  27148. *
  27149. * @param {NodeBuilder} builder - A reference to the current node builder.
  27150. * @param {Array<LightingNode>} lightNodes - An array of lighting nodes.
  27151. */
  27152. setupLights( builder, lightNodes ) {
  27153. for ( const lightNode of lightNodes ) {
  27154. lightNode.build( builder );
  27155. }
  27156. }
  27157. getLightNodes( builder ) {
  27158. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  27159. return this._lightNodes;
  27160. }
  27161. /**
  27162. * The implementation makes sure that for each light in the scene
  27163. * there is a corresponding light node. By building the light nodes
  27164. * and evaluating the lighting model the outgoing light is computed.
  27165. *
  27166. * @param {NodeBuilder} builder - A reference to the current node builder.
  27167. * @return {Node<vec3>} A node representing the outgoing light.
  27168. */
  27169. setup( builder ) {
  27170. const currentLightsNode = builder.lightsNode;
  27171. builder.lightsNode = this;
  27172. //
  27173. let outgoingLightNode = this.outgoingLightNode;
  27174. const context = builder.context;
  27175. const lightingModel = context.lightingModel;
  27176. const properties = builder.getNodeProperties( this );
  27177. if ( lightingModel ) {
  27178. const { totalDiffuseNode, totalSpecularNode } = this;
  27179. context.outgoingLight = outgoingLightNode;
  27180. const stack = builder.addStack();
  27181. //
  27182. properties.nodes = stack.nodes;
  27183. //
  27184. lightingModel.start( builder );
  27185. //
  27186. const { backdrop, backdropAlpha } = context;
  27187. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  27188. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  27189. if ( backdrop !== null ) {
  27190. if ( backdropAlpha !== null ) {
  27191. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  27192. } else {
  27193. totalDiffuse = vec3( backdrop );
  27194. }
  27195. context.material.transparent = true;
  27196. }
  27197. totalDiffuseNode.assign( totalDiffuse );
  27198. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  27199. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  27200. //
  27201. lightingModel.finish( builder );
  27202. //
  27203. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  27204. } else {
  27205. properties.nodes = [];
  27206. }
  27207. //
  27208. builder.lightsNode = currentLightsNode;
  27209. return outgoingLightNode;
  27210. }
  27211. /**
  27212. * Configures this node with an array of lights.
  27213. *
  27214. * @param {Array<Light>} lights - An array of lights.
  27215. * @return {LightsNode} A reference to this node.
  27216. */
  27217. setLights( lights ) {
  27218. this._lights = lights;
  27219. this._lightNodes = null;
  27220. this._lightNodesHash = null;
  27221. return this;
  27222. }
  27223. /**
  27224. * Returns an array of the scene's lights.
  27225. *
  27226. * @return {Array<Light>} The scene's lights.
  27227. */
  27228. getLights() {
  27229. return this._lights;
  27230. }
  27231. /**
  27232. * Whether the scene has lights or not.
  27233. *
  27234. * @type {boolean}
  27235. */
  27236. get hasLights() {
  27237. return this._lights.length > 0;
  27238. }
  27239. }
  27240. /**
  27241. * TSL function for creating an instance of `LightsNode` and configuring
  27242. * it with the given array of lights.
  27243. *
  27244. * @tsl
  27245. * @function
  27246. * @param {Array<Light>} lights - An array of lights.
  27247. * @return {LightsNode} The created lights node.
  27248. */
  27249. const lights = ( lights = [] ) => nodeObject( new LightsNode() ).setLights( lights );
  27250. /**
  27251. * Base class for all shadow nodes.
  27252. *
  27253. * Shadow nodes encapsulate shadow related logic and are always coupled to lighting nodes.
  27254. * Lighting nodes might share the same shadow node type or use specific ones depending on
  27255. * their requirements.
  27256. *
  27257. * @augments Node
  27258. */
  27259. class ShadowBaseNode extends Node {
  27260. static get type() {
  27261. return 'ShadowBaseNode';
  27262. }
  27263. /**
  27264. * Constructs a new shadow base node.
  27265. *
  27266. * @param {Light} light - The shadow casting light.
  27267. */
  27268. constructor( light ) {
  27269. super();
  27270. /**
  27271. * The shadow casting light.
  27272. *
  27273. * @type {Light}
  27274. */
  27275. this.light = light;
  27276. /**
  27277. * Overwritten since shadows are updated by default per render.
  27278. *
  27279. * @type {string}
  27280. * @default 'render'
  27281. */
  27282. this.updateBeforeType = NodeUpdateType.RENDER;
  27283. /**
  27284. * This flag can be used for type testing.
  27285. *
  27286. * @type {boolean}
  27287. * @readonly
  27288. * @default true
  27289. */
  27290. this.isShadowBaseNode = true;
  27291. }
  27292. /**
  27293. * Setups the shadow position node which is by default the predefined TSL node object `shadowPositionWorld`.
  27294. *
  27295. * @param {NodeBuilder} object - A configuration object that must at least hold a material reference.
  27296. */
  27297. setupShadowPosition( { context, material } ) {
  27298. // Use assign inside an Fn()
  27299. shadowPositionWorld.assign( material.receivedShadowPositionNode || context.shadowPositionWorld || positionWorld );
  27300. }
  27301. }
  27302. /**
  27303. * TSL object that represents the vertex position in world space during the shadow pass.
  27304. *
  27305. * @tsl
  27306. * @type {Node<vec3>}
  27307. */
  27308. const shadowPositionWorld = /*@__PURE__*/ property( 'vec3', 'shadowPositionWorld' );
  27309. /**
  27310. * Saves the state of the given renderer and stores it into the given state object.
  27311. *
  27312. * If not state object is provided, the function creates one.
  27313. *
  27314. * @function
  27315. * @param {Renderer} renderer - The renderer.
  27316. * @param {Object} [state={}] - The state.
  27317. * @return {Object} The state.
  27318. */
  27319. function saveRendererState( renderer, state = {} ) {
  27320. state.toneMapping = renderer.toneMapping;
  27321. state.toneMappingExposure = renderer.toneMappingExposure;
  27322. state.outputColorSpace = renderer.outputColorSpace;
  27323. state.renderTarget = renderer.getRenderTarget();
  27324. state.activeCubeFace = renderer.getActiveCubeFace();
  27325. state.activeMipmapLevel = renderer.getActiveMipmapLevel();
  27326. state.renderObjectFunction = renderer.getRenderObjectFunction();
  27327. state.pixelRatio = renderer.getPixelRatio();
  27328. state.mrt = renderer.getMRT();
  27329. state.clearColor = renderer.getClearColor( state.clearColor || new Color() );
  27330. state.clearAlpha = renderer.getClearAlpha();
  27331. state.autoClear = renderer.autoClear;
  27332. state.scissorTest = renderer.getScissorTest();
  27333. return state;
  27334. }
  27335. /**
  27336. * Saves the state of the given renderer and stores it into the given state object.
  27337. * Besides, the function also resets the state of the renderer to its default values.
  27338. *
  27339. * If not state object is provided, the function creates one.
  27340. *
  27341. * @function
  27342. * @param {Renderer} renderer - The renderer.
  27343. * @param {Object} [state={}] - The state.
  27344. * @return {Object} The state.
  27345. */
  27346. function resetRendererState( renderer, state ) {
  27347. state = saveRendererState( renderer, state );
  27348. renderer.setMRT( null );
  27349. renderer.setRenderObjectFunction( null );
  27350. renderer.setClearColor( 0x000000, 1 );
  27351. renderer.autoClear = true;
  27352. return state;
  27353. }
  27354. /**
  27355. * Restores the state of the given renderer from the given state object.
  27356. *
  27357. * @function
  27358. * @param {Renderer} renderer - The renderer.
  27359. * @param {Object} state - The state to restore.
  27360. */
  27361. function restoreRendererState( renderer, state ) {
  27362. renderer.toneMapping = state.toneMapping;
  27363. renderer.toneMappingExposure = state.toneMappingExposure;
  27364. renderer.outputColorSpace = state.outputColorSpace;
  27365. renderer.setRenderTarget( state.renderTarget, state.activeCubeFace, state.activeMipmapLevel );
  27366. renderer.setRenderObjectFunction( state.renderObjectFunction );
  27367. renderer.setPixelRatio( state.pixelRatio );
  27368. renderer.setMRT( state.mrt );
  27369. renderer.setClearColor( state.clearColor, state.clearAlpha );
  27370. renderer.autoClear = state.autoClear;
  27371. renderer.setScissorTest( state.scissorTest );
  27372. }
  27373. /**
  27374. * Saves the state of the given scene and stores it into the given state object.
  27375. *
  27376. * If not state object is provided, the function creates one.
  27377. *
  27378. * @function
  27379. * @param {Scene} scene - The scene.
  27380. * @param {Object} [state={}] - The state.
  27381. * @return {Object} The state.
  27382. */
  27383. function saveSceneState( scene, state = {} ) {
  27384. state.background = scene.background;
  27385. state.backgroundNode = scene.backgroundNode;
  27386. state.overrideMaterial = scene.overrideMaterial;
  27387. return state;
  27388. }
  27389. /**
  27390. * Saves the state of the given scene and stores it into the given state object.
  27391. * Besides, the function also resets the state of the scene to its default values.
  27392. *
  27393. * If not state object is provided, the function creates one.
  27394. *
  27395. * @function
  27396. * @param {Scene} scene - The scene.
  27397. * @param {Object} [state={}] - The state.
  27398. * @return {Object} The state.
  27399. */
  27400. function resetSceneState( scene, state ) {
  27401. state = saveSceneState( scene, state );
  27402. scene.background = null;
  27403. scene.backgroundNode = null;
  27404. scene.overrideMaterial = null;
  27405. return state;
  27406. }
  27407. /**
  27408. * Restores the state of the given scene from the given state object.
  27409. *
  27410. * @function
  27411. * @param {Scene} scene - The scene.
  27412. * @param {Object} state - The state to restore.
  27413. */
  27414. function restoreSceneState( scene, state ) {
  27415. scene.background = state.background;
  27416. scene.backgroundNode = state.backgroundNode;
  27417. scene.overrideMaterial = state.overrideMaterial;
  27418. }
  27419. /**
  27420. * Saves the state of the given renderer and scene and stores it into the given state object.
  27421. *
  27422. * If not state object is provided, the function creates one.
  27423. *
  27424. * @function
  27425. * @param {Renderer} renderer - The renderer.
  27426. * @param {Scene} scene - The scene.
  27427. * @param {Object} [state={}] - The state.
  27428. * @return {Object} The state.
  27429. */
  27430. function saveRendererAndSceneState( renderer, scene, state = {} ) {
  27431. state = saveRendererState( renderer, state );
  27432. state = saveSceneState( scene, state );
  27433. return state;
  27434. }
  27435. /**
  27436. * Saves the state of the given renderer and scene and stores it into the given state object.
  27437. * Besides, the function also resets the state of the renderer and scene to its default values.
  27438. *
  27439. * If not state object is provided, the function creates one.
  27440. *
  27441. * @function
  27442. * @param {Renderer} renderer - The renderer.
  27443. * @param {Scene} scene - The scene.
  27444. * @param {Object} [state={}] - The state.
  27445. * @return {Object} The state.
  27446. */
  27447. function resetRendererAndSceneState( renderer, scene, state ) {
  27448. state = resetRendererState( renderer, state );
  27449. state = resetSceneState( scene, state );
  27450. return state;
  27451. }
  27452. /**
  27453. * Restores the state of the given renderer and scene from the given state object.
  27454. *
  27455. * @function
  27456. * @param {Renderer} renderer - The renderer.
  27457. * @param {Scene} scene - The scene.
  27458. * @param {Object} state - The state to restore.
  27459. */
  27460. function restoreRendererAndSceneState( renderer, scene, state ) {
  27461. restoreRendererState( renderer, state );
  27462. restoreSceneState( scene, state );
  27463. }
  27464. var RendererUtils = /*#__PURE__*/Object.freeze({
  27465. __proto__: null,
  27466. resetRendererAndSceneState: resetRendererAndSceneState,
  27467. resetRendererState: resetRendererState,
  27468. resetSceneState: resetSceneState,
  27469. restoreRendererAndSceneState: restoreRendererAndSceneState,
  27470. restoreRendererState: restoreRendererState,
  27471. restoreSceneState: restoreSceneState,
  27472. saveRendererAndSceneState: saveRendererAndSceneState,
  27473. saveRendererState: saveRendererState,
  27474. saveSceneState: saveSceneState
  27475. });
  27476. const shadowMaterialLib = /*@__PURE__*/ new WeakMap();
  27477. /**
  27478. * A shadow filtering function performing basic filtering. This is in fact an unfiltered version of the shadow map
  27479. * with a binary `[0,1]` result.
  27480. *
  27481. * @method
  27482. * @param {Object} inputs - The input parameter object.
  27483. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  27484. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  27485. * @return {Node<float>} The filtering result.
  27486. */
  27487. const BasicShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, depthLayer } ) => {
  27488. let basic = texture( depthTexture, shadowCoord.xy ).label( 't_basic' );
  27489. if ( depthTexture.isArrayTexture ) {
  27490. basic = basic.depth( depthLayer );
  27491. }
  27492. return basic.compare( shadowCoord.z );
  27493. } );
  27494. /**
  27495. * A shadow filtering function performing PCF filtering.
  27496. *
  27497. * @method
  27498. * @param {Object} inputs - The input parameter object.
  27499. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  27500. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  27501. * @param {LightShadow} inputs.shadow - The light shadow.
  27502. * @return {Node<float>} The filtering result.
  27503. */
  27504. const PCFShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow, depthLayer } ) => {
  27505. const depthCompare = ( uv, compare ) => {
  27506. let depth = texture( depthTexture, uv );
  27507. if ( depthTexture.isArrayTexture ) {
  27508. depth = depth.depth( depthLayer );
  27509. }
  27510. return depth.compare( compare );
  27511. };
  27512. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  27513. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  27514. const texelSize = vec2( 1 ).div( mapSize );
  27515. const dx0 = texelSize.x.negate().mul( radius );
  27516. const dy0 = texelSize.y.negate().mul( radius );
  27517. const dx1 = texelSize.x.mul( radius );
  27518. const dy1 = texelSize.y.mul( radius );
  27519. const dx2 = dx0.div( 2 );
  27520. const dy2 = dy0.div( 2 );
  27521. const dx3 = dx1.div( 2 );
  27522. const dy3 = dy1.div( 2 );
  27523. return add(
  27524. depthCompare( shadowCoord.xy.add( vec2( dx0, dy0 ) ), shadowCoord.z ),
  27525. depthCompare( shadowCoord.xy.add( vec2( 0, dy0 ) ), shadowCoord.z ),
  27526. depthCompare( shadowCoord.xy.add( vec2( dx1, dy0 ) ), shadowCoord.z ),
  27527. depthCompare( shadowCoord.xy.add( vec2( dx2, dy2 ) ), shadowCoord.z ),
  27528. depthCompare( shadowCoord.xy.add( vec2( 0, dy2 ) ), shadowCoord.z ),
  27529. depthCompare( shadowCoord.xy.add( vec2( dx3, dy2 ) ), shadowCoord.z ),
  27530. depthCompare( shadowCoord.xy.add( vec2( dx0, 0 ) ), shadowCoord.z ),
  27531. depthCompare( shadowCoord.xy.add( vec2( dx2, 0 ) ), shadowCoord.z ),
  27532. depthCompare( shadowCoord.xy, shadowCoord.z ),
  27533. depthCompare( shadowCoord.xy.add( vec2( dx3, 0 ) ), shadowCoord.z ),
  27534. depthCompare( shadowCoord.xy.add( vec2( dx1, 0 ) ), shadowCoord.z ),
  27535. depthCompare( shadowCoord.xy.add( vec2( dx2, dy3 ) ), shadowCoord.z ),
  27536. depthCompare( shadowCoord.xy.add( vec2( 0, dy3 ) ), shadowCoord.z ),
  27537. depthCompare( shadowCoord.xy.add( vec2( dx3, dy3 ) ), shadowCoord.z ),
  27538. depthCompare( shadowCoord.xy.add( vec2( dx0, dy1 ) ), shadowCoord.z ),
  27539. depthCompare( shadowCoord.xy.add( vec2( 0, dy1 ) ), shadowCoord.z ),
  27540. depthCompare( shadowCoord.xy.add( vec2( dx1, dy1 ) ), shadowCoord.z )
  27541. ).mul( 1 / 17 );
  27542. } );
  27543. /**
  27544. * A shadow filtering function performing PCF soft filtering.
  27545. *
  27546. * @method
  27547. * @param {Object} inputs - The input parameter object.
  27548. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  27549. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  27550. * @param {LightShadow} inputs.shadow - The light shadow.
  27551. * @return {Node<float>} The filtering result.
  27552. */
  27553. const PCFSoftShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow, depthLayer } ) => {
  27554. const depthCompare = ( uv, compare ) => {
  27555. let depth = texture( depthTexture, uv );
  27556. if ( depthTexture.isArrayTexture ) {
  27557. depth = depth.depth( depthLayer );
  27558. }
  27559. return depth.compare( compare );
  27560. };
  27561. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  27562. const texelSize = vec2( 1 ).div( mapSize );
  27563. const dx = texelSize.x;
  27564. const dy = texelSize.y;
  27565. const uv = shadowCoord.xy;
  27566. const f = fract( uv.mul( mapSize ).add( 0.5 ) );
  27567. uv.subAssign( f.mul( texelSize ) );
  27568. return add(
  27569. depthCompare( uv, shadowCoord.z ),
  27570. depthCompare( uv.add( vec2( dx, 0 ) ), shadowCoord.z ),
  27571. depthCompare( uv.add( vec2( 0, dy ) ), shadowCoord.z ),
  27572. depthCompare( uv.add( texelSize ), shadowCoord.z ),
  27573. mix(
  27574. depthCompare( uv.add( vec2( dx.negate(), 0 ) ), shadowCoord.z ),
  27575. depthCompare( uv.add( vec2( dx.mul( 2 ), 0 ) ), shadowCoord.z ),
  27576. f.x
  27577. ),
  27578. mix(
  27579. depthCompare( uv.add( vec2( dx.negate(), dy ) ), shadowCoord.z ),
  27580. depthCompare( uv.add( vec2( dx.mul( 2 ), dy ) ), shadowCoord.z ),
  27581. f.x
  27582. ),
  27583. mix(
  27584. depthCompare( uv.add( vec2( 0, dy.negate() ) ), shadowCoord.z ),
  27585. depthCompare( uv.add( vec2( 0, dy.mul( 2 ) ) ), shadowCoord.z ),
  27586. f.y
  27587. ),
  27588. mix(
  27589. depthCompare( uv.add( vec2( dx, dy.negate() ) ), shadowCoord.z ),
  27590. depthCompare( uv.add( vec2( dx, dy.mul( 2 ) ) ), shadowCoord.z ),
  27591. f.y
  27592. ),
  27593. mix(
  27594. mix(
  27595. depthCompare( uv.add( vec2( dx.negate(), dy.negate() ) ), shadowCoord.z ),
  27596. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.negate() ) ), shadowCoord.z ),
  27597. f.x
  27598. ),
  27599. mix(
  27600. depthCompare( uv.add( vec2( dx.negate(), dy.mul( 2 ) ) ), shadowCoord.z ),
  27601. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.mul( 2 ) ) ), shadowCoord.z ),
  27602. f.x
  27603. ),
  27604. f.y
  27605. )
  27606. ).mul( 1 / 9 );
  27607. } );
  27608. /**
  27609. * A shadow filtering function performing VSM filtering.
  27610. *
  27611. * @method
  27612. * @param {Object} inputs - The input parameter object.
  27613. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  27614. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  27615. * @return {Node<float>} The filtering result.
  27616. */
  27617. const VSMShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, depthLayer } ) => {
  27618. const occlusion = float( 1 ).toVar();
  27619. let distribution = texture( depthTexture ).sample( shadowCoord.xy );
  27620. if ( depthTexture.isArrayTexture ) {
  27621. distribution = distribution.depth( depthLayer );
  27622. }
  27623. distribution = distribution.rg;
  27624. const hardShadow = step( shadowCoord.z, distribution.x );
  27625. If( hardShadow.notEqual( float( 1.0 ) ), () => {
  27626. const distance = shadowCoord.z.sub( distribution.x );
  27627. const variance = max$1( 0, distribution.y.mul( distribution.y ) );
  27628. let softnessProbability = variance.div( variance.add( distance.mul( distance ) ) ); // Chebeyshevs inequality
  27629. softnessProbability = clamp( sub( softnessProbability, 0.3 ).div( 0.95 - 0.3 ) );
  27630. occlusion.assign( clamp( max$1( hardShadow, softnessProbability ) ) );
  27631. } );
  27632. return occlusion;
  27633. } );
  27634. //
  27635. const linearDistance = /*@__PURE__*/ Fn( ( [ position, cameraNear, cameraFar ] ) => {
  27636. let dist = positionWorld.sub( position ).length();
  27637. dist = dist.sub( cameraNear ).div( cameraFar.sub( cameraNear ) );
  27638. dist = dist.saturate(); // clamp to [ 0, 1 ]
  27639. return dist;
  27640. } );
  27641. const linearShadowDistance = ( light ) => {
  27642. const camera = light.shadow.camera;
  27643. const nearDistance = reference( 'near', 'float', camera ).setGroup( renderGroup );
  27644. const farDistance = reference( 'far', 'float', camera ).setGroup( renderGroup );
  27645. const referencePosition = objectPosition( light );
  27646. return linearDistance( referencePosition, nearDistance, farDistance );
  27647. };
  27648. /**
  27649. * Retrieves or creates a shadow material for the given light source.
  27650. *
  27651. * This function checks if a shadow material already exists for the provided light.
  27652. * If not, it creates a new `NodeMaterial` configured for shadow rendering and stores it
  27653. * in the `shadowMaterialLib` for future use.
  27654. *
  27655. * @param {Light} light - The light source for which the shadow material is needed.
  27656. * If the light is a point light, a depth node is calculated
  27657. * using the linear shadow distance.
  27658. * @returns {NodeMaterial} The shadow material associated with the given light.
  27659. */
  27660. const getShadowMaterial = ( light ) => {
  27661. let material = shadowMaterialLib.get( light );
  27662. if ( material === undefined ) {
  27663. const depthNode = light.isPointLight ? linearShadowDistance( light ) : null;
  27664. material = new NodeMaterial();
  27665. material.colorNode = vec4( 0, 0, 0, 1 );
  27666. material.depthNode = depthNode;
  27667. material.isShadowPassMaterial = true; // Use to avoid other overrideMaterial override material.colorNode unintentionally when using material.shadowNode
  27668. material.name = 'ShadowMaterial';
  27669. material.fog = false;
  27670. shadowMaterialLib.set( light, material );
  27671. }
  27672. return material;
  27673. };
  27674. //
  27675. const _shadowRenderObjectLibrary = /*@__PURE__*/ new ChainMap();
  27676. const _shadowRenderObjectKeys = [];
  27677. /**
  27678. * Creates a function to render shadow objects in a scene.
  27679. *
  27680. * @param {Renderer} renderer - The renderer.
  27681. * @param {LightShadow} shadow - The light shadow object containing shadow properties.
  27682. * @param {number} shadowType - The type of shadow map (e.g., BasicShadowMap).
  27683. * @param {boolean} useVelocity - Whether to use velocity data for rendering.
  27684. * @return {Function} A function that renders shadow objects.
  27685. *
  27686. * The returned function has the following parameters:
  27687. * @param {Object3D} object - The 3D object to render.
  27688. * @param {Scene} scene - The scene containing the object.
  27689. * @param {Camera} _camera - The camera used for rendering.
  27690. * @param {BufferGeometry} geometry - The geometry of the object.
  27691. * @param {Material} material - The material of the object.
  27692. * @param {Group} group - The group the object belongs to.
  27693. * @param {...any} params - Additional parameters for rendering.
  27694. */
  27695. const getShadowRenderObjectFunction = ( renderer, shadow, shadowType, useVelocity ) => {
  27696. _shadowRenderObjectKeys[ 0 ] = renderer;
  27697. _shadowRenderObjectKeys[ 1 ] = shadow;
  27698. let renderObjectFunction = _shadowRenderObjectLibrary.get( _shadowRenderObjectKeys );
  27699. if ( renderObjectFunction === undefined || ( renderObjectFunction.shadowType !== shadowType || renderObjectFunction.useVelocity !== useVelocity ) ) {
  27700. renderObjectFunction = ( object, scene, _camera, geometry, material, group, ...params ) => {
  27701. if ( object.castShadow === true || ( object.receiveShadow && shadowType === VSMShadowMap ) ) {
  27702. if ( useVelocity ) {
  27703. getDataFromObject( object ).useVelocity = true;
  27704. }
  27705. object.onBeforeShadow( renderer, object, _camera, shadow.camera, geometry, scene.overrideMaterial, group );
  27706. renderer.renderObject( object, scene, _camera, geometry, material, group, ...params );
  27707. object.onAfterShadow( renderer, object, _camera, shadow.camera, geometry, scene.overrideMaterial, group );
  27708. }
  27709. };
  27710. renderObjectFunction.shadowType = shadowType;
  27711. renderObjectFunction.useVelocity = useVelocity;
  27712. _shadowRenderObjectLibrary.set( _shadowRenderObjectKeys, renderObjectFunction );
  27713. }
  27714. _shadowRenderObjectKeys[ 0 ] = null;
  27715. _shadowRenderObjectKeys[ 1 ] = null;
  27716. return renderObjectFunction;
  27717. };
  27718. /**
  27719. * Represents the shader code for the first VSM render pass.
  27720. *
  27721. * @method
  27722. * @param {Object} inputs - The input parameter object.
  27723. * @param {Node<float>} inputs.samples - The number of samples
  27724. * @param {Node<float>} inputs.radius - The radius.
  27725. * @param {Node<float>} inputs.size - The size.
  27726. * @param {TextureNode} inputs.shadowPass - A reference to the render target's depth data.
  27727. * @return {Node<vec2>} The VSM output.
  27728. */
  27729. const VSMPassVertical = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass, depthLayer } ) => {
  27730. const mean = float( 0 ).toVar( 'meanVertical' );
  27731. const squaredMean = float( 0 ).toVar( 'squareMeanVertical' );
  27732. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  27733. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( -1 ) );
  27734. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  27735. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  27736. let depth = shadowPass.sample( add( screenCoordinate.xy, vec2( 0, uvOffset ).mul( radius ) ).div( size ) );
  27737. if ( shadowPass.value.isArrayTexture ) {
  27738. depth = depth.depth( depthLayer );
  27739. }
  27740. depth = depth.x;
  27741. mean.addAssign( depth );
  27742. squaredMean.addAssign( depth.mul( depth ) );
  27743. } );
  27744. mean.divAssign( samples );
  27745. squaredMean.divAssign( samples );
  27746. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  27747. return vec2( mean, std_dev );
  27748. } );
  27749. /**
  27750. * Represents the shader code for the second VSM render pass.
  27751. *
  27752. * @method
  27753. * @param {Object} inputs - The input parameter object.
  27754. * @param {Node<float>} inputs.samples - The number of samples
  27755. * @param {Node<float>} inputs.radius - The radius.
  27756. * @param {Node<float>} inputs.size - The size.
  27757. * @param {TextureNode} inputs.shadowPass - The result of the first VSM render pass.
  27758. * @return {Node<vec2>} The VSM output.
  27759. */
  27760. const VSMPassHorizontal = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass, depthLayer } ) => {
  27761. const mean = float( 0 ).toVar( 'meanHorizontal' );
  27762. const squaredMean = float( 0 ).toVar( 'squareMeanHorizontal' );
  27763. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  27764. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( -1 ) );
  27765. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  27766. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  27767. let distribution = shadowPass.sample( add( screenCoordinate.xy, vec2( uvOffset, 0 ).mul( radius ) ).div( size ) );
  27768. if ( shadowPass.value.isArrayTexture ) {
  27769. distribution = distribution.depth( depthLayer );
  27770. }
  27771. mean.addAssign( distribution.x );
  27772. squaredMean.addAssign( add( distribution.y.mul( distribution.y ), distribution.x.mul( distribution.x ) ) );
  27773. } );
  27774. mean.divAssign( samples );
  27775. squaredMean.divAssign( samples );
  27776. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  27777. return vec2( mean, std_dev );
  27778. } );
  27779. const _shadowFilterLib = [ BasicShadowFilter, PCFShadowFilter, PCFSoftShadowFilter, VSMShadowFilter ];
  27780. //
  27781. let _rendererState;
  27782. const _quadMesh = /*@__PURE__*/ new QuadMesh();
  27783. /**
  27784. * Represents the default shadow implementation for lighting nodes.
  27785. *
  27786. * @augments ShadowBaseNode
  27787. */
  27788. class ShadowNode extends ShadowBaseNode {
  27789. static get type() {
  27790. return 'ShadowNode';
  27791. }
  27792. /**
  27793. * Constructs a new shadow node.
  27794. *
  27795. * @param {Light} light - The shadow casting light.
  27796. * @param {?LightShadow} [shadow=null] - An optional light shadow.
  27797. */
  27798. constructor( light, shadow = null ) {
  27799. super( light );
  27800. /**
  27801. * The light shadow which defines the properties light's
  27802. * shadow.
  27803. *
  27804. * @type {?LightShadow}
  27805. * @default null
  27806. */
  27807. this.shadow = shadow || light.shadow;
  27808. /**
  27809. * A reference to the shadow map which is a render target.
  27810. *
  27811. * @type {?RenderTarget}
  27812. * @default null
  27813. */
  27814. this.shadowMap = null;
  27815. /**
  27816. * Only relevant for VSM shadows. Render target for the
  27817. * first VSM render pass.
  27818. *
  27819. * @type {?RenderTarget}
  27820. * @default null
  27821. */
  27822. this.vsmShadowMapVertical = null;
  27823. /**
  27824. * Only relevant for VSM shadows. Render target for the
  27825. * second VSM render pass.
  27826. *
  27827. * @type {?RenderTarget}
  27828. * @default null
  27829. */
  27830. this.vsmShadowMapHorizontal = null;
  27831. /**
  27832. * Only relevant for VSM shadows. Node material which
  27833. * is used to render the first VSM pass.
  27834. *
  27835. * @type {?NodeMaterial}
  27836. * @default null
  27837. */
  27838. this.vsmMaterialVertical = null;
  27839. /**
  27840. * Only relevant for VSM shadows. Node material which
  27841. * is used to render the second VSM pass.
  27842. *
  27843. * @type {?NodeMaterial}
  27844. * @default null
  27845. */
  27846. this.vsmMaterialHorizontal = null;
  27847. /**
  27848. * A reference to the output node which defines the
  27849. * final result of this shadow node.
  27850. *
  27851. * @type {?Node}
  27852. * @private
  27853. * @default null
  27854. */
  27855. this._node = null;
  27856. this._cameraFrameId = new WeakMap();
  27857. /**
  27858. * This flag can be used for type testing.
  27859. *
  27860. * @type {boolean}
  27861. * @readonly
  27862. * @default true
  27863. */
  27864. this.isShadowNode = true;
  27865. /**
  27866. * This index can be used when overriding setupRenderTarget with a RenderTarget Array to specify the depth layer.
  27867. *
  27868. * @type {number}
  27869. * @readonly
  27870. * @default true
  27871. */
  27872. this.depthLayer = 0;
  27873. }
  27874. /**
  27875. * Setups the shadow filtering.
  27876. *
  27877. * @param {NodeBuilder} builder - A reference to the current node builder.
  27878. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  27879. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  27880. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  27881. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  27882. * @param {LightShadow} inputs.shadow - The light shadow.
  27883. * @return {Node<float>} The result node of the shadow filtering.
  27884. */
  27885. setupShadowFilter( builder, { filterFn, depthTexture, shadowCoord, shadow, depthLayer } ) {
  27886. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  27887. .and( shadowCoord.x.lessThanEqual( 1 ) )
  27888. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  27889. .and( shadowCoord.y.lessThanEqual( 1 ) )
  27890. .and( shadowCoord.z.lessThanEqual( 1 ) );
  27891. const shadowNode = filterFn( { depthTexture, shadowCoord, shadow, depthLayer } );
  27892. return frustumTest.select( shadowNode, float( 1 ) );
  27893. }
  27894. /**
  27895. * Setups the shadow coordinates.
  27896. *
  27897. * @param {NodeBuilder} builder - A reference to the current node builder.
  27898. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  27899. * @return {Node<vec3>} The shadow coordinates.
  27900. */
  27901. setupShadowCoord( builder, shadowPosition ) {
  27902. const { shadow } = this;
  27903. const { renderer } = builder;
  27904. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  27905. let shadowCoord = shadowPosition;
  27906. let coordZ;
  27907. if ( shadow.camera.isOrthographicCamera || renderer.logarithmicDepthBuffer !== true ) {
  27908. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  27909. coordZ = shadowCoord.z;
  27910. if ( renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  27911. coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Conversion [ 0, 1 ] to [ - 1, 1 ]
  27912. }
  27913. } else {
  27914. const w = shadowCoord.w;
  27915. shadowCoord = shadowCoord.xy.div( w ); // <-- Only divide X/Y coords since we don't need Z
  27916. // The normally available "cameraNear" and "cameraFar" nodes cannot be used here because they do not get
  27917. // updated to use the shadow camera. So, we have to declare our own "local" ones here.
  27918. // TODO: How do we get the cameraNear/cameraFar nodes to use the shadow camera so we don't have to declare local ones here?
  27919. const cameraNearLocal = reference( 'near', 'float', shadow.camera ).setGroup( renderGroup );
  27920. const cameraFarLocal = reference( 'far', 'float', shadow.camera ).setGroup( renderGroup );
  27921. coordZ = viewZToLogarithmicDepth( w.negate(), cameraNearLocal, cameraFarLocal );
  27922. }
  27923. shadowCoord = vec3(
  27924. shadowCoord.x,
  27925. shadowCoord.y.oneMinus(), // follow webgpu standards
  27926. coordZ.add( bias )
  27927. );
  27928. return shadowCoord;
  27929. }
  27930. /**
  27931. * Returns the shadow filtering function for the given shadow type.
  27932. *
  27933. * @param {number} type - The shadow type.
  27934. * @return {Function} The filtering function.
  27935. */
  27936. getShadowFilterFn( type ) {
  27937. return _shadowFilterLib[ type ];
  27938. }
  27939. setupRenderTarget( shadow, builder ) {
  27940. const depthTexture = new DepthTexture( shadow.mapSize.width, shadow.mapSize.height );
  27941. depthTexture.name = 'ShadowDepthTexture';
  27942. depthTexture.compareFunction = LessCompare;
  27943. const shadowMap = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  27944. shadowMap.texture.name = 'ShadowMap';
  27945. shadowMap.texture.type = shadow.mapType;
  27946. shadowMap.depthTexture = depthTexture;
  27947. return { shadowMap, depthTexture };
  27948. }
  27949. /**
  27950. * Setups the shadow output node.
  27951. *
  27952. * @param {NodeBuilder} builder - A reference to the current node builder.
  27953. * @return {Node<vec3>} The shadow output node.
  27954. */
  27955. setupShadow( builder ) {
  27956. const { renderer } = builder;
  27957. const { light, shadow } = this;
  27958. const shadowMapType = renderer.shadowMap.type;
  27959. const { depthTexture, shadowMap } = this.setupRenderTarget( shadow, builder );
  27960. shadow.camera.updateProjectionMatrix();
  27961. // VSM
  27962. if ( shadowMapType === VSMShadowMap && shadow.isPointLightShadow !== true ) {
  27963. depthTexture.compareFunction = null; // VSM does not use textureSampleCompare()/texture2DCompare()
  27964. if ( shadowMap.depth > 1 ) {
  27965. if ( ! shadowMap._vsmShadowMapVertical ) {
  27966. shadowMap._vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depth: shadowMap.depth, depthBuffer: false } );
  27967. shadowMap._vsmShadowMapVertical.texture.name = 'VSMVertical';
  27968. }
  27969. this.vsmShadowMapVertical = shadowMap._vsmShadowMapVertical;
  27970. if ( ! shadowMap._vsmShadowMapHorizontal ) {
  27971. shadowMap._vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depth: shadowMap.depth, depthBuffer: false } );
  27972. shadowMap._vsmShadowMapHorizontal.texture.name = 'VSMHorizontal';
  27973. }
  27974. this.vsmShadowMapHorizontal = shadowMap._vsmShadowMapHorizontal;
  27975. } else {
  27976. this.vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depthBuffer: false } );
  27977. this.vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depthBuffer: false } );
  27978. }
  27979. let shadowPassVertical = texture( depthTexture );
  27980. if ( depthTexture.isArrayTexture ) {
  27981. shadowPassVertical = shadowPassVertical.depth( this.depthLayer );
  27982. }
  27983. let shadowPassHorizontal = texture( this.vsmShadowMapVertical.texture );
  27984. if ( depthTexture.isArrayTexture ) {
  27985. shadowPassHorizontal = shadowPassHorizontal.depth( this.depthLayer );
  27986. }
  27987. const samples = reference( 'blurSamples', 'float', shadow ).setGroup( renderGroup );
  27988. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  27989. const size = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  27990. let material = this.vsmMaterialVertical || ( this.vsmMaterialVertical = new NodeMaterial() );
  27991. material.fragmentNode = VSMPassVertical( { samples, radius, size, shadowPass: shadowPassVertical, depthLayer: this.depthLayer } ).context( builder.getSharedContext() );
  27992. material.name = 'VSMVertical';
  27993. material = this.vsmMaterialHorizontal || ( this.vsmMaterialHorizontal = new NodeMaterial() );
  27994. material.fragmentNode = VSMPassHorizontal( { samples, radius, size, shadowPass: shadowPassHorizontal, depthLayer: this.depthLayer } ).context( builder.getSharedContext() );
  27995. material.name = 'VSMHorizontal';
  27996. }
  27997. //
  27998. const shadowIntensity = reference( 'intensity', 'float', shadow ).setGroup( renderGroup );
  27999. const normalBias = reference( 'normalBias', 'float', shadow ).setGroup( renderGroup );
  28000. const shadowPosition = lightShadowMatrix( light ).mul( shadowPositionWorld.add( transformedNormalWorld.mul( normalBias ) ) );
  28001. const shadowCoord = this.setupShadowCoord( builder, shadowPosition );
  28002. //
  28003. const filterFn = shadow.filterNode || this.getShadowFilterFn( renderer.shadowMap.type ) || null;
  28004. if ( filterFn === null ) {
  28005. throw new Error( 'THREE.WebGPURenderer: Shadow map type not supported yet.' );
  28006. }
  28007. const shadowDepthTexture = ( shadowMapType === VSMShadowMap && shadow.isPointLightShadow !== true ) ? this.vsmShadowMapHorizontal.texture : depthTexture;
  28008. const shadowNode = this.setupShadowFilter( builder, { filterFn, shadowTexture: shadowMap.texture, depthTexture: shadowDepthTexture, shadowCoord, shadow, depthLayer: this.depthLayer } );
  28009. let shadowColor = texture( shadowMap.texture, shadowCoord );
  28010. if ( depthTexture.isArrayTexture ) {
  28011. shadowColor = shadowColor.depth( this.depthLayer );
  28012. }
  28013. const shadowOutput = mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) ).toVar();
  28014. this.shadowMap = shadowMap;
  28015. this.shadow.map = shadowMap;
  28016. return shadowOutput;
  28017. }
  28018. /**
  28019. * The implementation performs the setup of the output node. An output is only
  28020. * produces if shadow mapping is globally enabled in the renderer.
  28021. *
  28022. * @param {NodeBuilder} builder - A reference to the current node builder.
  28023. * @return {ShaderCallNodeInternal} The output node.
  28024. */
  28025. setup( builder ) {
  28026. if ( builder.renderer.shadowMap.enabled === false ) return;
  28027. return Fn( () => {
  28028. let node = this._node;
  28029. this.setupShadowPosition( builder );
  28030. if ( node === null ) {
  28031. this._node = node = this.setupShadow( builder );
  28032. }
  28033. if ( builder.material.shadowNode ) { // @deprecated, r171
  28034. console.warn( 'THREE.NodeMaterial: ".shadowNode" is deprecated. Use ".castShadowNode" instead.' );
  28035. }
  28036. if ( builder.material.receivedShadowNode ) {
  28037. node = builder.material.receivedShadowNode( node );
  28038. }
  28039. return node;
  28040. } )();
  28041. }
  28042. /**
  28043. * Renders the shadow. The logic of this function could be included
  28044. * into {@link ShadowNode#updateShadow} however more specialized shadow
  28045. * nodes might require a custom shadow map rendering. By having a
  28046. * dedicated method, it's easier to overwrite the default behavior.
  28047. *
  28048. * @param {NodeFrame} frame - A reference to the current node frame.
  28049. */
  28050. renderShadow( frame ) {
  28051. const { shadow, shadowMap, light } = this;
  28052. const { renderer, scene } = frame;
  28053. shadow.updateMatrices( light );
  28054. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.height, shadowMap.depth );
  28055. renderer.render( scene, shadow.camera );
  28056. }
  28057. /**
  28058. * Updates the shadow.
  28059. *
  28060. * @param {NodeFrame} frame - A reference to the current node frame.
  28061. */
  28062. updateShadow( frame ) {
  28063. const { shadowMap, light, shadow } = this;
  28064. const { renderer, scene, camera } = frame;
  28065. const shadowType = renderer.shadowMap.type;
  28066. const depthVersion = shadowMap.depthTexture.version;
  28067. this._depthVersionCached = depthVersion;
  28068. const _shadowCameraLayer = shadow.camera.layers.mask;
  28069. if ( ( shadow.camera.layers.mask & 0xFFFFFFFE ) === 0 ) {
  28070. shadow.camera.layers.mask = camera.layers.mask;
  28071. }
  28072. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  28073. const currentMRT = renderer.getMRT();
  28074. const useVelocity = currentMRT ? currentMRT.has( 'velocity' ) : false;
  28075. _rendererState = resetRendererAndSceneState( renderer, scene, _rendererState );
  28076. scene.overrideMaterial = getShadowMaterial( light );
  28077. renderer.setRenderObjectFunction( getShadowRenderObjectFunction( renderer, shadow, shadowType, useVelocity ) );
  28078. renderer.setClearColor( 0x000000, 0 );
  28079. renderer.setRenderTarget( shadowMap );
  28080. this.renderShadow( frame );
  28081. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  28082. // vsm blur pass
  28083. if ( shadowType === VSMShadowMap && shadow.isPointLightShadow !== true ) {
  28084. this.vsmPass( renderer );
  28085. }
  28086. shadow.camera.layers.mask = _shadowCameraLayer;
  28087. restoreRendererAndSceneState( renderer, scene, _rendererState );
  28088. }
  28089. /**
  28090. * For VSM additional render passes are required.
  28091. *
  28092. * @param {Renderer} renderer - A reference to the current renderer.
  28093. */
  28094. vsmPass( renderer ) {
  28095. const { shadow } = this;
  28096. const depth = this.shadowMap.depth;
  28097. this.vsmShadowMapVertical.setSize( shadow.mapSize.width, shadow.mapSize.height, depth );
  28098. this.vsmShadowMapHorizontal.setSize( shadow.mapSize.width, shadow.mapSize.height, depth );
  28099. renderer.setRenderTarget( this.vsmShadowMapVertical );
  28100. _quadMesh.material = this.vsmMaterialVertical;
  28101. _quadMesh.render( renderer );
  28102. renderer.setRenderTarget( this.vsmShadowMapHorizontal );
  28103. _quadMesh.material = this.vsmMaterialHorizontal;
  28104. _quadMesh.render( renderer );
  28105. }
  28106. /**
  28107. * Frees the internal resources of this shadow node.
  28108. */
  28109. dispose() {
  28110. this.shadowMap.dispose();
  28111. this.shadowMap = null;
  28112. if ( this.vsmShadowMapVertical !== null ) {
  28113. this.vsmShadowMapVertical.dispose();
  28114. this.vsmShadowMapVertical = null;
  28115. this.vsmMaterialVertical.dispose();
  28116. this.vsmMaterialVertical = null;
  28117. }
  28118. if ( this.vsmShadowMapHorizontal !== null ) {
  28119. this.vsmShadowMapHorizontal.dispose();
  28120. this.vsmShadowMapHorizontal = null;
  28121. this.vsmMaterialHorizontal.dispose();
  28122. this.vsmMaterialHorizontal = null;
  28123. }
  28124. super.dispose();
  28125. }
  28126. /**
  28127. * The implementation performs the update of the shadow map if necessary.
  28128. *
  28129. * @param {NodeFrame} frame - A reference to the current node frame.
  28130. */
  28131. updateBefore( frame ) {
  28132. const { shadow } = this;
  28133. let needsUpdate = shadow.needsUpdate || shadow.autoUpdate;
  28134. if ( needsUpdate ) {
  28135. if ( this._cameraFrameId[ frame.camera ] === frame.frameId ) {
  28136. needsUpdate = false;
  28137. }
  28138. this._cameraFrameId[ frame.camera ] = frame.frameId;
  28139. }
  28140. if ( needsUpdate ) {
  28141. this.updateShadow( frame );
  28142. if ( this.shadowMap.depthTexture.version === this._depthVersionCached ) {
  28143. shadow.needsUpdate = false;
  28144. }
  28145. }
  28146. }
  28147. }
  28148. /**
  28149. * TSL function for creating an instance of `ShadowNode`.
  28150. *
  28151. * @tsl
  28152. * @function
  28153. * @param {Light} light - The shadow casting light.
  28154. * @param {?LightShadow} [shadow] - The light shadow.
  28155. * @return {ShadowNode} The created shadow node.
  28156. */
  28157. const shadow = ( light, shadow ) => nodeObject( new ShadowNode( light, shadow ) );
  28158. const _clearColor$1 = /*@__PURE__*/ new Color();
  28159. // cubeToUV() maps a 3D direction vector suitable for cube texture mapping to a 2D
  28160. // vector suitable for 2D texture mapping. This code uses the following layout for the
  28161. // 2D texture:
  28162. //
  28163. // xzXZ
  28164. // y Y
  28165. //
  28166. // Y - Positive y direction
  28167. // y - Negative y direction
  28168. // X - Positive x direction
  28169. // x - Negative x direction
  28170. // Z - Positive z direction
  28171. // z - Negative z direction
  28172. //
  28173. // Source and test bed:
  28174. // https://gist.github.com/tschw/da10c43c467ce8afd0c4
  28175. const cubeToUV = /*@__PURE__*/ Fn( ( [ pos, texelSizeY ] ) => {
  28176. const v = pos.toVar();
  28177. // Number of texels to avoid at the edge of each square
  28178. const absV = abs( v );
  28179. // Intersect unit cube
  28180. const scaleToCube = div( 1.0, max$1( absV.x, max$1( absV.y, absV.z ) ) );
  28181. absV.mulAssign( scaleToCube );
  28182. // Apply scale to avoid seams
  28183. // two texels less per square (one texel will do for NEAREST)
  28184. v.mulAssign( scaleToCube.mul( texelSizeY.mul( 2 ).oneMinus() ) );
  28185. // Unwrap
  28186. // space: -1 ... 1 range for each square
  28187. //
  28188. // #X## dim := ( 4 , 2 )
  28189. // # # center := ( 1 , 1 )
  28190. const planar = vec2( v.xy ).toVar();
  28191. const almostATexel = texelSizeY.mul( 1.5 );
  28192. const almostOne = almostATexel.oneMinus();
  28193. If( absV.z.greaterThanEqual( almostOne ), () => {
  28194. If( v.z.greaterThan( 0.0 ), () => {
  28195. planar.x.assign( sub( 4.0, v.x ) );
  28196. } );
  28197. } ).ElseIf( absV.x.greaterThanEqual( almostOne ), () => {
  28198. const signX = sign( v.x );
  28199. planar.x.assign( v.z.mul( signX ).add( signX.mul( 2.0 ) ) );
  28200. } ).ElseIf( absV.y.greaterThanEqual( almostOne ), () => {
  28201. const signY = sign( v.y );
  28202. planar.x.assign( v.x.add( signY.mul( 2.0 ) ).add( 2.0 ) );
  28203. planar.y.assign( v.z.mul( signY ).sub( 2.0 ) );
  28204. } );
  28205. // Transform to UV space
  28206. // scale := 0.5 / dim
  28207. // translate := ( center + 0.5 ) / dim
  28208. return vec2( 0.125, 0.25 ).mul( planar ).add( vec2( 0.375, 0.75 ) ).flipY();
  28209. } ).setLayout( {
  28210. name: 'cubeToUV',
  28211. type: 'vec2',
  28212. inputs: [
  28213. { name: 'pos', type: 'vec3' },
  28214. { name: 'texelSizeY', type: 'float' }
  28215. ]
  28216. } );
  28217. const BasicPointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize } ) => {
  28218. return texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp );
  28219. } );
  28220. const PointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize, shadow } ) => {
  28221. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  28222. const offset = vec2( -1, 1.0 ).mul( radius ).mul( texelSize.y );
  28223. return texture( depthTexture, cubeToUV( bd3D.add( offset.xyy ), texelSize.y ) ).compare( dp )
  28224. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyy ), texelSize.y ) ).compare( dp ) )
  28225. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xyx ), texelSize.y ) ).compare( dp ) )
  28226. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyx ), texelSize.y ) ).compare( dp ) )
  28227. .add( texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp ) )
  28228. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxy ), texelSize.y ) ).compare( dp ) )
  28229. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxy ), texelSize.y ) ).compare( dp ) )
  28230. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxx ), texelSize.y ) ).compare( dp ) )
  28231. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxx ), texelSize.y ) ).compare( dp ) )
  28232. .mul( 1.0 / 9.0 );
  28233. } );
  28234. const pointShadowFilter = /*@__PURE__*/ Fn( ( { filterFn, depthTexture, shadowCoord, shadow } ) => {
  28235. // for point lights, the uniform @vShadowCoord is re-purposed to hold
  28236. // the vector from the light to the world-space position of the fragment.
  28237. const lightToPosition = shadowCoord.xyz.toVar();
  28238. const lightToPositionLength = lightToPosition.length();
  28239. const cameraNearLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.near );
  28240. const cameraFarLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.far );
  28241. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  28242. const mapSize = uniform( shadow.mapSize ).setGroup( renderGroup );
  28243. const result = float( 1.0 ).toVar();
  28244. If( lightToPositionLength.sub( cameraFarLocal ).lessThanEqual( 0.0 ).and( lightToPositionLength.sub( cameraNearLocal ).greaterThanEqual( 0.0 ) ), () => {
  28245. // dp = normalized distance from light to fragment position
  28246. const dp = lightToPositionLength.sub( cameraNearLocal ).div( cameraFarLocal.sub( cameraNearLocal ) ).toVar(); // need to clamp?
  28247. dp.addAssign( bias );
  28248. // bd3D = base direction 3D
  28249. const bd3D = lightToPosition.normalize();
  28250. const texelSize = vec2( 1.0 ).div( mapSize.mul( vec2( 4.0, 2.0 ) ) );
  28251. // percentage-closer filtering
  28252. result.assign( filterFn( { depthTexture, bd3D, dp, texelSize, shadow } ) );
  28253. } );
  28254. return result;
  28255. } );
  28256. const _viewport = /*@__PURE__*/ new Vector4();
  28257. const _viewportSize = /*@__PURE__*/ new Vector2();
  28258. const _shadowMapSize = /*@__PURE__*/ new Vector2();
  28259. /**
  28260. * Represents the shadow implementation for point light nodes.
  28261. *
  28262. * @augments ShadowNode
  28263. */
  28264. class PointShadowNode extends ShadowNode {
  28265. static get type() {
  28266. return 'PointShadowNode';
  28267. }
  28268. /**
  28269. * Constructs a new point shadow node.
  28270. *
  28271. * @param {PointLight} light - The shadow casting point light.
  28272. * @param {?PointLightShadow} [shadow=null] - An optional point light shadow.
  28273. */
  28274. constructor( light, shadow = null ) {
  28275. super( light, shadow );
  28276. }
  28277. /**
  28278. * Overwrites the default implementation to return point light shadow specific
  28279. * filtering functions.
  28280. *
  28281. * @param {number} type - The shadow type.
  28282. * @return {Function} The filtering function.
  28283. */
  28284. getShadowFilterFn( type ) {
  28285. return type === BasicShadowMap ? BasicPointShadowFilter : PointShadowFilter;
  28286. }
  28287. /**
  28288. * Overwrites the default implementation so the unaltered shadow position is used.
  28289. *
  28290. * @param {NodeBuilder} builder - A reference to the current node builder.
  28291. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  28292. * @return {Node<vec3>} The shadow coordinates.
  28293. */
  28294. setupShadowCoord( builder, shadowPosition ) {
  28295. return shadowPosition;
  28296. }
  28297. /**
  28298. * Overwrites the default implementation to only use point light specific
  28299. * shadow filter functions.
  28300. *
  28301. * @param {NodeBuilder} builder - A reference to the current node builder.
  28302. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  28303. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  28304. * @param {Texture} inputs.shadowTexture - A reference to the shadow map's texture.
  28305. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  28306. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  28307. * @param {LightShadow} inputs.shadow - The light shadow.
  28308. * @return {Node<float>} The result node of the shadow filtering.
  28309. */
  28310. setupShadowFilter( builder, { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } ) {
  28311. return pointShadowFilter( { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } );
  28312. }
  28313. /**
  28314. * Overwrites the default implementation with point light specific
  28315. * rendering code.
  28316. *
  28317. * @param {NodeFrame} frame - A reference to the current node frame.
  28318. */
  28319. renderShadow( frame ) {
  28320. const { shadow, shadowMap, light } = this;
  28321. const { renderer, scene } = frame;
  28322. const shadowFrameExtents = shadow.getFrameExtents();
  28323. _shadowMapSize.copy( shadow.mapSize );
  28324. _shadowMapSize.multiply( shadowFrameExtents );
  28325. shadowMap.setSize( _shadowMapSize.width, _shadowMapSize.height );
  28326. _viewportSize.copy( shadow.mapSize );
  28327. //
  28328. const previousAutoClear = renderer.autoClear;
  28329. const previousClearColor = renderer.getClearColor( _clearColor$1 );
  28330. const previousClearAlpha = renderer.getClearAlpha();
  28331. renderer.autoClear = false;
  28332. renderer.setClearColor( shadow.clearColor, shadow.clearAlpha );
  28333. renderer.clear();
  28334. const viewportCount = shadow.getViewportCount();
  28335. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  28336. const viewport = shadow.getViewport( vp );
  28337. const x = _viewportSize.x * viewport.x;
  28338. const y = _shadowMapSize.y - _viewportSize.y - ( _viewportSize.y * viewport.y );
  28339. _viewport.set(
  28340. x,
  28341. y,
  28342. _viewportSize.x * viewport.z,
  28343. _viewportSize.y * viewport.w
  28344. );
  28345. shadowMap.viewport.copy( _viewport );
  28346. shadow.updateMatrices( light, vp );
  28347. renderer.render( scene, shadow.camera );
  28348. }
  28349. //
  28350. renderer.autoClear = previousAutoClear;
  28351. renderer.setClearColor( previousClearColor, previousClearAlpha );
  28352. }
  28353. }
  28354. /**
  28355. * TSL function for creating an instance of `PointShadowNode`.
  28356. *
  28357. * @tsl
  28358. * @function
  28359. * @param {PointLight} light - The shadow casting point light.
  28360. * @param {?PointLightShadow} [shadow=null] - An optional point light shadow.
  28361. * @return {PointShadowNode} The created point shadow node.
  28362. */
  28363. const pointShadow = ( light, shadow ) => nodeObject( new PointShadowNode( light, shadow ) );
  28364. /**
  28365. * Base class for analytic light nodes.
  28366. *
  28367. * @augments LightingNode
  28368. */
  28369. class AnalyticLightNode extends LightingNode {
  28370. static get type() {
  28371. return 'AnalyticLightNode';
  28372. }
  28373. /**
  28374. * Constructs a new analytic light node.
  28375. *
  28376. * @param {?Light} [light=null] - The light source.
  28377. */
  28378. constructor( light = null ) {
  28379. super();
  28380. /**
  28381. * The light source.
  28382. *
  28383. * @type {?Light}
  28384. * @default null
  28385. */
  28386. this.light = light;
  28387. /**
  28388. * The light's color value.
  28389. *
  28390. * @type {Color}
  28391. */
  28392. this.color = new Color();
  28393. /**
  28394. * The light's color node. Points to `colorNode` of the light source, if set. Otherwise
  28395. * it creates a uniform node based on {@link AnalyticLightNode#color}.
  28396. *
  28397. * @type {Node}
  28398. */
  28399. this.colorNode = ( light && light.colorNode ) || uniform( this.color ).setGroup( renderGroup );
  28400. /**
  28401. * This property is used to retain a reference to the original value of {@link AnalyticLightNode#colorNode}.
  28402. * The final color node is represented by a different node when using shadows.
  28403. *
  28404. * @type {?Node}
  28405. * @default null
  28406. */
  28407. this.baseColorNode = null;
  28408. /**
  28409. * Represents the light's shadow.
  28410. *
  28411. * @type {?ShadowNode}
  28412. * @default null
  28413. */
  28414. this.shadowNode = null;
  28415. /**
  28416. * Represents the light's shadow color.
  28417. *
  28418. * @type {?Node}
  28419. * @default null
  28420. */
  28421. this.shadowColorNode = null;
  28422. /**
  28423. * This flag can be used for type testing.
  28424. *
  28425. * @type {boolean}
  28426. * @readonly
  28427. * @default true
  28428. */
  28429. this.isAnalyticLightNode = true;
  28430. /**
  28431. * Overwritten since analytic light nodes are updated
  28432. * once per frame.
  28433. *
  28434. * @type {string}
  28435. * @default 'frame'
  28436. */
  28437. this.updateType = NodeUpdateType.FRAME;
  28438. }
  28439. getHash() {
  28440. return this.light.uuid;
  28441. }
  28442. /**
  28443. * Returns a node representing a direction vector which points from the current
  28444. * position in view space to the light's position in view space.
  28445. *
  28446. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  28447. * @return {Node<vec3>} The light vector node.
  28448. */
  28449. getLightVector( builder ) {
  28450. return lightViewPosition( this.light ).sub( builder.context.positionView || positionView );
  28451. }
  28452. /**
  28453. * Sets up the direct lighting for the analytic light node.
  28454. *
  28455. * @abstract
  28456. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  28457. * @return {Object|undefined} The direct light data (color and direction).
  28458. */
  28459. setupDirect( /*builder*/ ) { }
  28460. /**
  28461. * Sets up the direct rect area lighting for the analytic light node.
  28462. *
  28463. * @abstract
  28464. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  28465. * @return {Object|undefined} The direct rect area light data.
  28466. */
  28467. setupDirectRectArea( /*builder*/ ) { }
  28468. /**
  28469. * Setups the shadow node for this light. The method exists so concrete light classes
  28470. * can setup different types of shadow nodes.
  28471. *
  28472. * @return {ShadowNode} The created shadow node.
  28473. */
  28474. setupShadowNode() {
  28475. return shadow( this.light );
  28476. }
  28477. /**
  28478. * Setups the shadow for this light. This method is only executed if the light
  28479. * cast shadows and the current build object receives shadows. It incorporates
  28480. * shadows into the lighting computation.
  28481. *
  28482. * @param {NodeBuilder} builder - The current node builder.
  28483. */
  28484. setupShadow( builder ) {
  28485. const { renderer } = builder;
  28486. if ( renderer.shadowMap.enabled === false ) return;
  28487. let shadowColorNode = this.shadowColorNode;
  28488. if ( shadowColorNode === null ) {
  28489. const customShadowNode = this.light.shadow.shadowNode;
  28490. let shadowNode;
  28491. if ( customShadowNode !== undefined ) {
  28492. shadowNode = nodeObject( customShadowNode );
  28493. } else {
  28494. shadowNode = this.setupShadowNode();
  28495. }
  28496. this.shadowNode = shadowNode;
  28497. this.shadowColorNode = shadowColorNode = this.colorNode.mul( shadowNode );
  28498. this.baseColorNode = this.colorNode;
  28499. }
  28500. //
  28501. this.colorNode = shadowColorNode;
  28502. }
  28503. /**
  28504. * Unlike most other nodes, lighting nodes do not return a output node in {@link Node#setup}.
  28505. * The main purpose of lighting nodes is to configure the current {@link LightingModel} and/or
  28506. * invocate the respective interface methods.
  28507. *
  28508. * @param {NodeBuilder} builder - The current node builder.
  28509. */
  28510. setup( builder ) {
  28511. this.colorNode = this.baseColorNode || this.colorNode;
  28512. if ( this.light.castShadow ) {
  28513. if ( builder.object.receiveShadow ) {
  28514. this.setupShadow( builder );
  28515. }
  28516. } else if ( this.shadowNode !== null ) {
  28517. this.shadowNode.dispose();
  28518. this.shadowNode = null;
  28519. this.shadowColorNode = null;
  28520. }
  28521. const directLightData = this.setupDirect( builder );
  28522. const directRectAreaLightData = this.setupDirectRectArea( builder );
  28523. if ( directLightData ) {
  28524. builder.lightsNode.setupDirectLight( builder, this, directLightData );
  28525. }
  28526. if ( directRectAreaLightData ) {
  28527. builder.lightsNode.setupDirectRectAreaLight( builder, this, directRectAreaLightData );
  28528. }
  28529. }
  28530. /**
  28531. * The update method is used to update light uniforms per frame.
  28532. * Potentially overwritten in concrete light nodes to update light
  28533. * specific uniforms.
  28534. *
  28535. * @param {NodeFrame} frame - A reference to the current node frame.
  28536. */
  28537. update( /*frame*/ ) {
  28538. const { light } = this;
  28539. this.color.copy( light.color ).multiplyScalar( light.intensity );
  28540. }
  28541. }
  28542. /**
  28543. * Represents a `discard` shader operation in TSL.
  28544. *
  28545. * @method
  28546. * @param {Object} inputs - The input parameter object.
  28547. * @param {Node<float>} inputs.lightDistance - The distance of the light's position to the current fragment position.
  28548. * @param {Node<float>} inputs.cutoffDistance - The light's cutoff distance.
  28549. * @param {Node<float>} inputs.decayExponent - The light's decay exponent.
  28550. * @return {Node<float>} The distance falloff.
  28551. */
  28552. const getDistanceAttenuation = /*@__PURE__*/ Fn( ( { lightDistance, cutoffDistance, decayExponent } ) => {
  28553. // based upon Frostbite 3 Moving to Physically-based Rendering
  28554. // page 32, equation 26: E[window1]
  28555. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  28556. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  28557. return cutoffDistance.greaterThan( 0 ).select(
  28558. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  28559. distanceFalloff
  28560. );
  28561. } ); // validated
  28562. const directPointLight = ( { color, lightVector, cutoffDistance, decayExponent } ) => {
  28563. const lightDirection = lightVector.normalize();
  28564. const lightDistance = lightVector.length();
  28565. const attenuation = getDistanceAttenuation( {
  28566. lightDistance,
  28567. cutoffDistance,
  28568. decayExponent
  28569. } );
  28570. const lightColor = color.mul( attenuation );
  28571. return { lightDirection, lightColor };
  28572. };
  28573. /**
  28574. * Module for representing point lights as nodes.
  28575. *
  28576. * @augments AnalyticLightNode
  28577. */
  28578. class PointLightNode extends AnalyticLightNode {
  28579. static get type() {
  28580. return 'PointLightNode';
  28581. }
  28582. /**
  28583. * Constructs a new point light node.
  28584. *
  28585. * @param {?PointLight} [light=null] - The point light source.
  28586. */
  28587. constructor( light = null ) {
  28588. super( light );
  28589. /**
  28590. * Uniform node representing the cutoff distance.
  28591. *
  28592. * @type {UniformNode<float>}
  28593. */
  28594. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  28595. /**
  28596. * Uniform node representing the decay exponent.
  28597. *
  28598. * @type {UniformNode<float>}
  28599. */
  28600. this.decayExponentNode = uniform( 2 ).setGroup( renderGroup );
  28601. }
  28602. /**
  28603. * Overwritten to updated point light specific uniforms.
  28604. *
  28605. * @param {NodeFrame} frame - A reference to the current node frame.
  28606. */
  28607. update( frame ) {
  28608. const { light } = this;
  28609. super.update( frame );
  28610. this.cutoffDistanceNode.value = light.distance;
  28611. this.decayExponentNode.value = light.decay;
  28612. }
  28613. /**
  28614. * Overwritten to setup point light specific shadow.
  28615. *
  28616. * @return {PointShadowNode}
  28617. */
  28618. setupShadowNode() {
  28619. return pointShadow( this.light );
  28620. }
  28621. setupDirect( builder ) {
  28622. return directPointLight( {
  28623. color: this.colorNode,
  28624. lightVector: this.getLightVector( builder ),
  28625. cutoffDistance: this.cutoffDistanceNode,
  28626. decayExponent: this.decayExponentNode
  28627. } );
  28628. }
  28629. }
  28630. /**
  28631. * Creates a 2x2 checkerboard pattern that can be used as procedural texture data.
  28632. *
  28633. * @tsl
  28634. * @function
  28635. * @param {Node<vec2>} coord - The uv coordinates.
  28636. * @return {Node<float>} The result data.
  28637. */
  28638. const checker = /*@__PURE__*/ Fn( ( [ coord = uv() ] ) => {
  28639. const uv = coord.mul( 2.0 );
  28640. const cx = uv.x.floor();
  28641. const cy = uv.y.floor();
  28642. const result = cx.add( cy ).mod( 2.0 );
  28643. return result.sign();
  28644. } );
  28645. /**
  28646. * Generates a circle based on the uv coordinates.
  28647. *
  28648. * @tsl
  28649. * @function
  28650. * @param {Node<vec2>} coord - The uv to generate the circle.
  28651. * @return {Node<float>} The circle shape.
  28652. */
  28653. const shapeCircle = Fn( ( [ coord = uv() ], { renderer, material } ) => {
  28654. const len2 = lengthSq( coord.mul( 2 ).sub( 1 ) );
  28655. let alpha;
  28656. if ( material.alphaToCoverage && renderer.samples > 1 ) {
  28657. const dlen = float( len2.fwidth() ).toVar();
  28658. alpha = smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus();
  28659. } else {
  28660. alpha = select( len2.greaterThan( 1.0 ), 0, 1 );
  28661. }
  28662. return alpha;
  28663. } );
  28664. // Three.js Transpiler
  28665. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  28666. const mx_select = /*@__PURE__*/ Fn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  28667. const f = float( f_immutable ).toVar();
  28668. const t = float( t_immutable ).toVar();
  28669. const b = bool( b_immutable ).toVar();
  28670. return select( b, t, f );
  28671. } ).setLayout( {
  28672. name: 'mx_select',
  28673. type: 'float',
  28674. inputs: [
  28675. { name: 'b', type: 'bool' },
  28676. { name: 't', type: 'float' },
  28677. { name: 'f', type: 'float' }
  28678. ]
  28679. } );
  28680. const mx_negate_if = /*@__PURE__*/ Fn( ( [ val_immutable, b_immutable ] ) => {
  28681. const b = bool( b_immutable ).toVar();
  28682. const val = float( val_immutable ).toVar();
  28683. return select( b, val.negate(), val );
  28684. } ).setLayout( {
  28685. name: 'mx_negate_if',
  28686. type: 'float',
  28687. inputs: [
  28688. { name: 'val', type: 'float' },
  28689. { name: 'b', type: 'bool' }
  28690. ]
  28691. } );
  28692. const mx_floor = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  28693. const x = float( x_immutable ).toVar();
  28694. return int( floor( x ) );
  28695. } ).setLayout( {
  28696. name: 'mx_floor',
  28697. type: 'int',
  28698. inputs: [
  28699. { name: 'x', type: 'float' }
  28700. ]
  28701. } );
  28702. const mx_floorfrac = /*@__PURE__*/ Fn( ( [ x_immutable, i ] ) => {
  28703. const x = float( x_immutable ).toVar();
  28704. i.assign( mx_floor( x ) );
  28705. return x.sub( float( i ) );
  28706. } );
  28707. const mx_bilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  28708. const t = float( t_immutable ).toVar();
  28709. const s = float( s_immutable ).toVar();
  28710. const v3 = float( v3_immutable ).toVar();
  28711. const v2 = float( v2_immutable ).toVar();
  28712. const v1 = float( v1_immutable ).toVar();
  28713. const v0 = float( v0_immutable ).toVar();
  28714. const s1 = float( sub( 1.0, s ) ).toVar();
  28715. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  28716. } ).setLayout( {
  28717. name: 'mx_bilerp_0',
  28718. type: 'float',
  28719. inputs: [
  28720. { name: 'v0', type: 'float' },
  28721. { name: 'v1', type: 'float' },
  28722. { name: 'v2', type: 'float' },
  28723. { name: 'v3', type: 'float' },
  28724. { name: 's', type: 'float' },
  28725. { name: 't', type: 'float' }
  28726. ]
  28727. } );
  28728. const mx_bilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  28729. const t = float( t_immutable ).toVar();
  28730. const s = float( s_immutable ).toVar();
  28731. const v3 = vec3( v3_immutable ).toVar();
  28732. const v2 = vec3( v2_immutable ).toVar();
  28733. const v1 = vec3( v1_immutable ).toVar();
  28734. const v0 = vec3( v0_immutable ).toVar();
  28735. const s1 = float( sub( 1.0, s ) ).toVar();
  28736. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  28737. } ).setLayout( {
  28738. name: 'mx_bilerp_1',
  28739. type: 'vec3',
  28740. inputs: [
  28741. { name: 'v0', type: 'vec3' },
  28742. { name: 'v1', type: 'vec3' },
  28743. { name: 'v2', type: 'vec3' },
  28744. { name: 'v3', type: 'vec3' },
  28745. { name: 's', type: 'float' },
  28746. { name: 't', type: 'float' }
  28747. ]
  28748. } );
  28749. const mx_bilerp = /*@__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  28750. 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 ] ) => {
  28751. const r = float( r_immutable ).toVar();
  28752. const t = float( t_immutable ).toVar();
  28753. const s = float( s_immutable ).toVar();
  28754. const v7 = float( v7_immutable ).toVar();
  28755. const v6 = float( v6_immutable ).toVar();
  28756. const v5 = float( v5_immutable ).toVar();
  28757. const v4 = float( v4_immutable ).toVar();
  28758. const v3 = float( v3_immutable ).toVar();
  28759. const v2 = float( v2_immutable ).toVar();
  28760. const v1 = float( v1_immutable ).toVar();
  28761. const v0 = float( v0_immutable ).toVar();
  28762. const s1 = float( sub( 1.0, s ) ).toVar();
  28763. const t1 = float( sub( 1.0, t ) ).toVar();
  28764. const r1 = float( sub( 1.0, r ) ).toVar();
  28765. 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 ) ) ) ) ) );
  28766. } ).setLayout( {
  28767. name: 'mx_trilerp_0',
  28768. type: 'float',
  28769. inputs: [
  28770. { name: 'v0', type: 'float' },
  28771. { name: 'v1', type: 'float' },
  28772. { name: 'v2', type: 'float' },
  28773. { name: 'v3', type: 'float' },
  28774. { name: 'v4', type: 'float' },
  28775. { name: 'v5', type: 'float' },
  28776. { name: 'v6', type: 'float' },
  28777. { name: 'v7', type: 'float' },
  28778. { name: 's', type: 'float' },
  28779. { name: 't', type: 'float' },
  28780. { name: 'r', type: 'float' }
  28781. ]
  28782. } );
  28783. 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 ] ) => {
  28784. const r = float( r_immutable ).toVar();
  28785. const t = float( t_immutable ).toVar();
  28786. const s = float( s_immutable ).toVar();
  28787. const v7 = vec3( v7_immutable ).toVar();
  28788. const v6 = vec3( v6_immutable ).toVar();
  28789. const v5 = vec3( v5_immutable ).toVar();
  28790. const v4 = vec3( v4_immutable ).toVar();
  28791. const v3 = vec3( v3_immutable ).toVar();
  28792. const v2 = vec3( v2_immutable ).toVar();
  28793. const v1 = vec3( v1_immutable ).toVar();
  28794. const v0 = vec3( v0_immutable ).toVar();
  28795. const s1 = float( sub( 1.0, s ) ).toVar();
  28796. const t1 = float( sub( 1.0, t ) ).toVar();
  28797. const r1 = float( sub( 1.0, r ) ).toVar();
  28798. 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 ) ) ) ) ) );
  28799. } ).setLayout( {
  28800. name: 'mx_trilerp_1',
  28801. type: 'vec3',
  28802. inputs: [
  28803. { name: 'v0', type: 'vec3' },
  28804. { name: 'v1', type: 'vec3' },
  28805. { name: 'v2', type: 'vec3' },
  28806. { name: 'v3', type: 'vec3' },
  28807. { name: 'v4', type: 'vec3' },
  28808. { name: 'v5', type: 'vec3' },
  28809. { name: 'v6', type: 'vec3' },
  28810. { name: 'v7', type: 'vec3' },
  28811. { name: 's', type: 'float' },
  28812. { name: 't', type: 'float' },
  28813. { name: 'r', type: 'float' }
  28814. ]
  28815. } );
  28816. const mx_trilerp = /*@__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  28817. const mx_gradient_float_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  28818. const y = float( y_immutable ).toVar();
  28819. const x = float( x_immutable ).toVar();
  28820. const hash = uint( hash_immutable ).toVar();
  28821. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  28822. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  28823. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  28824. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  28825. } ).setLayout( {
  28826. name: 'mx_gradient_float_0',
  28827. type: 'float',
  28828. inputs: [
  28829. { name: 'hash', type: 'uint' },
  28830. { name: 'x', type: 'float' },
  28831. { name: 'y', type: 'float' }
  28832. ]
  28833. } );
  28834. const mx_gradient_float_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  28835. const z = float( z_immutable ).toVar();
  28836. const y = float( y_immutable ).toVar();
  28837. const x = float( x_immutable ).toVar();
  28838. const hash = uint( hash_immutable ).toVar();
  28839. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  28840. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  28841. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  28842. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  28843. } ).setLayout( {
  28844. name: 'mx_gradient_float_1',
  28845. type: 'float',
  28846. inputs: [
  28847. { name: 'hash', type: 'uint' },
  28848. { name: 'x', type: 'float' },
  28849. { name: 'y', type: 'float' },
  28850. { name: 'z', type: 'float' }
  28851. ]
  28852. } );
  28853. const mx_gradient_float = /*@__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  28854. const mx_gradient_vec3_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  28855. const y = float( y_immutable ).toVar();
  28856. const x = float( x_immutable ).toVar();
  28857. const hash = uvec3( hash_immutable ).toVar();
  28858. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  28859. } ).setLayout( {
  28860. name: 'mx_gradient_vec3_0',
  28861. type: 'vec3',
  28862. inputs: [
  28863. { name: 'hash', type: 'uvec3' },
  28864. { name: 'x', type: 'float' },
  28865. { name: 'y', type: 'float' }
  28866. ]
  28867. } );
  28868. const mx_gradient_vec3_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  28869. const z = float( z_immutable ).toVar();
  28870. const y = float( y_immutable ).toVar();
  28871. const x = float( x_immutable ).toVar();
  28872. const hash = uvec3( hash_immutable ).toVar();
  28873. 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 ) );
  28874. } ).setLayout( {
  28875. name: 'mx_gradient_vec3_1',
  28876. type: 'vec3',
  28877. inputs: [
  28878. { name: 'hash', type: 'uvec3' },
  28879. { name: 'x', type: 'float' },
  28880. { name: 'y', type: 'float' },
  28881. { name: 'z', type: 'float' }
  28882. ]
  28883. } );
  28884. const mx_gradient_vec3 = /*@__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  28885. const mx_gradient_scale2d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  28886. const v = float( v_immutable ).toVar();
  28887. return mul( 0.6616, v );
  28888. } ).setLayout( {
  28889. name: 'mx_gradient_scale2d_0',
  28890. type: 'float',
  28891. inputs: [
  28892. { name: 'v', type: 'float' }
  28893. ]
  28894. } );
  28895. const mx_gradient_scale3d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  28896. const v = float( v_immutable ).toVar();
  28897. return mul( 0.9820, v );
  28898. } ).setLayout( {
  28899. name: 'mx_gradient_scale3d_0',
  28900. type: 'float',
  28901. inputs: [
  28902. { name: 'v', type: 'float' }
  28903. ]
  28904. } );
  28905. const mx_gradient_scale2d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  28906. const v = vec3( v_immutable ).toVar();
  28907. return mul( 0.6616, v );
  28908. } ).setLayout( {
  28909. name: 'mx_gradient_scale2d_1',
  28910. type: 'vec3',
  28911. inputs: [
  28912. { name: 'v', type: 'vec3' }
  28913. ]
  28914. } );
  28915. const mx_gradient_scale2d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  28916. const mx_gradient_scale3d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  28917. const v = vec3( v_immutable ).toVar();
  28918. return mul( 0.9820, v );
  28919. } ).setLayout( {
  28920. name: 'mx_gradient_scale3d_1',
  28921. type: 'vec3',
  28922. inputs: [
  28923. { name: 'v', type: 'vec3' }
  28924. ]
  28925. } );
  28926. const mx_gradient_scale3d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  28927. const mx_rotl32 = /*@__PURE__*/ Fn( ( [ x_immutable, k_immutable ] ) => {
  28928. const k = int( k_immutable ).toVar();
  28929. const x = uint( x_immutable ).toVar();
  28930. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  28931. } ).setLayout( {
  28932. name: 'mx_rotl32',
  28933. type: 'uint',
  28934. inputs: [
  28935. { name: 'x', type: 'uint' },
  28936. { name: 'k', type: 'int' }
  28937. ]
  28938. } );
  28939. const mx_bjmix = /*@__PURE__*/ Fn( ( [ a, b, c ] ) => {
  28940. a.subAssign( c );
  28941. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  28942. c.addAssign( b );
  28943. b.subAssign( a );
  28944. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  28945. a.addAssign( c );
  28946. c.subAssign( b );
  28947. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  28948. b.addAssign( a );
  28949. a.subAssign( c );
  28950. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  28951. c.addAssign( b );
  28952. b.subAssign( a );
  28953. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  28954. a.addAssign( c );
  28955. c.subAssign( b );
  28956. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  28957. b.addAssign( a );
  28958. } );
  28959. const mx_bjfinal = /*@__PURE__*/ Fn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  28960. const c = uint( c_immutable ).toVar();
  28961. const b = uint( b_immutable ).toVar();
  28962. const a = uint( a_immutable ).toVar();
  28963. c.bitXorAssign( b );
  28964. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  28965. a.bitXorAssign( c );
  28966. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  28967. b.bitXorAssign( a );
  28968. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  28969. c.bitXorAssign( b );
  28970. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  28971. a.bitXorAssign( c );
  28972. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  28973. b.bitXorAssign( a );
  28974. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  28975. c.bitXorAssign( b );
  28976. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  28977. return c;
  28978. } ).setLayout( {
  28979. name: 'mx_bjfinal',
  28980. type: 'uint',
  28981. inputs: [
  28982. { name: 'a', type: 'uint' },
  28983. { name: 'b', type: 'uint' },
  28984. { name: 'c', type: 'uint' }
  28985. ]
  28986. } );
  28987. const mx_bits_to_01 = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  28988. const bits = uint( bits_immutable ).toVar();
  28989. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  28990. } ).setLayout( {
  28991. name: 'mx_bits_to_01',
  28992. type: 'float',
  28993. inputs: [
  28994. { name: 'bits', type: 'uint' }
  28995. ]
  28996. } );
  28997. const mx_fade = /*@__PURE__*/ Fn( ( [ t_immutable ] ) => {
  28998. const t = float( t_immutable ).toVar();
  28999. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  29000. } ).setLayout( {
  29001. name: 'mx_fade',
  29002. type: 'float',
  29003. inputs: [
  29004. { name: 't', type: 'float' }
  29005. ]
  29006. } );
  29007. const mx_hash_int_0 = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  29008. const x = int( x_immutable ).toVar();
  29009. const len = uint( uint( 1 ) ).toVar();
  29010. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  29011. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  29012. } ).setLayout( {
  29013. name: 'mx_hash_int_0',
  29014. type: 'uint',
  29015. inputs: [
  29016. { name: 'x', type: 'int' }
  29017. ]
  29018. } );
  29019. const mx_hash_int_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  29020. const y = int( y_immutable ).toVar();
  29021. const x = int( x_immutable ).toVar();
  29022. const len = uint( uint( 2 ) ).toVar();
  29023. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  29024. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  29025. a.addAssign( uint( x ) );
  29026. b.addAssign( uint( y ) );
  29027. return mx_bjfinal( a, b, c );
  29028. } ).setLayout( {
  29029. name: 'mx_hash_int_1',
  29030. type: 'uint',
  29031. inputs: [
  29032. { name: 'x', type: 'int' },
  29033. { name: 'y', type: 'int' }
  29034. ]
  29035. } );
  29036. const mx_hash_int_2 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  29037. const z = int( z_immutable ).toVar();
  29038. const y = int( y_immutable ).toVar();
  29039. const x = int( x_immutable ).toVar();
  29040. const len = uint( uint( 3 ) ).toVar();
  29041. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  29042. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  29043. a.addAssign( uint( x ) );
  29044. b.addAssign( uint( y ) );
  29045. c.addAssign( uint( z ) );
  29046. return mx_bjfinal( a, b, c );
  29047. } ).setLayout( {
  29048. name: 'mx_hash_int_2',
  29049. type: 'uint',
  29050. inputs: [
  29051. { name: 'x', type: 'int' },
  29052. { name: 'y', type: 'int' },
  29053. { name: 'z', type: 'int' }
  29054. ]
  29055. } );
  29056. const mx_hash_int_3 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  29057. const xx = int( xx_immutable ).toVar();
  29058. const z = int( z_immutable ).toVar();
  29059. const y = int( y_immutable ).toVar();
  29060. const x = int( x_immutable ).toVar();
  29061. const len = uint( uint( 4 ) ).toVar();
  29062. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  29063. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  29064. a.addAssign( uint( x ) );
  29065. b.addAssign( uint( y ) );
  29066. c.addAssign( uint( z ) );
  29067. mx_bjmix( a, b, c );
  29068. a.addAssign( uint( xx ) );
  29069. return mx_bjfinal( a, b, c );
  29070. } ).setLayout( {
  29071. name: 'mx_hash_int_3',
  29072. type: 'uint',
  29073. inputs: [
  29074. { name: 'x', type: 'int' },
  29075. { name: 'y', type: 'int' },
  29076. { name: 'z', type: 'int' },
  29077. { name: 'xx', type: 'int' }
  29078. ]
  29079. } );
  29080. const mx_hash_int_4 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  29081. const yy = int( yy_immutable ).toVar();
  29082. const xx = int( xx_immutable ).toVar();
  29083. const z = int( z_immutable ).toVar();
  29084. const y = int( y_immutable ).toVar();
  29085. const x = int( x_immutable ).toVar();
  29086. const len = uint( uint( 5 ) ).toVar();
  29087. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  29088. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  29089. a.addAssign( uint( x ) );
  29090. b.addAssign( uint( y ) );
  29091. c.addAssign( uint( z ) );
  29092. mx_bjmix( a, b, c );
  29093. a.addAssign( uint( xx ) );
  29094. b.addAssign( uint( yy ) );
  29095. return mx_bjfinal( a, b, c );
  29096. } ).setLayout( {
  29097. name: 'mx_hash_int_4',
  29098. type: 'uint',
  29099. inputs: [
  29100. { name: 'x', type: 'int' },
  29101. { name: 'y', type: 'int' },
  29102. { name: 'z', type: 'int' },
  29103. { name: 'xx', type: 'int' },
  29104. { name: 'yy', type: 'int' }
  29105. ]
  29106. } );
  29107. 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 ] );
  29108. const mx_hash_vec3_0 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  29109. const y = int( y_immutable ).toVar();
  29110. const x = int( x_immutable ).toVar();
  29111. const h = uint( mx_hash_int( x, y ) ).toVar();
  29112. const result = uvec3().toVar();
  29113. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  29114. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  29115. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  29116. return result;
  29117. } ).setLayout( {
  29118. name: 'mx_hash_vec3_0',
  29119. type: 'uvec3',
  29120. inputs: [
  29121. { name: 'x', type: 'int' },
  29122. { name: 'y', type: 'int' }
  29123. ]
  29124. } );
  29125. const mx_hash_vec3_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  29126. const z = int( z_immutable ).toVar();
  29127. const y = int( y_immutable ).toVar();
  29128. const x = int( x_immutable ).toVar();
  29129. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  29130. const result = uvec3().toVar();
  29131. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  29132. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  29133. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  29134. return result;
  29135. } ).setLayout( {
  29136. name: 'mx_hash_vec3_1',
  29137. type: 'uvec3',
  29138. inputs: [
  29139. { name: 'x', type: 'int' },
  29140. { name: 'y', type: 'int' },
  29141. { name: 'z', type: 'int' }
  29142. ]
  29143. } );
  29144. const mx_hash_vec3 = /*@__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  29145. const mx_perlin_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29146. const p = vec2( p_immutable ).toVar();
  29147. const X = int().toVar(), Y = int().toVar();
  29148. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  29149. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  29150. const u = float( mx_fade( fx ) ).toVar();
  29151. const v = float( mx_fade( fy ) ).toVar();
  29152. 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();
  29153. return mx_gradient_scale2d( result );
  29154. } ).setLayout( {
  29155. name: 'mx_perlin_noise_float_0',
  29156. type: 'float',
  29157. inputs: [
  29158. { name: 'p', type: 'vec2' }
  29159. ]
  29160. } );
  29161. const mx_perlin_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29162. const p = vec3( p_immutable ).toVar();
  29163. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  29164. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  29165. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  29166. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  29167. const u = float( mx_fade( fx ) ).toVar();
  29168. const v = float( mx_fade( fy ) ).toVar();
  29169. const w = float( mx_fade( fz ) ).toVar();
  29170. 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();
  29171. return mx_gradient_scale3d( result );
  29172. } ).setLayout( {
  29173. name: 'mx_perlin_noise_float_1',
  29174. type: 'float',
  29175. inputs: [
  29176. { name: 'p', type: 'vec3' }
  29177. ]
  29178. } );
  29179. const mx_perlin_noise_float = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  29180. const mx_perlin_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29181. const p = vec2( p_immutable ).toVar();
  29182. const X = int().toVar(), Y = int().toVar();
  29183. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  29184. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  29185. const u = float( mx_fade( fx ) ).toVar();
  29186. const v = float( mx_fade( fy ) ).toVar();
  29187. 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();
  29188. return mx_gradient_scale2d( result );
  29189. } ).setLayout( {
  29190. name: 'mx_perlin_noise_vec3_0',
  29191. type: 'vec3',
  29192. inputs: [
  29193. { name: 'p', type: 'vec2' }
  29194. ]
  29195. } );
  29196. const mx_perlin_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29197. const p = vec3( p_immutable ).toVar();
  29198. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  29199. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  29200. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  29201. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  29202. const u = float( mx_fade( fx ) ).toVar();
  29203. const v = float( mx_fade( fy ) ).toVar();
  29204. const w = float( mx_fade( fz ) ).toVar();
  29205. 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();
  29206. return mx_gradient_scale3d( result );
  29207. } ).setLayout( {
  29208. name: 'mx_perlin_noise_vec3_1',
  29209. type: 'vec3',
  29210. inputs: [
  29211. { name: 'p', type: 'vec3' }
  29212. ]
  29213. } );
  29214. const mx_perlin_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  29215. const mx_cell_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29216. const p = float( p_immutable ).toVar();
  29217. const ix = int( mx_floor( p ) ).toVar();
  29218. return mx_bits_to_01( mx_hash_int( ix ) );
  29219. } ).setLayout( {
  29220. name: 'mx_cell_noise_float_0',
  29221. type: 'float',
  29222. inputs: [
  29223. { name: 'p', type: 'float' }
  29224. ]
  29225. } );
  29226. const mx_cell_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29227. const p = vec2( p_immutable ).toVar();
  29228. const ix = int( mx_floor( p.x ) ).toVar();
  29229. const iy = int( mx_floor( p.y ) ).toVar();
  29230. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  29231. } ).setLayout( {
  29232. name: 'mx_cell_noise_float_1',
  29233. type: 'float',
  29234. inputs: [
  29235. { name: 'p', type: 'vec2' }
  29236. ]
  29237. } );
  29238. const mx_cell_noise_float_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29239. const p = vec3( p_immutable ).toVar();
  29240. const ix = int( mx_floor( p.x ) ).toVar();
  29241. const iy = int( mx_floor( p.y ) ).toVar();
  29242. const iz = int( mx_floor( p.z ) ).toVar();
  29243. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  29244. } ).setLayout( {
  29245. name: 'mx_cell_noise_float_2',
  29246. type: 'float',
  29247. inputs: [
  29248. { name: 'p', type: 'vec3' }
  29249. ]
  29250. } );
  29251. const mx_cell_noise_float_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29252. const p = vec4( p_immutable ).toVar();
  29253. const ix = int( mx_floor( p.x ) ).toVar();
  29254. const iy = int( mx_floor( p.y ) ).toVar();
  29255. const iz = int( mx_floor( p.z ) ).toVar();
  29256. const iw = int( mx_floor( p.w ) ).toVar();
  29257. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  29258. } ).setLayout( {
  29259. name: 'mx_cell_noise_float_3',
  29260. type: 'float',
  29261. inputs: [
  29262. { name: 'p', type: 'vec4' }
  29263. ]
  29264. } );
  29265. 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 ] );
  29266. const mx_cell_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29267. const p = float( p_immutable ).toVar();
  29268. const ix = int( mx_floor( p ) ).toVar();
  29269. 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 ) ) ) );
  29270. } ).setLayout( {
  29271. name: 'mx_cell_noise_vec3_0',
  29272. type: 'vec3',
  29273. inputs: [
  29274. { name: 'p', type: 'float' }
  29275. ]
  29276. } );
  29277. const mx_cell_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29278. const p = vec2( p_immutable ).toVar();
  29279. const ix = int( mx_floor( p.x ) ).toVar();
  29280. const iy = int( mx_floor( p.y ) ).toVar();
  29281. 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 ) ) ) );
  29282. } ).setLayout( {
  29283. name: 'mx_cell_noise_vec3_1',
  29284. type: 'vec3',
  29285. inputs: [
  29286. { name: 'p', type: 'vec2' }
  29287. ]
  29288. } );
  29289. const mx_cell_noise_vec3_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29290. const p = vec3( p_immutable ).toVar();
  29291. const ix = int( mx_floor( p.x ) ).toVar();
  29292. const iy = int( mx_floor( p.y ) ).toVar();
  29293. const iz = int( mx_floor( p.z ) ).toVar();
  29294. 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 ) ) ) );
  29295. } ).setLayout( {
  29296. name: 'mx_cell_noise_vec3_2',
  29297. type: 'vec3',
  29298. inputs: [
  29299. { name: 'p', type: 'vec3' }
  29300. ]
  29301. } );
  29302. const mx_cell_noise_vec3_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29303. const p = vec4( p_immutable ).toVar();
  29304. const ix = int( mx_floor( p.x ) ).toVar();
  29305. const iy = int( mx_floor( p.y ) ).toVar();
  29306. const iz = int( mx_floor( p.z ) ).toVar();
  29307. const iw = int( mx_floor( p.w ) ).toVar();
  29308. 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 ) ) ) );
  29309. } ).setLayout( {
  29310. name: 'mx_cell_noise_vec3_3',
  29311. type: 'vec3',
  29312. inputs: [
  29313. { name: 'p', type: 'vec4' }
  29314. ]
  29315. } );
  29316. 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 ] );
  29317. const mx_fractal_noise_float$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  29318. const diminish = float( diminish_immutable ).toVar();
  29319. const lacunarity = float( lacunarity_immutable ).toVar();
  29320. const octaves = int( octaves_immutable ).toVar();
  29321. const p = vec3( p_immutable ).toVar();
  29322. const result = float( 0.0 ).toVar();
  29323. const amplitude = float( 1.0 ).toVar();
  29324. Loop( octaves, () => {
  29325. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  29326. amplitude.mulAssign( diminish );
  29327. p.mulAssign( lacunarity );
  29328. } );
  29329. return result;
  29330. } ).setLayout( {
  29331. name: 'mx_fractal_noise_float',
  29332. type: 'float',
  29333. inputs: [
  29334. { name: 'p', type: 'vec3' },
  29335. { name: 'octaves', type: 'int' },
  29336. { name: 'lacunarity', type: 'float' },
  29337. { name: 'diminish', type: 'float' }
  29338. ]
  29339. } );
  29340. const mx_fractal_noise_vec3$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  29341. const diminish = float( diminish_immutable ).toVar();
  29342. const lacunarity = float( lacunarity_immutable ).toVar();
  29343. const octaves = int( octaves_immutable ).toVar();
  29344. const p = vec3( p_immutable ).toVar();
  29345. const result = vec3( 0.0 ).toVar();
  29346. const amplitude = float( 1.0 ).toVar();
  29347. Loop( octaves, () => {
  29348. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  29349. amplitude.mulAssign( diminish );
  29350. p.mulAssign( lacunarity );
  29351. } );
  29352. return result;
  29353. } ).setLayout( {
  29354. name: 'mx_fractal_noise_vec3',
  29355. type: 'vec3',
  29356. inputs: [
  29357. { name: 'p', type: 'vec3' },
  29358. { name: 'octaves', type: 'int' },
  29359. { name: 'lacunarity', type: 'float' },
  29360. { name: 'diminish', type: 'float' }
  29361. ]
  29362. } );
  29363. const mx_fractal_noise_vec2$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  29364. const diminish = float( diminish_immutable ).toVar();
  29365. const lacunarity = float( lacunarity_immutable ).toVar();
  29366. const octaves = int( octaves_immutable ).toVar();
  29367. const p = vec3( p_immutable ).toVar();
  29368. 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 ) );
  29369. } ).setLayout( {
  29370. name: 'mx_fractal_noise_vec2',
  29371. type: 'vec2',
  29372. inputs: [
  29373. { name: 'p', type: 'vec3' },
  29374. { name: 'octaves', type: 'int' },
  29375. { name: 'lacunarity', type: 'float' },
  29376. { name: 'diminish', type: 'float' }
  29377. ]
  29378. } );
  29379. const mx_fractal_noise_vec4$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  29380. const diminish = float( diminish_immutable ).toVar();
  29381. const lacunarity = float( lacunarity_immutable ).toVar();
  29382. const octaves = int( octaves_immutable ).toVar();
  29383. const p = vec3( p_immutable ).toVar();
  29384. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  29385. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  29386. return vec4( c, f );
  29387. } ).setLayout( {
  29388. name: 'mx_fractal_noise_vec4',
  29389. type: 'vec4',
  29390. inputs: [
  29391. { name: 'p', type: 'vec3' },
  29392. { name: 'octaves', type: 'int' },
  29393. { name: 'lacunarity', type: 'float' },
  29394. { name: 'diminish', type: 'float' }
  29395. ]
  29396. } );
  29397. const mx_worley_distance_0 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  29398. const metric = int( metric_immutable ).toVar();
  29399. const jitter = float( jitter_immutable ).toVar();
  29400. const yoff = int( yoff_immutable ).toVar();
  29401. const xoff = int( xoff_immutable ).toVar();
  29402. const y = int( y_immutable ).toVar();
  29403. const x = int( x_immutable ).toVar();
  29404. const p = vec2( p_immutable ).toVar();
  29405. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  29406. const off = vec2( tmp.x, tmp.y ).toVar();
  29407. off.subAssign( 0.5 );
  29408. off.mulAssign( jitter );
  29409. off.addAssign( 0.5 );
  29410. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  29411. const diff = vec2( cellpos.sub( p ) ).toVar();
  29412. If( metric.equal( int( 2 ) ), () => {
  29413. return abs( diff.x ).add( abs( diff.y ) );
  29414. } );
  29415. If( metric.equal( int( 3 ) ), () => {
  29416. return max$1( abs( diff.x ), abs( diff.y ) );
  29417. } );
  29418. return dot( diff, diff );
  29419. } ).setLayout( {
  29420. name: 'mx_worley_distance_0',
  29421. type: 'float',
  29422. inputs: [
  29423. { name: 'p', type: 'vec2' },
  29424. { name: 'x', type: 'int' },
  29425. { name: 'y', type: 'int' },
  29426. { name: 'xoff', type: 'int' },
  29427. { name: 'yoff', type: 'int' },
  29428. { name: 'jitter', type: 'float' },
  29429. { name: 'metric', type: 'int' }
  29430. ]
  29431. } );
  29432. 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 ] ) => {
  29433. const metric = int( metric_immutable ).toVar();
  29434. const jitter = float( jitter_immutable ).toVar();
  29435. const zoff = int( zoff_immutable ).toVar();
  29436. const yoff = int( yoff_immutable ).toVar();
  29437. const xoff = int( xoff_immutable ).toVar();
  29438. const z = int( z_immutable ).toVar();
  29439. const y = int( y_immutable ).toVar();
  29440. const x = int( x_immutable ).toVar();
  29441. const p = vec3( p_immutable ).toVar();
  29442. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  29443. off.subAssign( 0.5 );
  29444. off.mulAssign( jitter );
  29445. off.addAssign( 0.5 );
  29446. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  29447. const diff = vec3( cellpos.sub( p ) ).toVar();
  29448. If( metric.equal( int( 2 ) ), () => {
  29449. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  29450. } );
  29451. If( metric.equal( int( 3 ) ), () => {
  29452. return max$1( abs( diff.x ), abs( diff.y ), abs( diff.z ) );
  29453. } );
  29454. return dot( diff, diff );
  29455. } ).setLayout( {
  29456. name: 'mx_worley_distance_1',
  29457. type: 'float',
  29458. inputs: [
  29459. { name: 'p', type: 'vec3' },
  29460. { name: 'x', type: 'int' },
  29461. { name: 'y', type: 'int' },
  29462. { name: 'z', type: 'int' },
  29463. { name: 'xoff', type: 'int' },
  29464. { name: 'yoff', type: 'int' },
  29465. { name: 'zoff', type: 'int' },
  29466. { name: 'jitter', type: 'float' },
  29467. { name: 'metric', type: 'int' }
  29468. ]
  29469. } );
  29470. const mx_worley_distance = /*@__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  29471. const mx_worley_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  29472. const metric = int( metric_immutable ).toVar();
  29473. const jitter = float( jitter_immutable ).toVar();
  29474. const p = vec2( p_immutable ).toVar();
  29475. const X = int().toVar(), Y = int().toVar();
  29476. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  29477. const sqdist = float( 1e6 ).toVar();
  29478. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  29479. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  29480. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  29481. sqdist.assign( min$1( sqdist, dist ) );
  29482. } );
  29483. } );
  29484. If( metric.equal( int( 0 ) ), () => {
  29485. sqdist.assign( sqrt( sqdist ) );
  29486. } );
  29487. return sqdist;
  29488. } ).setLayout( {
  29489. name: 'mx_worley_noise_float_0',
  29490. type: 'float',
  29491. inputs: [
  29492. { name: 'p', type: 'vec2' },
  29493. { name: 'jitter', type: 'float' },
  29494. { name: 'metric', type: 'int' }
  29495. ]
  29496. } );
  29497. const mx_worley_noise_vec2_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  29498. const metric = int( metric_immutable ).toVar();
  29499. const jitter = float( jitter_immutable ).toVar();
  29500. const p = vec2( p_immutable ).toVar();
  29501. const X = int().toVar(), Y = int().toVar();
  29502. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  29503. const sqdist = vec2( 1e6, 1e6 ).toVar();
  29504. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  29505. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  29506. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  29507. If( dist.lessThan( sqdist.x ), () => {
  29508. sqdist.y.assign( sqdist.x );
  29509. sqdist.x.assign( dist );
  29510. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  29511. sqdist.y.assign( dist );
  29512. } );
  29513. } );
  29514. } );
  29515. If( metric.equal( int( 0 ) ), () => {
  29516. sqdist.assign( sqrt( sqdist ) );
  29517. } );
  29518. return sqdist;
  29519. } ).setLayout( {
  29520. name: 'mx_worley_noise_vec2_0',
  29521. type: 'vec2',
  29522. inputs: [
  29523. { name: 'p', type: 'vec2' },
  29524. { name: 'jitter', type: 'float' },
  29525. { name: 'metric', type: 'int' }
  29526. ]
  29527. } );
  29528. const mx_worley_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  29529. const metric = int( metric_immutable ).toVar();
  29530. const jitter = float( jitter_immutable ).toVar();
  29531. const p = vec2( p_immutable ).toVar();
  29532. const X = int().toVar(), Y = int().toVar();
  29533. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  29534. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  29535. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  29536. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  29537. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  29538. If( dist.lessThan( sqdist.x ), () => {
  29539. sqdist.z.assign( sqdist.y );
  29540. sqdist.y.assign( sqdist.x );
  29541. sqdist.x.assign( dist );
  29542. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  29543. sqdist.z.assign( sqdist.y );
  29544. sqdist.y.assign( dist );
  29545. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  29546. sqdist.z.assign( dist );
  29547. } );
  29548. } );
  29549. } );
  29550. If( metric.equal( int( 0 ) ), () => {
  29551. sqdist.assign( sqrt( sqdist ) );
  29552. } );
  29553. return sqdist;
  29554. } ).setLayout( {
  29555. name: 'mx_worley_noise_vec3_0',
  29556. type: 'vec3',
  29557. inputs: [
  29558. { name: 'p', type: 'vec2' },
  29559. { name: 'jitter', type: 'float' },
  29560. { name: 'metric', type: 'int' }
  29561. ]
  29562. } );
  29563. const mx_worley_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  29564. const metric = int( metric_immutable ).toVar();
  29565. const jitter = float( jitter_immutable ).toVar();
  29566. const p = vec3( p_immutable ).toVar();
  29567. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  29568. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  29569. const sqdist = float( 1e6 ).toVar();
  29570. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  29571. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  29572. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  29573. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  29574. sqdist.assign( min$1( sqdist, dist ) );
  29575. } );
  29576. } );
  29577. } );
  29578. If( metric.equal( int( 0 ) ), () => {
  29579. sqdist.assign( sqrt( sqdist ) );
  29580. } );
  29581. return sqdist;
  29582. } ).setLayout( {
  29583. name: 'mx_worley_noise_float_1',
  29584. type: 'float',
  29585. inputs: [
  29586. { name: 'p', type: 'vec3' },
  29587. { name: 'jitter', type: 'float' },
  29588. { name: 'metric', type: 'int' }
  29589. ]
  29590. } );
  29591. const mx_worley_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  29592. const mx_worley_noise_vec2_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  29593. const metric = int( metric_immutable ).toVar();
  29594. const jitter = float( jitter_immutable ).toVar();
  29595. const p = vec3( p_immutable ).toVar();
  29596. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  29597. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  29598. const sqdist = vec2( 1e6, 1e6 ).toVar();
  29599. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  29600. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  29601. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  29602. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  29603. If( dist.lessThan( sqdist.x ), () => {
  29604. sqdist.y.assign( sqdist.x );
  29605. sqdist.x.assign( dist );
  29606. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  29607. sqdist.y.assign( dist );
  29608. } );
  29609. } );
  29610. } );
  29611. } );
  29612. If( metric.equal( int( 0 ) ), () => {
  29613. sqdist.assign( sqrt( sqdist ) );
  29614. } );
  29615. return sqdist;
  29616. } ).setLayout( {
  29617. name: 'mx_worley_noise_vec2_1',
  29618. type: 'vec2',
  29619. inputs: [
  29620. { name: 'p', type: 'vec3' },
  29621. { name: 'jitter', type: 'float' },
  29622. { name: 'metric', type: 'int' }
  29623. ]
  29624. } );
  29625. const mx_worley_noise_vec2$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  29626. const mx_worley_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  29627. const metric = int( metric_immutable ).toVar();
  29628. const jitter = float( jitter_immutable ).toVar();
  29629. const p = vec3( p_immutable ).toVar();
  29630. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  29631. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  29632. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  29633. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  29634. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  29635. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  29636. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  29637. If( dist.lessThan( sqdist.x ), () => {
  29638. sqdist.z.assign( sqdist.y );
  29639. sqdist.y.assign( sqdist.x );
  29640. sqdist.x.assign( dist );
  29641. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  29642. sqdist.z.assign( sqdist.y );
  29643. sqdist.y.assign( dist );
  29644. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  29645. sqdist.z.assign( dist );
  29646. } );
  29647. } );
  29648. } );
  29649. } );
  29650. If( metric.equal( int( 0 ) ), () => {
  29651. sqdist.assign( sqrt( sqdist ) );
  29652. } );
  29653. return sqdist;
  29654. } ).setLayout( {
  29655. name: 'mx_worley_noise_vec3_1',
  29656. type: 'vec3',
  29657. inputs: [
  29658. { name: 'p', type: 'vec3' },
  29659. { name: 'jitter', type: 'float' },
  29660. { name: 'metric', type: 'int' }
  29661. ]
  29662. } );
  29663. const mx_worley_noise_vec3$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  29664. // Three.js Transpiler
  29665. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  29666. const mx_hsvtorgb = /*@__PURE__*/ Fn( ( [ hsv ] ) => {
  29667. const s = hsv.y;
  29668. const v = hsv.z;
  29669. const result = vec3().toVar();
  29670. If( s.lessThan( 0.0001 ), () => {
  29671. result.assign( vec3( v, v, v ) );
  29672. } ).Else( () => {
  29673. let h = hsv.x;
  29674. h = h.sub( floor( h ) ).mul( 6.0 ).toVar(); // TODO: check what .toVar() is needed in node system cache
  29675. const hi = int( trunc( h ) );
  29676. const f = h.sub( float( hi ) );
  29677. const p = v.mul( s.oneMinus() );
  29678. const q = v.mul( s.mul( f ).oneMinus() );
  29679. const t = v.mul( s.mul( f.oneMinus() ).oneMinus() );
  29680. If( hi.equal( int( 0 ) ), () => {
  29681. result.assign( vec3( v, t, p ) );
  29682. } ).ElseIf( hi.equal( int( 1 ) ), () => {
  29683. result.assign( vec3( q, v, p ) );
  29684. } ).ElseIf( hi.equal( int( 2 ) ), () => {
  29685. result.assign( vec3( p, v, t ) );
  29686. } ).ElseIf( hi.equal( int( 3 ) ), () => {
  29687. result.assign( vec3( p, q, v ) );
  29688. } ).ElseIf( hi.equal( int( 4 ) ), () => {
  29689. result.assign( vec3( t, p, v ) );
  29690. } ).Else( () => {
  29691. result.assign( vec3( v, p, q ) );
  29692. } );
  29693. } );
  29694. return result;
  29695. } ).setLayout( {
  29696. name: 'mx_hsvtorgb',
  29697. type: 'vec3',
  29698. inputs: [
  29699. { name: 'hsv', type: 'vec3' }
  29700. ]
  29701. } );
  29702. const mx_rgbtohsv = /*@__PURE__*/ Fn( ( [ c_immutable ] ) => {
  29703. const c = vec3( c_immutable ).toVar();
  29704. const r = float( c.x ).toVar();
  29705. const g = float( c.y ).toVar();
  29706. const b = float( c.z ).toVar();
  29707. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  29708. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  29709. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  29710. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  29711. v.assign( maxcomp );
  29712. If( maxcomp.greaterThan( 0.0 ), () => {
  29713. s.assign( delta.div( maxcomp ) );
  29714. } ).Else( () => {
  29715. s.assign( 0.0 );
  29716. } );
  29717. If( s.lessThanEqual( 0.0 ), () => {
  29718. h.assign( 0.0 );
  29719. } ).Else( () => {
  29720. If( r.greaterThanEqual( maxcomp ), () => {
  29721. h.assign( g.sub( b ).div( delta ) );
  29722. } ).ElseIf( g.greaterThanEqual( maxcomp ), () => {
  29723. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  29724. } ).Else( () => {
  29725. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  29726. } );
  29727. h.mulAssign( 1.0 / 6.0 );
  29728. If( h.lessThan( 0.0 ), () => {
  29729. h.addAssign( 1.0 );
  29730. } );
  29731. } );
  29732. return vec3( h, s, v );
  29733. } ).setLayout( {
  29734. name: 'mx_rgbtohsv',
  29735. type: 'vec3',
  29736. inputs: [
  29737. { name: 'c', type: 'vec3' }
  29738. ]
  29739. } );
  29740. // Three.js Transpiler
  29741. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  29742. const mx_srgb_texture_to_lin_rec709 = /*@__PURE__*/ Fn( ( [ color_immutable ] ) => {
  29743. const color = vec3( color_immutable ).toVar();
  29744. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  29745. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  29746. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  29747. return mix( linSeg, powSeg, isAbove );
  29748. } ).setLayout( {
  29749. name: 'mx_srgb_texture_to_lin_rec709',
  29750. type: 'vec3',
  29751. inputs: [
  29752. { name: 'color', type: 'vec3' }
  29753. ]
  29754. } );
  29755. const mx_aastep = ( threshold, value ) => {
  29756. threshold = float( threshold );
  29757. value = float( value );
  29758. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  29759. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  29760. };
  29761. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  29762. const mx_ramplr = ( valuel, valuer, texcoord = uv() ) => _ramp( valuel, valuer, texcoord, 'x' );
  29763. const mx_ramptb = ( valuet, valueb, texcoord = uv() ) => _ramp( valuet, valueb, texcoord, 'y' );
  29764. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  29765. const mx_splitlr = ( valuel, valuer, center, texcoord = uv() ) => _split( valuel, valuer, center, texcoord, 'x' );
  29766. const mx_splittb = ( valuet, valueb, center, texcoord = uv() ) => _split( valuet, valueb, center, texcoord, 'y' );
  29767. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  29768. const mx_safepower = ( in1, in2 = 1 ) => {
  29769. in1 = float( in1 );
  29770. return in1.abs().pow( in2 ).mul( in1.sign() );
  29771. };
  29772. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  29773. const mx_noise_float = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  29774. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  29775. const mx_noise_vec3 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  29776. const mx_noise_vec4 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => {
  29777. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  29778. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  29779. return noise_vec4.mul( amplitude ).add( pivot );
  29780. };
  29781. const mx_worley_noise_float = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  29782. const mx_worley_noise_vec2 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  29783. const mx_worley_noise_vec3 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  29784. const mx_cell_noise_float = ( texcoord = uv() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  29785. const mx_fractal_noise_float = ( position = uv(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_float$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude );
  29786. const mx_fractal_noise_vec2 = ( position = uv(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec2$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude );
  29787. const mx_fractal_noise_vec3 = ( position = uv(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec3$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude );
  29788. const mx_fractal_noise_vec4 = ( position = uv(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec4$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude );
  29789. /**
  29790. * This computes a parallax corrected normal which is used for box-projected cube mapping (BPCEM).
  29791. *
  29792. * Reference: {@link https://devlog-martinsh.blogspot.com/2011/09/box-projected-cube-environment-mapping.html}
  29793. *
  29794. * ```js
  29795. * const uvNode = getParallaxCorrectNormal( reflectVector, vec3( 200, 100, 100 ), vec3( 0, - 50, 0 ) );
  29796. * material.envNode = pmremTexture( renderTarget.texture, uvNode );
  29797. * ```
  29798. *
  29799. * @tsl
  29800. * @function
  29801. * @param {Node<vec3>} normal - The normal to correct.
  29802. * @param {Node<vec3>} cubeSize - The cube size should reflect the size of the environment (BPCEM is usually applied in closed environments like rooms).
  29803. * @param {Node<vec3>} cubePos - The cube position.
  29804. * @return {Node<vec3>} The parallax corrected normal.
  29805. */
  29806. const getParallaxCorrectNormal = /*@__PURE__*/ Fn( ( [ normal, cubeSize, cubePos ] ) => {
  29807. const nDir = normalize( normal ).toVar();
  29808. const rbmax = sub( float( 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar();
  29809. const rbmin = sub( float( -0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar();
  29810. const rbminmax = vec3().toVar();
  29811. rbminmax.x = nDir.x.greaterThan( float( 0 ) ).select( rbmax.x, rbmin.x );
  29812. rbminmax.y = nDir.y.greaterThan( float( 0 ) ).select( rbmax.y, rbmin.y );
  29813. rbminmax.z = nDir.z.greaterThan( float( 0 ) ).select( rbmax.z, rbmin.z );
  29814. const correction = min$1( rbminmax.x, rbminmax.y, rbminmax.z ).toVar();
  29815. const boxIntersection = positionWorld.add( nDir.mul( correction ) ).toVar();
  29816. return boxIntersection.sub( cubePos );
  29817. } );
  29818. const getShIrradianceAt = /*@__PURE__*/ Fn( ( [ normal, shCoefficients ] ) => {
  29819. // normal is assumed to have unit length
  29820. const x = normal.x, y = normal.y, z = normal.z;
  29821. // band 0
  29822. let result = shCoefficients.element( 0 ).mul( 0.886227 );
  29823. // band 1
  29824. result = result.add( shCoefficients.element( 1 ).mul( 2.0 * 0.511664 ).mul( y ) );
  29825. result = result.add( shCoefficients.element( 2 ).mul( 2.0 * 0.511664 ).mul( z ) );
  29826. result = result.add( shCoefficients.element( 3 ).mul( 2.0 * 0.511664 ).mul( x ) );
  29827. // band 2
  29828. result = result.add( shCoefficients.element( 4 ).mul( 2.0 * 0.429043 ).mul( x ).mul( y ) );
  29829. result = result.add( shCoefficients.element( 5 ).mul( 2.0 * 0.429043 ).mul( y ).mul( z ) );
  29830. result = result.add( shCoefficients.element( 6 ).mul( z.mul( z ).mul( 0.743125 ).sub( 0.247708 ) ) );
  29831. result = result.add( shCoefficients.element( 7 ).mul( 2.0 * 0.429043 ).mul( x ).mul( z ) );
  29832. result = result.add( shCoefficients.element( 8 ).mul( 0.429043 ).mul( mul( x, x ).sub( mul( y, y ) ) ) );
  29833. return result;
  29834. } );
  29835. // constants
  29836. var TSL = /*#__PURE__*/Object.freeze({
  29837. __proto__: null,
  29838. BRDF_GGX: BRDF_GGX,
  29839. BRDF_Lambert: BRDF_Lambert,
  29840. BasicPointShadowFilter: BasicPointShadowFilter,
  29841. BasicShadowFilter: BasicShadowFilter,
  29842. Break: Break,
  29843. Const: Const,
  29844. Continue: Continue,
  29845. DFGApprox: DFGApprox,
  29846. D_GGX: D_GGX,
  29847. Discard: Discard,
  29848. EPSILON: EPSILON,
  29849. F_Schlick: F_Schlick,
  29850. Fn: Fn,
  29851. INFINITY: INFINITY,
  29852. If: If,
  29853. Loop: Loop,
  29854. NodeAccess: NodeAccess,
  29855. NodeShaderStage: NodeShaderStage,
  29856. NodeType: NodeType,
  29857. NodeUpdateType: NodeUpdateType,
  29858. PCFShadowFilter: PCFShadowFilter,
  29859. PCFSoftShadowFilter: PCFSoftShadowFilter,
  29860. PI: PI,
  29861. PI2: PI2,
  29862. PointShadowFilter: PointShadowFilter,
  29863. Return: Return,
  29864. Schlick_to_F0: Schlick_to_F0,
  29865. ScriptableNodeResources: ScriptableNodeResources,
  29866. ShaderNode: ShaderNode,
  29867. Stack: Stack,
  29868. Switch: Switch,
  29869. TBNViewMatrix: TBNViewMatrix,
  29870. VSMShadowFilter: VSMShadowFilter,
  29871. V_GGX_SmithCorrelated: V_GGX_SmithCorrelated,
  29872. Var: Var,
  29873. abs: abs,
  29874. acesFilmicToneMapping: acesFilmicToneMapping,
  29875. acos: acos,
  29876. add: add,
  29877. addMethodChaining: addMethodChaining,
  29878. addNodeElement: addNodeElement,
  29879. agxToneMapping: agxToneMapping,
  29880. all: all,
  29881. alphaT: alphaT,
  29882. and: and,
  29883. anisotropy: anisotropy,
  29884. anisotropyB: anisotropyB,
  29885. anisotropyT: anisotropyT,
  29886. any: any,
  29887. append: append,
  29888. array: array,
  29889. arrayBuffer: arrayBuffer,
  29890. asin: asin,
  29891. assign: assign,
  29892. atan: atan,
  29893. atan2: atan2,
  29894. atomicAdd: atomicAdd,
  29895. atomicAnd: atomicAnd,
  29896. atomicFunc: atomicFunc,
  29897. atomicLoad: atomicLoad,
  29898. atomicMax: atomicMax,
  29899. atomicMin: atomicMin,
  29900. atomicOr: atomicOr,
  29901. atomicStore: atomicStore,
  29902. atomicSub: atomicSub,
  29903. atomicXor: atomicXor,
  29904. attenuationColor: attenuationColor,
  29905. attenuationDistance: attenuationDistance,
  29906. attribute: attribute,
  29907. attributeArray: attributeArray,
  29908. backgroundBlurriness: backgroundBlurriness,
  29909. backgroundIntensity: backgroundIntensity,
  29910. backgroundRotation: backgroundRotation,
  29911. batch: batch,
  29912. billboarding: billboarding,
  29913. bitAnd: bitAnd,
  29914. bitNot: bitNot,
  29915. bitOr: bitOr,
  29916. bitXor: bitXor,
  29917. bitangentGeometry: bitangentGeometry,
  29918. bitangentLocal: bitangentLocal,
  29919. bitangentView: bitangentView,
  29920. bitangentWorld: bitangentWorld,
  29921. bitcast: bitcast,
  29922. blendBurn: blendBurn,
  29923. blendColor: blendColor,
  29924. blendDodge: blendDodge,
  29925. blendOverlay: blendOverlay,
  29926. blendScreen: blendScreen,
  29927. blur: blur,
  29928. bool: bool,
  29929. buffer: buffer,
  29930. bufferAttribute: bufferAttribute,
  29931. bumpMap: bumpMap,
  29932. burn: burn,
  29933. bvec2: bvec2,
  29934. bvec3: bvec3,
  29935. bvec4: bvec4,
  29936. bypass: bypass,
  29937. cache: cache,
  29938. call: call,
  29939. cameraFar: cameraFar,
  29940. cameraIndex: cameraIndex,
  29941. cameraNear: cameraNear,
  29942. cameraNormalMatrix: cameraNormalMatrix,
  29943. cameraPosition: cameraPosition,
  29944. cameraProjectionMatrix: cameraProjectionMatrix,
  29945. cameraProjectionMatrixInverse: cameraProjectionMatrixInverse,
  29946. cameraViewMatrix: cameraViewMatrix,
  29947. cameraWorldMatrix: cameraWorldMatrix,
  29948. cbrt: cbrt,
  29949. cdl: cdl,
  29950. ceil: ceil,
  29951. checker: checker,
  29952. cineonToneMapping: cineonToneMapping,
  29953. clamp: clamp,
  29954. clearcoat: clearcoat,
  29955. clearcoatRoughness: clearcoatRoughness,
  29956. code: code,
  29957. color: color,
  29958. colorSpaceToWorking: colorSpaceToWorking,
  29959. colorToDirection: colorToDirection,
  29960. compute: compute,
  29961. computeSkinning: computeSkinning,
  29962. cond: cond,
  29963. context: context,
  29964. convert: convert,
  29965. convertColorSpace: convertColorSpace,
  29966. convertToTexture: convertToTexture,
  29967. cos: cos,
  29968. cross: cross,
  29969. cubeTexture: cubeTexture,
  29970. cubeTextureBase: cubeTextureBase,
  29971. cubeToUV: cubeToUV,
  29972. dFdx: dFdx,
  29973. dFdy: dFdy,
  29974. dashSize: dashSize,
  29975. debug: debug,
  29976. decrement: decrement,
  29977. decrementBefore: decrementBefore,
  29978. defaultBuildStages: defaultBuildStages,
  29979. defaultShaderStages: defaultShaderStages,
  29980. defined: defined,
  29981. degrees: degrees,
  29982. deltaTime: deltaTime,
  29983. densityFog: densityFog,
  29984. densityFogFactor: densityFogFactor,
  29985. depth: depth,
  29986. depthPass: depthPass,
  29987. difference: difference,
  29988. diffuseColor: diffuseColor,
  29989. directPointLight: directPointLight,
  29990. directionToColor: directionToColor,
  29991. dispersion: dispersion,
  29992. distance: distance,
  29993. div: div,
  29994. dodge: dodge,
  29995. dot: dot,
  29996. drawIndex: drawIndex,
  29997. dynamicBufferAttribute: dynamicBufferAttribute,
  29998. element: element,
  29999. emissive: emissive,
  30000. equal: equal,
  30001. equals: equals,
  30002. equirectUV: equirectUV,
  30003. exp: exp,
  30004. exp2: exp2,
  30005. expression: expression,
  30006. faceDirection: faceDirection,
  30007. faceForward: faceForward,
  30008. faceforward: faceforward,
  30009. float: float,
  30010. floor: floor,
  30011. fog: fog,
  30012. fract: fract,
  30013. frameGroup: frameGroup,
  30014. frameId: frameId,
  30015. frontFacing: frontFacing,
  30016. fwidth: fwidth,
  30017. gain: gain,
  30018. gapSize: gapSize,
  30019. getConstNodeType: getConstNodeType,
  30020. getCurrentStack: getCurrentStack,
  30021. getDirection: getDirection,
  30022. getDistanceAttenuation: getDistanceAttenuation,
  30023. getGeometryRoughness: getGeometryRoughness,
  30024. getNormalFromDepth: getNormalFromDepth,
  30025. getParallaxCorrectNormal: getParallaxCorrectNormal,
  30026. getRoughness: getRoughness,
  30027. getScreenPosition: getScreenPosition,
  30028. getShIrradianceAt: getShIrradianceAt,
  30029. getShadowMaterial: getShadowMaterial,
  30030. getShadowRenderObjectFunction: getShadowRenderObjectFunction,
  30031. getTextureIndex: getTextureIndex,
  30032. getViewPosition: getViewPosition,
  30033. globalId: globalId,
  30034. glsl: glsl,
  30035. glslFn: glslFn,
  30036. grayscale: grayscale,
  30037. greaterThan: greaterThan,
  30038. greaterThanEqual: greaterThanEqual,
  30039. hash: hash,
  30040. highpModelNormalViewMatrix: highpModelNormalViewMatrix,
  30041. highpModelViewMatrix: highpModelViewMatrix,
  30042. hue: hue,
  30043. increment: increment,
  30044. incrementBefore: incrementBefore,
  30045. instance: instance,
  30046. instanceIndex: instanceIndex,
  30047. instancedArray: instancedArray,
  30048. instancedBufferAttribute: instancedBufferAttribute,
  30049. instancedDynamicBufferAttribute: instancedDynamicBufferAttribute,
  30050. instancedMesh: instancedMesh,
  30051. int: int,
  30052. inverseSqrt: inverseSqrt,
  30053. inversesqrt: inversesqrt,
  30054. invocationLocalIndex: invocationLocalIndex,
  30055. invocationSubgroupIndex: invocationSubgroupIndex,
  30056. ior: ior,
  30057. iridescence: iridescence,
  30058. iridescenceIOR: iridescenceIOR,
  30059. iridescenceThickness: iridescenceThickness,
  30060. ivec2: ivec2,
  30061. ivec3: ivec3,
  30062. ivec4: ivec4,
  30063. js: js,
  30064. label: label,
  30065. length: length,
  30066. lengthSq: lengthSq,
  30067. lessThan: lessThan,
  30068. lessThanEqual: lessThanEqual,
  30069. lightPosition: lightPosition,
  30070. lightProjectionUV: lightProjectionUV,
  30071. lightShadowMatrix: lightShadowMatrix,
  30072. lightTargetDirection: lightTargetDirection,
  30073. lightTargetPosition: lightTargetPosition,
  30074. lightViewPosition: lightViewPosition,
  30075. lightingContext: lightingContext,
  30076. lights: lights,
  30077. linearDepth: linearDepth,
  30078. linearToneMapping: linearToneMapping,
  30079. localId: localId,
  30080. log: log,
  30081. log2: log2,
  30082. logarithmicDepthToViewZ: logarithmicDepthToViewZ,
  30083. loop: loop,
  30084. luminance: luminance,
  30085. mat2: mat2,
  30086. mat3: mat3,
  30087. mat4: mat4,
  30088. matcapUV: matcapUV,
  30089. materialAO: materialAO,
  30090. materialAlphaTest: materialAlphaTest,
  30091. materialAnisotropy: materialAnisotropy,
  30092. materialAnisotropyVector: materialAnisotropyVector,
  30093. materialAttenuationColor: materialAttenuationColor,
  30094. materialAttenuationDistance: materialAttenuationDistance,
  30095. materialClearcoat: materialClearcoat,
  30096. materialClearcoatNormal: materialClearcoatNormal,
  30097. materialClearcoatRoughness: materialClearcoatRoughness,
  30098. materialColor: materialColor,
  30099. materialDispersion: materialDispersion,
  30100. materialEmissive: materialEmissive,
  30101. materialEnvIntensity: materialEnvIntensity,
  30102. materialEnvRotation: materialEnvRotation,
  30103. materialIOR: materialIOR,
  30104. materialIridescence: materialIridescence,
  30105. materialIridescenceIOR: materialIridescenceIOR,
  30106. materialIridescenceThickness: materialIridescenceThickness,
  30107. materialLightMap: materialLightMap,
  30108. materialLineDashOffset: materialLineDashOffset,
  30109. materialLineDashSize: materialLineDashSize,
  30110. materialLineGapSize: materialLineGapSize,
  30111. materialLineScale: materialLineScale,
  30112. materialLineWidth: materialLineWidth,
  30113. materialMetalness: materialMetalness,
  30114. materialNormal: materialNormal,
  30115. materialOpacity: materialOpacity,
  30116. materialPointSize: materialPointSize,
  30117. materialReference: materialReference,
  30118. materialReflectivity: materialReflectivity,
  30119. materialRefractionRatio: materialRefractionRatio,
  30120. materialRotation: materialRotation,
  30121. materialRoughness: materialRoughness,
  30122. materialSheen: materialSheen,
  30123. materialSheenRoughness: materialSheenRoughness,
  30124. materialShininess: materialShininess,
  30125. materialSpecular: materialSpecular,
  30126. materialSpecularColor: materialSpecularColor,
  30127. materialSpecularIntensity: materialSpecularIntensity,
  30128. materialSpecularStrength: materialSpecularStrength,
  30129. materialThickness: materialThickness,
  30130. materialTransmission: materialTransmission,
  30131. max: max$1,
  30132. maxMipLevel: maxMipLevel,
  30133. mediumpModelViewMatrix: mediumpModelViewMatrix,
  30134. metalness: metalness,
  30135. min: min$1,
  30136. mix: mix,
  30137. mixElement: mixElement,
  30138. mod: mod,
  30139. modInt: modInt,
  30140. modelDirection: modelDirection,
  30141. modelNormalMatrix: modelNormalMatrix,
  30142. modelPosition: modelPosition,
  30143. modelRadius: modelRadius,
  30144. modelScale: modelScale,
  30145. modelViewMatrix: modelViewMatrix,
  30146. modelViewPosition: modelViewPosition,
  30147. modelViewProjection: modelViewProjection,
  30148. modelWorldMatrix: modelWorldMatrix,
  30149. modelWorldMatrixInverse: modelWorldMatrixInverse,
  30150. morphReference: morphReference,
  30151. mrt: mrt,
  30152. mul: mul,
  30153. mx_aastep: mx_aastep,
  30154. mx_cell_noise_float: mx_cell_noise_float,
  30155. mx_contrast: mx_contrast,
  30156. mx_fractal_noise_float: mx_fractal_noise_float,
  30157. mx_fractal_noise_vec2: mx_fractal_noise_vec2,
  30158. mx_fractal_noise_vec3: mx_fractal_noise_vec3,
  30159. mx_fractal_noise_vec4: mx_fractal_noise_vec4,
  30160. mx_hsvtorgb: mx_hsvtorgb,
  30161. mx_noise_float: mx_noise_float,
  30162. mx_noise_vec3: mx_noise_vec3,
  30163. mx_noise_vec4: mx_noise_vec4,
  30164. mx_ramplr: mx_ramplr,
  30165. mx_ramptb: mx_ramptb,
  30166. mx_rgbtohsv: mx_rgbtohsv,
  30167. mx_safepower: mx_safepower,
  30168. mx_splitlr: mx_splitlr,
  30169. mx_splittb: mx_splittb,
  30170. mx_srgb_texture_to_lin_rec709: mx_srgb_texture_to_lin_rec709,
  30171. mx_transform_uv: mx_transform_uv,
  30172. mx_worley_noise_float: mx_worley_noise_float,
  30173. mx_worley_noise_vec2: mx_worley_noise_vec2,
  30174. mx_worley_noise_vec3: mx_worley_noise_vec3,
  30175. namespace: namespace,
  30176. negate: negate,
  30177. neutralToneMapping: neutralToneMapping,
  30178. nodeArray: nodeArray,
  30179. nodeImmutable: nodeImmutable,
  30180. nodeObject: nodeObject,
  30181. nodeObjects: nodeObjects,
  30182. nodeProxy: nodeProxy,
  30183. normalFlat: normalFlat,
  30184. normalGeometry: normalGeometry,
  30185. normalLocal: normalLocal,
  30186. normalMap: normalMap,
  30187. normalView: normalView,
  30188. normalWorld: normalWorld,
  30189. normalize: normalize,
  30190. not: not,
  30191. notEqual: notEqual,
  30192. numWorkgroups: numWorkgroups,
  30193. objectDirection: objectDirection,
  30194. objectGroup: objectGroup,
  30195. objectPosition: objectPosition,
  30196. objectRadius: objectRadius,
  30197. objectScale: objectScale,
  30198. objectViewPosition: objectViewPosition,
  30199. objectWorldMatrix: objectWorldMatrix,
  30200. oneMinus: oneMinus,
  30201. or: or,
  30202. orthographicDepthToViewZ: orthographicDepthToViewZ,
  30203. oscSawtooth: oscSawtooth,
  30204. oscSine: oscSine,
  30205. oscSquare: oscSquare,
  30206. oscTriangle: oscTriangle,
  30207. output: output,
  30208. outputStruct: outputStruct,
  30209. overlay: overlay,
  30210. overloadingFn: overloadingFn,
  30211. parabola: parabola,
  30212. parallaxDirection: parallaxDirection,
  30213. parallaxUV: parallaxUV,
  30214. parameter: parameter,
  30215. pass: pass,
  30216. passTexture: passTexture,
  30217. pcurve: pcurve,
  30218. perspectiveDepthToViewZ: perspectiveDepthToViewZ,
  30219. pmremTexture: pmremTexture,
  30220. pointShadow: pointShadow,
  30221. pointUV: pointUV,
  30222. pointWidth: pointWidth,
  30223. positionGeometry: positionGeometry,
  30224. positionLocal: positionLocal,
  30225. positionPrevious: positionPrevious,
  30226. positionView: positionView,
  30227. positionViewDirection: positionViewDirection,
  30228. positionWorld: positionWorld,
  30229. positionWorldDirection: positionWorldDirection,
  30230. posterize: posterize,
  30231. pow: pow,
  30232. pow2: pow2,
  30233. pow3: pow3,
  30234. pow4: pow4,
  30235. premult: premult,
  30236. property: property,
  30237. radians: radians,
  30238. rand: rand,
  30239. range: range,
  30240. rangeFog: rangeFog,
  30241. rangeFogFactor: rangeFogFactor,
  30242. reciprocal: reciprocal,
  30243. reference: reference,
  30244. referenceBuffer: referenceBuffer,
  30245. reflect: reflect,
  30246. reflectVector: reflectVector,
  30247. reflectView: reflectView,
  30248. reflector: reflector,
  30249. refract: refract,
  30250. refractVector: refractVector,
  30251. refractView: refractView,
  30252. reinhardToneMapping: reinhardToneMapping,
  30253. remainder: remainder,
  30254. remap: remap,
  30255. remapClamp: remapClamp,
  30256. renderGroup: renderGroup,
  30257. renderOutput: renderOutput,
  30258. rendererReference: rendererReference,
  30259. rotate: rotate,
  30260. rotateUV: rotateUV,
  30261. roughness: roughness,
  30262. round: round,
  30263. rtt: rtt,
  30264. sRGBTransferEOTF: sRGBTransferEOTF,
  30265. sRGBTransferOETF: sRGBTransferOETF,
  30266. sampler: sampler,
  30267. samplerComparison: samplerComparison,
  30268. saturate: saturate,
  30269. saturation: saturation,
  30270. screen: screen,
  30271. screenCoordinate: screenCoordinate,
  30272. screenSize: screenSize,
  30273. screenUV: screenUV,
  30274. scriptable: scriptable,
  30275. scriptableValue: scriptableValue,
  30276. select: select,
  30277. setCurrentStack: setCurrentStack,
  30278. shaderStages: shaderStages,
  30279. shadow: shadow,
  30280. shadowPositionWorld: shadowPositionWorld,
  30281. shapeCircle: shapeCircle,
  30282. sharedUniformGroup: sharedUniformGroup,
  30283. sheen: sheen,
  30284. sheenRoughness: sheenRoughness,
  30285. shiftLeft: shiftLeft,
  30286. shiftRight: shiftRight,
  30287. shininess: shininess,
  30288. sign: sign,
  30289. sin: sin,
  30290. sinc: sinc,
  30291. skinning: skinning,
  30292. smoothstep: smoothstep,
  30293. smoothstepElement: smoothstepElement,
  30294. specularColor: specularColor,
  30295. specularF90: specularF90,
  30296. spherizeUV: spherizeUV,
  30297. split: split,
  30298. spritesheetUV: spritesheetUV,
  30299. sqrt: sqrt,
  30300. stack: stack,
  30301. step: step,
  30302. storage: storage,
  30303. storageBarrier: storageBarrier,
  30304. storageObject: storageObject,
  30305. storageTexture: storageTexture,
  30306. string: string,
  30307. struct: struct,
  30308. sub: sub,
  30309. subgroupIndex: subgroupIndex,
  30310. subgroupSize: subgroupSize,
  30311. tan: tan,
  30312. tangentGeometry: tangentGeometry,
  30313. tangentLocal: tangentLocal,
  30314. tangentView: tangentView,
  30315. tangentWorld: tangentWorld,
  30316. temp: temp,
  30317. texture: texture,
  30318. texture3D: texture3D,
  30319. textureBarrier: textureBarrier,
  30320. textureBicubic: textureBicubic,
  30321. textureCubeUV: textureCubeUV,
  30322. textureLoad: textureLoad,
  30323. textureSize: textureSize,
  30324. textureStore: textureStore,
  30325. thickness: thickness,
  30326. time: time,
  30327. timerDelta: timerDelta,
  30328. timerGlobal: timerGlobal,
  30329. timerLocal: timerLocal,
  30330. toneMapping: toneMapping,
  30331. toneMappingExposure: toneMappingExposure,
  30332. toonOutlinePass: toonOutlinePass,
  30333. transformDirection: transformDirection,
  30334. transformNormal: transformNormal,
  30335. transformNormalToView: transformNormalToView,
  30336. transformedBentNormalView: transformedBentNormalView,
  30337. transformedBitangentView: transformedBitangentView,
  30338. transformedBitangentWorld: transformedBitangentWorld,
  30339. transformedClearcoatNormalView: transformedClearcoatNormalView,
  30340. transformedNormalView: transformedNormalView,
  30341. transformedNormalWorld: transformedNormalWorld,
  30342. transformedTangentView: transformedTangentView,
  30343. transformedTangentWorld: transformedTangentWorld,
  30344. transmission: transmission,
  30345. transpose: transpose,
  30346. triNoise3D: triNoise3D,
  30347. triplanarTexture: triplanarTexture,
  30348. triplanarTextures: triplanarTextures,
  30349. trunc: trunc,
  30350. tslFn: tslFn,
  30351. uint: uint,
  30352. uniform: uniform,
  30353. uniformArray: uniformArray,
  30354. uniformCubeTexture: uniformCubeTexture,
  30355. uniformGroup: uniformGroup,
  30356. uniformTexture: uniformTexture,
  30357. uniforms: uniforms,
  30358. unpremult: unpremult,
  30359. userData: userData,
  30360. uv: uv,
  30361. uvec2: uvec2,
  30362. uvec3: uvec3,
  30363. uvec4: uvec4,
  30364. varying: varying,
  30365. varyingProperty: varyingProperty,
  30366. vec2: vec2,
  30367. vec3: vec3,
  30368. vec4: vec4,
  30369. vectorComponents: vectorComponents,
  30370. velocity: velocity,
  30371. vertexColor: vertexColor,
  30372. vertexIndex: vertexIndex,
  30373. vertexStage: vertexStage,
  30374. vibrance: vibrance,
  30375. viewZToLogarithmicDepth: viewZToLogarithmicDepth,
  30376. viewZToOrthographicDepth: viewZToOrthographicDepth,
  30377. viewZToPerspectiveDepth: viewZToPerspectiveDepth,
  30378. viewport: viewport,
  30379. viewportBottomLeft: viewportBottomLeft,
  30380. viewportCoordinate: viewportCoordinate,
  30381. viewportDepthTexture: viewportDepthTexture,
  30382. viewportLinearDepth: viewportLinearDepth,
  30383. viewportMipTexture: viewportMipTexture,
  30384. viewportResolution: viewportResolution,
  30385. viewportSafeUV: viewportSafeUV,
  30386. viewportSharedTexture: viewportSharedTexture,
  30387. viewportSize: viewportSize,
  30388. viewportTexture: viewportTexture,
  30389. viewportTopLeft: viewportTopLeft,
  30390. viewportUV: viewportUV,
  30391. wgsl: wgsl,
  30392. wgslFn: wgslFn,
  30393. workgroupArray: workgroupArray,
  30394. workgroupBarrier: workgroupBarrier,
  30395. workgroupId: workgroupId,
  30396. workingToColorSpace: workingToColorSpace,
  30397. xor: xor
  30398. });
  30399. const _clearColor = /*@__PURE__*/ new Color4();
  30400. /**
  30401. * This renderer module manages the background.
  30402. *
  30403. * @private
  30404. * @augments DataMap
  30405. */
  30406. class Background extends DataMap {
  30407. /**
  30408. * Constructs a new background management component.
  30409. *
  30410. * @param {Renderer} renderer - The renderer.
  30411. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  30412. */
  30413. constructor( renderer, nodes ) {
  30414. super();
  30415. /**
  30416. * The renderer.
  30417. *
  30418. * @type {Renderer}
  30419. */
  30420. this.renderer = renderer;
  30421. /**
  30422. * Renderer component for managing nodes related logic.
  30423. *
  30424. * @type {Nodes}
  30425. */
  30426. this.nodes = nodes;
  30427. }
  30428. /**
  30429. * Updates the background for the given scene. Depending on how `Scene.background`
  30430. * or `Scene.backgroundNode` are configured, this method might configure a simple clear
  30431. * or add a mesh to the render list for rendering the background as a textured plane
  30432. * or skybox.
  30433. *
  30434. * @param {Scene} scene - The scene.
  30435. * @param {RenderList} renderList - The current render list.
  30436. * @param {RenderContext} renderContext - The current render context.
  30437. */
  30438. update( scene, renderList, renderContext ) {
  30439. const renderer = this.renderer;
  30440. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  30441. let forceClear = false;
  30442. if ( background === null ) {
  30443. // no background settings, use clear color configuration from the renderer
  30444. renderer._clearColor.getRGB( _clearColor );
  30445. _clearColor.a = renderer._clearColor.a;
  30446. } else if ( background.isColor === true ) {
  30447. // background is an opaque color
  30448. background.getRGB( _clearColor );
  30449. _clearColor.a = 1;
  30450. forceClear = true;
  30451. } else if ( background.isNode === true ) {
  30452. const sceneData = this.get( scene );
  30453. const backgroundNode = background;
  30454. _clearColor.copy( renderer._clearColor );
  30455. let backgroundMesh = sceneData.backgroundMesh;
  30456. if ( backgroundMesh === undefined ) {
  30457. const backgroundMeshNode = context( vec4( backgroundNode ).mul( backgroundIntensity ), {
  30458. // @TODO: Add Texture2D support using node context
  30459. getUV: () => backgroundRotation.mul( normalWorld ),
  30460. getTextureLevel: () => backgroundBlurriness
  30461. } );
  30462. let viewProj = modelViewProjection;
  30463. viewProj = viewProj.setZ( viewProj.w );
  30464. const nodeMaterial = new NodeMaterial();
  30465. nodeMaterial.name = 'Background.material';
  30466. nodeMaterial.side = BackSide;
  30467. nodeMaterial.depthTest = false;
  30468. nodeMaterial.depthWrite = false;
  30469. nodeMaterial.allowOverride = false;
  30470. nodeMaterial.fog = false;
  30471. nodeMaterial.lights = false;
  30472. nodeMaterial.vertexNode = viewProj;
  30473. nodeMaterial.colorNode = backgroundMeshNode;
  30474. sceneData.backgroundMeshNode = backgroundMeshNode;
  30475. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  30476. backgroundMesh.frustumCulled = false;
  30477. backgroundMesh.name = 'Background.mesh';
  30478. backgroundMesh.onBeforeRender = function ( renderer, scene, camera ) {
  30479. this.matrixWorld.copyPosition( camera.matrixWorld );
  30480. };
  30481. function onBackgroundDispose() {
  30482. background.removeEventListener( 'dispose', onBackgroundDispose );
  30483. backgroundMesh.material.dispose();
  30484. backgroundMesh.geometry.dispose();
  30485. }
  30486. background.addEventListener( 'dispose', onBackgroundDispose );
  30487. }
  30488. const backgroundCacheKey = backgroundNode.getCacheKey();
  30489. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  30490. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  30491. sceneData.backgroundMeshNode.needsUpdate = true;
  30492. backgroundMesh.material.needsUpdate = true;
  30493. sceneData.backgroundCacheKey = backgroundCacheKey;
  30494. }
  30495. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null, null );
  30496. } else {
  30497. console.error( 'THREE.Renderer: Unsupported background configuration.', background );
  30498. }
  30499. //
  30500. const environmentBlendMode = renderer.xr.getEnvironmentBlendMode();
  30501. if ( environmentBlendMode === 'additive' ) {
  30502. _clearColor.set( 0, 0, 0, 1 );
  30503. } else if ( environmentBlendMode === 'alpha-blend' ) {
  30504. _clearColor.set( 0, 0, 0, 0 );
  30505. }
  30506. //
  30507. if ( renderer.autoClear === true || forceClear === true ) {
  30508. const clearColorValue = renderContext.clearColorValue;
  30509. clearColorValue.r = _clearColor.r;
  30510. clearColorValue.g = _clearColor.g;
  30511. clearColorValue.b = _clearColor.b;
  30512. clearColorValue.a = _clearColor.a;
  30513. // premultiply alpha
  30514. if ( renderer.backend.isWebGLBackend === true || renderer.alpha === true ) {
  30515. clearColorValue.r *= clearColorValue.a;
  30516. clearColorValue.g *= clearColorValue.a;
  30517. clearColorValue.b *= clearColorValue.a;
  30518. }
  30519. //
  30520. renderContext.depthClearValue = renderer._clearDepth;
  30521. renderContext.stencilClearValue = renderer._clearStencil;
  30522. renderContext.clearColor = renderer.autoClearColor === true;
  30523. renderContext.clearDepth = renderer.autoClearDepth === true;
  30524. renderContext.clearStencil = renderer.autoClearStencil === true;
  30525. } else {
  30526. renderContext.clearColor = false;
  30527. renderContext.clearDepth = false;
  30528. renderContext.clearStencil = false;
  30529. }
  30530. }
  30531. }
  30532. let _id$6 = 0;
  30533. /**
  30534. * A bind group represents a collection of bindings and thus a collection
  30535. * or resources. Bind groups are assigned to pipelines to provide them
  30536. * with the required resources (like uniform buffers or textures).
  30537. *
  30538. * @private
  30539. */
  30540. class BindGroup {
  30541. /**
  30542. * Constructs a new bind group.
  30543. *
  30544. * @param {string} name - The bind group's name.
  30545. * @param {Array<Binding>} bindings - An array of bindings.
  30546. * @param {number} index - The group index.
  30547. * @param {Array<Binding>} bindingsReference - An array of reference bindings.
  30548. */
  30549. constructor( name = '', bindings = [], index = 0, bindingsReference = [] ) {
  30550. /**
  30551. * The bind group's name.
  30552. *
  30553. * @type {string}
  30554. */
  30555. this.name = name;
  30556. /**
  30557. * An array of bindings.
  30558. *
  30559. * @type {Array<Binding>}
  30560. */
  30561. this.bindings = bindings;
  30562. /**
  30563. * The group index.
  30564. *
  30565. * @type {number}
  30566. */
  30567. this.index = index;
  30568. /**
  30569. * An array of reference bindings.
  30570. *
  30571. * @type {Array<Binding>}
  30572. */
  30573. this.bindingsReference = bindingsReference;
  30574. /**
  30575. * The group's ID.
  30576. *
  30577. * @type {number}
  30578. */
  30579. this.id = _id$6 ++;
  30580. }
  30581. }
  30582. /**
  30583. * This module represents the state of a node builder after it was
  30584. * used to build the nodes for a render object. The state holds the
  30585. * results of the build for further processing in the renderer.
  30586. *
  30587. * Render objects with identical cache keys share the same node builder state.
  30588. *
  30589. * @private
  30590. */
  30591. class NodeBuilderState {
  30592. /**
  30593. * Constructs a new node builder state.
  30594. *
  30595. * @param {string} vertexShader - The native vertex shader code.
  30596. * @param {string} fragmentShader - The native fragment shader code.
  30597. * @param {string} computeShader - The native compute shader code.
  30598. * @param {Array<NodeAttribute>} nodeAttributes - An array of node attributes.
  30599. * @param {Array<BindGroup>} bindings - An array of bind groups.
  30600. * @param {Array<Node>} updateNodes - An array of nodes that implement their `update()` method.
  30601. * @param {Array<Node>} updateBeforeNodes - An array of nodes that implement their `updateBefore()` method.
  30602. * @param {Array<Node>} updateAfterNodes - An array of nodes that implement their `updateAfter()` method.
  30603. * @param {NodeMaterialObserver} observer - A node material observer.
  30604. * @param {Array<Object>} transforms - An array with transform attribute objects. Only relevant when using compute shaders with WebGL 2.
  30605. */
  30606. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, observer, transforms = [] ) {
  30607. /**
  30608. * The native vertex shader code.
  30609. *
  30610. * @type {string}
  30611. */
  30612. this.vertexShader = vertexShader;
  30613. /**
  30614. * The native fragment shader code.
  30615. *
  30616. * @type {string}
  30617. */
  30618. this.fragmentShader = fragmentShader;
  30619. /**
  30620. * The native compute shader code.
  30621. *
  30622. * @type {string}
  30623. */
  30624. this.computeShader = computeShader;
  30625. /**
  30626. * An array with transform attribute objects.
  30627. * Only relevant when using compute shaders with WebGL 2.
  30628. *
  30629. * @type {Array<Object>}
  30630. */
  30631. this.transforms = transforms;
  30632. /**
  30633. * An array of node attributes representing
  30634. * the attributes of the shaders.
  30635. *
  30636. * @type {Array<NodeAttribute>}
  30637. */
  30638. this.nodeAttributes = nodeAttributes;
  30639. /**
  30640. * An array of bind groups representing the uniform or storage
  30641. * buffers, texture or samplers of the shader.
  30642. *
  30643. * @type {Array<BindGroup>}
  30644. */
  30645. this.bindings = bindings;
  30646. /**
  30647. * An array of nodes that implement their `update()` method.
  30648. *
  30649. * @type {Array<Node>}
  30650. */
  30651. this.updateNodes = updateNodes;
  30652. /**
  30653. * An array of nodes that implement their `updateBefore()` method.
  30654. *
  30655. * @type {Array<Node>}
  30656. */
  30657. this.updateBeforeNodes = updateBeforeNodes;
  30658. /**
  30659. * An array of nodes that implement their `updateAfter()` method.
  30660. *
  30661. * @type {Array<Node>}
  30662. */
  30663. this.updateAfterNodes = updateAfterNodes;
  30664. /**
  30665. * A node material observer.
  30666. *
  30667. * @type {NodeMaterialObserver}
  30668. */
  30669. this.observer = observer;
  30670. /**
  30671. * How often this state is used by render objects.
  30672. *
  30673. * @type {number}
  30674. */
  30675. this.usedTimes = 0;
  30676. }
  30677. /**
  30678. * This method is used to create a array of bind groups based
  30679. * on the existing bind groups of this state. Shared groups are
  30680. * not cloned.
  30681. *
  30682. * @return {Array<BindGroup>} A array of bind groups.
  30683. */
  30684. createBindings() {
  30685. const bindings = [];
  30686. for ( const instanceGroup of this.bindings ) {
  30687. const shared = instanceGroup.bindings[ 0 ].groupNode.shared; // All bindings in the group must have the same groupNode.
  30688. if ( shared !== true ) {
  30689. const bindingsGroup = new BindGroup( instanceGroup.name, [], instanceGroup.index, instanceGroup );
  30690. bindings.push( bindingsGroup );
  30691. for ( const instanceBinding of instanceGroup.bindings ) {
  30692. bindingsGroup.bindings.push( instanceBinding.clone() );
  30693. }
  30694. } else {
  30695. bindings.push( instanceGroup );
  30696. }
  30697. }
  30698. return bindings;
  30699. }
  30700. }
  30701. /**
  30702. * {@link NodeBuilder} is going to create instances of this class during the build process
  30703. * of nodes. They represent the final shader attributes that are going to be generated
  30704. * by the builder. Arrays of node attributes is maintained in {@link NodeBuilder#attributes}
  30705. * and {@link NodeBuilder#bufferAttributes} for this purpose.
  30706. */
  30707. class NodeAttribute {
  30708. /**
  30709. * Constructs a new node attribute.
  30710. *
  30711. * @param {string} name - The name of the attribute.
  30712. * @param {string} type - The type of the attribute.
  30713. * @param {?Node} node - An optional reference to the node.
  30714. */
  30715. constructor( name, type, node = null ) {
  30716. /**
  30717. * This flag can be used for type testing.
  30718. *
  30719. * @type {boolean}
  30720. * @readonly
  30721. * @default true
  30722. */
  30723. this.isNodeAttribute = true;
  30724. /**
  30725. * The name of the attribute.
  30726. *
  30727. * @type {string}
  30728. */
  30729. this.name = name;
  30730. /**
  30731. * The type of the attribute.
  30732. *
  30733. * @type {string}
  30734. */
  30735. this.type = type;
  30736. /**
  30737. * An optional reference to the node.
  30738. *
  30739. * @type {?Node}
  30740. * @default null
  30741. */
  30742. this.node = node;
  30743. }
  30744. }
  30745. /**
  30746. * {@link NodeBuilder} is going to create instances of this class during the build process
  30747. * of nodes. They represent the final shader uniforms that are going to be generated
  30748. * by the builder. A dictionary of node uniforms is maintained in {@link NodeBuilder#uniforms}
  30749. * for this purpose.
  30750. */
  30751. class NodeUniform {
  30752. /**
  30753. * Constructs a new node uniform.
  30754. *
  30755. * @param {string} name - The name of the uniform.
  30756. * @param {string} type - The type of the uniform.
  30757. * @param {UniformNode} node - An reference to the node.
  30758. */
  30759. constructor( name, type, node ) {
  30760. /**
  30761. * This flag can be used for type testing.
  30762. *
  30763. * @type {boolean}
  30764. * @readonly
  30765. * @default true
  30766. */
  30767. this.isNodeUniform = true;
  30768. /**
  30769. * The name of the uniform.
  30770. *
  30771. * @type {string}
  30772. */
  30773. this.name = name;
  30774. /**
  30775. * The type of the uniform.
  30776. *
  30777. * @type {string}
  30778. */
  30779. this.type = type;
  30780. /**
  30781. * An reference to the node.
  30782. *
  30783. * @type {UniformNode}
  30784. */
  30785. this.node = node.getSelf();
  30786. }
  30787. /**
  30788. * The value of the uniform node.
  30789. *
  30790. * @type {any}
  30791. */
  30792. get value() {
  30793. return this.node.value;
  30794. }
  30795. set value( val ) {
  30796. this.node.value = val;
  30797. }
  30798. /**
  30799. * The id of the uniform node.
  30800. *
  30801. * @type {number}
  30802. */
  30803. get id() {
  30804. return this.node.id;
  30805. }
  30806. /**
  30807. * The uniform node's group.
  30808. *
  30809. * @type {UniformGroupNode}
  30810. */
  30811. get groupNode() {
  30812. return this.node.groupNode;
  30813. }
  30814. }
  30815. /**
  30816. * {@link NodeBuilder} is going to create instances of this class during the build process
  30817. * of nodes. They represent the final shader variables that are going to be generated
  30818. * by the builder. A dictionary of node variables is maintained in {@link NodeBuilder#vars} for
  30819. * this purpose.
  30820. */
  30821. class NodeVar {
  30822. /**
  30823. * Constructs a new node variable.
  30824. *
  30825. * @param {string} name - The name of the variable.
  30826. * @param {string} type - The type of the variable.
  30827. * @param {boolean} [readOnly=false] - The read-only flag.
  30828. * @param {?number} [count=null] - The size.
  30829. */
  30830. constructor( name, type, readOnly = false, count = null ) {
  30831. /**
  30832. * This flag can be used for type testing.
  30833. *
  30834. * @type {boolean}
  30835. * @readonly
  30836. * @default true
  30837. */
  30838. this.isNodeVar = true;
  30839. /**
  30840. * The name of the variable.
  30841. *
  30842. * @type {string}
  30843. */
  30844. this.name = name;
  30845. /**
  30846. * The type of the variable.
  30847. *
  30848. * @type {string}
  30849. */
  30850. this.type = type;
  30851. /**
  30852. * The read-only flag.
  30853. *
  30854. * @type {boolean}
  30855. */
  30856. this.readOnly = readOnly;
  30857. /**
  30858. * The size.
  30859. *
  30860. * @type {?number}
  30861. */
  30862. this.count = count;
  30863. }
  30864. }
  30865. /**
  30866. * {@link NodeBuilder} is going to create instances of this class during the build process
  30867. * of nodes. They represent the final shader varyings that are going to be generated
  30868. * by the builder. An array of node varyings is maintained in {@link NodeBuilder#varyings} for
  30869. * this purpose.
  30870. *
  30871. * @augments NodeVar
  30872. */
  30873. class NodeVarying extends NodeVar {
  30874. /**
  30875. * Constructs a new node varying.
  30876. *
  30877. * @param {string} name - The name of the varying.
  30878. * @param {string} type - The type of the varying.
  30879. * @param {?string} interpolationType - The interpolation type of the varying.
  30880. * @param {?string} interpolationSampling - The interpolation sampling type of the varying.
  30881. */
  30882. constructor( name, type, interpolationType = null, interpolationSampling = null ) {
  30883. super( name, type );
  30884. /**
  30885. * Whether this varying requires interpolation or not. This property can be used
  30886. * to check if the varying can be optimized for a variable.
  30887. *
  30888. * @type {boolean}
  30889. * @default false
  30890. */
  30891. this.needsInterpolation = false;
  30892. /**
  30893. * This flag can be used for type testing.
  30894. *
  30895. * @type {boolean}
  30896. * @readonly
  30897. * @default true
  30898. */
  30899. this.isNodeVarying = true;
  30900. /**
  30901. * The interpolation type of the varying data.
  30902. *
  30903. * @type {?string}
  30904. * @default null
  30905. */
  30906. this.interpolationType = interpolationType;
  30907. /**
  30908. * The interpolation sampling type of varying data.
  30909. *
  30910. * @type {?string}
  30911. * @default null
  30912. */
  30913. this.interpolationSampling = interpolationSampling;
  30914. }
  30915. }
  30916. /**
  30917. * {@link NodeBuilder} is going to create instances of this class during the build process
  30918. * of nodes. They represent user-defined, native shader code portions that are going to be
  30919. * injected by the builder. A dictionary of node codes is maintained in {@link NodeBuilder#codes}
  30920. * for this purpose.
  30921. */
  30922. class NodeCode {
  30923. /**
  30924. * Constructs a new code node.
  30925. *
  30926. * @param {string} name - The name of the code.
  30927. * @param {string} type - The node type.
  30928. * @param {string} [code=''] - The native shader code.
  30929. */
  30930. constructor( name, type, code = '' ) {
  30931. /**
  30932. * The name of the code.
  30933. *
  30934. * @type {string}
  30935. */
  30936. this.name = name;
  30937. /**
  30938. * The node type.
  30939. *
  30940. * @type {string}
  30941. */
  30942. this.type = type;
  30943. /**
  30944. * The native shader code.
  30945. *
  30946. * @type {string}
  30947. * @default ''
  30948. */
  30949. this.code = code;
  30950. Object.defineProperty( this, 'isNodeCode', { value: true } );
  30951. }
  30952. }
  30953. let _id$5 = 0;
  30954. /**
  30955. * This utility class is used in {@link NodeBuilder} as an internal
  30956. * cache data structure for node data.
  30957. */
  30958. class NodeCache {
  30959. /**
  30960. * Constructs a new node cache.
  30961. *
  30962. * @param {?NodeCache} parent - A reference to a parent cache.
  30963. */
  30964. constructor( parent = null ) {
  30965. /**
  30966. * The id of the cache.
  30967. *
  30968. * @type {number}
  30969. * @readonly
  30970. */
  30971. this.id = _id$5 ++;
  30972. /**
  30973. * A weak map for managing node data.
  30974. *
  30975. * @type {WeakMap<Node, Object>}
  30976. */
  30977. this.nodesData = new WeakMap();
  30978. /**
  30979. * Reference to a parent node cache.
  30980. *
  30981. * @type {?NodeCache}
  30982. * @default null
  30983. */
  30984. this.parent = parent;
  30985. }
  30986. /**
  30987. * Returns the data for the given node.
  30988. *
  30989. * @param {Node} node - The node.
  30990. * @return {?Object} The data for the node.
  30991. */
  30992. getData( node ) {
  30993. let data = this.nodesData.get( node );
  30994. if ( data === undefined && this.parent !== null ) {
  30995. data = this.parent.getData( node );
  30996. }
  30997. return data;
  30998. }
  30999. /**
  31000. * Sets the data for a given node.
  31001. *
  31002. * @param {Node} node - The node.
  31003. * @param {Object} data - The data that should be cached.
  31004. */
  31005. setData( node, data ) {
  31006. this.nodesData.set( node, data );
  31007. }
  31008. }
  31009. class StructType {
  31010. constructor( name, members ) {
  31011. this.name = name;
  31012. this.members = members;
  31013. this.output = false;
  31014. }
  31015. }
  31016. /**
  31017. * Abstract base class for uniforms.
  31018. *
  31019. * @abstract
  31020. * @private
  31021. */
  31022. class Uniform {
  31023. /**
  31024. * Constructs a new uniform.
  31025. *
  31026. * @param {string} name - The uniform's name.
  31027. * @param {any} value - The uniform's value.
  31028. */
  31029. constructor( name, value ) {
  31030. /**
  31031. * The uniform's name.
  31032. *
  31033. * @type {string}
  31034. */
  31035. this.name = name;
  31036. /**
  31037. * The uniform's value.
  31038. *
  31039. * @type {any}
  31040. */
  31041. this.value = value;
  31042. /**
  31043. * Used to build the uniform buffer according to the STD140 layout.
  31044. * Derived uniforms will set this property to a data type specific
  31045. * value.
  31046. *
  31047. * @type {number}
  31048. */
  31049. this.boundary = 0;
  31050. /**
  31051. * The item size. Derived uniforms will set this property to a data
  31052. * type specific value.
  31053. *
  31054. * @type {number}
  31055. */
  31056. this.itemSize = 0;
  31057. /**
  31058. * This property is set by {@link UniformsGroup} and marks
  31059. * the start position in the uniform buffer.
  31060. *
  31061. * @type {number}
  31062. */
  31063. this.offset = 0;
  31064. }
  31065. /**
  31066. * Sets the uniform's value.
  31067. *
  31068. * @param {any} value - The value to set.
  31069. */
  31070. setValue( value ) {
  31071. this.value = value;
  31072. }
  31073. /**
  31074. * Returns the uniform's value.
  31075. *
  31076. * @return {any} The value.
  31077. */
  31078. getValue() {
  31079. return this.value;
  31080. }
  31081. }
  31082. /**
  31083. * Represents a Number uniform.
  31084. *
  31085. * @private
  31086. * @augments Uniform
  31087. */
  31088. class NumberUniform extends Uniform {
  31089. /**
  31090. * Constructs a new Number uniform.
  31091. *
  31092. * @param {string} name - The uniform's name.
  31093. * @param {number} value - The uniform's value.
  31094. */
  31095. constructor( name, value = 0 ) {
  31096. super( name, value );
  31097. /**
  31098. * This flag can be used for type testing.
  31099. *
  31100. * @type {boolean}
  31101. * @readonly
  31102. * @default true
  31103. */
  31104. this.isNumberUniform = true;
  31105. this.boundary = 4;
  31106. this.itemSize = 1;
  31107. }
  31108. }
  31109. /**
  31110. * Represents a Vector2 uniform.
  31111. *
  31112. * @private
  31113. * @augments Uniform
  31114. */
  31115. class Vector2Uniform extends Uniform {
  31116. /**
  31117. * Constructs a new Number uniform.
  31118. *
  31119. * @param {string} name - The uniform's name.
  31120. * @param {Vector2} value - The uniform's value.
  31121. */
  31122. constructor( name, value = new Vector2() ) {
  31123. super( name, value );
  31124. /**
  31125. * This flag can be used for type testing.
  31126. *
  31127. * @type {boolean}
  31128. * @readonly
  31129. * @default true
  31130. */
  31131. this.isVector2Uniform = true;
  31132. this.boundary = 8;
  31133. this.itemSize = 2;
  31134. }
  31135. }
  31136. /**
  31137. * Represents a Vector3 uniform.
  31138. *
  31139. * @private
  31140. * @augments Uniform
  31141. */
  31142. class Vector3Uniform extends Uniform {
  31143. /**
  31144. * Constructs a new Number uniform.
  31145. *
  31146. * @param {string} name - The uniform's name.
  31147. * @param {Vector3} value - The uniform's value.
  31148. */
  31149. constructor( name, value = new Vector3() ) {
  31150. super( name, value );
  31151. /**
  31152. * This flag can be used for type testing.
  31153. *
  31154. * @type {boolean}
  31155. * @readonly
  31156. * @default true
  31157. */
  31158. this.isVector3Uniform = true;
  31159. this.boundary = 16;
  31160. this.itemSize = 3;
  31161. }
  31162. }
  31163. /**
  31164. * Represents a Vector4 uniform.
  31165. *
  31166. * @private
  31167. * @augments Uniform
  31168. */
  31169. class Vector4Uniform extends Uniform {
  31170. /**
  31171. * Constructs a new Number uniform.
  31172. *
  31173. * @param {string} name - The uniform's name.
  31174. * @param {Vector4} value - The uniform's value.
  31175. */
  31176. constructor( name, value = new Vector4() ) {
  31177. super( name, value );
  31178. /**
  31179. * This flag can be used for type testing.
  31180. *
  31181. * @type {boolean}
  31182. * @readonly
  31183. * @default true
  31184. */
  31185. this.isVector4Uniform = true;
  31186. this.boundary = 16;
  31187. this.itemSize = 4;
  31188. }
  31189. }
  31190. /**
  31191. * Represents a Color uniform.
  31192. *
  31193. * @private
  31194. * @augments Uniform
  31195. */
  31196. class ColorUniform extends Uniform {
  31197. /**
  31198. * Constructs a new Number uniform.
  31199. *
  31200. * @param {string} name - The uniform's name.
  31201. * @param {Color} value - The uniform's value.
  31202. */
  31203. constructor( name, value = new Color() ) {
  31204. super( name, value );
  31205. /**
  31206. * This flag can be used for type testing.
  31207. *
  31208. * @type {boolean}
  31209. * @readonly
  31210. * @default true
  31211. */
  31212. this.isColorUniform = true;
  31213. this.boundary = 16;
  31214. this.itemSize = 3;
  31215. }
  31216. }
  31217. /**
  31218. * Represents a Matrix2 uniform.
  31219. *
  31220. * @private
  31221. * @augments Uniform
  31222. */
  31223. class Matrix2Uniform extends Uniform {
  31224. /**
  31225. * Constructs a new Number uniform.
  31226. *
  31227. * @param {string} name - The uniform's name.
  31228. * @param {Matrix2} value - The uniform's value.
  31229. */
  31230. constructor( name, value = new Matrix2() ) {
  31231. super( name, value );
  31232. /**
  31233. * This flag can be used for type testing.
  31234. *
  31235. * @type {boolean}
  31236. * @readonly
  31237. * @default true
  31238. */
  31239. this.isMatrix2Uniform = true;
  31240. this.boundary = 8;
  31241. this.itemSize = 4;
  31242. }
  31243. }
  31244. /**
  31245. * Represents a Matrix3 uniform.
  31246. *
  31247. * @private
  31248. * @augments Uniform
  31249. */
  31250. class Matrix3Uniform extends Uniform {
  31251. /**
  31252. * Constructs a new Number uniform.
  31253. *
  31254. * @param {string} name - The uniform's name.
  31255. * @param {Matrix3} value - The uniform's value.
  31256. */
  31257. constructor( name, value = new Matrix3() ) {
  31258. super( name, value );
  31259. /**
  31260. * This flag can be used for type testing.
  31261. *
  31262. * @type {boolean}
  31263. * @readonly
  31264. * @default true
  31265. */
  31266. this.isMatrix3Uniform = true;
  31267. this.boundary = 48;
  31268. this.itemSize = 12;
  31269. }
  31270. }
  31271. /**
  31272. * Represents a Matrix4 uniform.
  31273. *
  31274. * @private
  31275. * @augments Uniform
  31276. */
  31277. class Matrix4Uniform extends Uniform {
  31278. /**
  31279. * Constructs a new Number uniform.
  31280. *
  31281. * @param {string} name - The uniform's name.
  31282. * @param {Matrix4} value - The uniform's value.
  31283. */
  31284. constructor( name, value = new Matrix4() ) {
  31285. super( name, value );
  31286. /**
  31287. * This flag can be used for type testing.
  31288. *
  31289. * @type {boolean}
  31290. * @readonly
  31291. * @default true
  31292. */
  31293. this.isMatrix4Uniform = true;
  31294. this.boundary = 64;
  31295. this.itemSize = 16;
  31296. }
  31297. }
  31298. /**
  31299. * A special form of Number uniform binding type.
  31300. * It's value is managed by a node object.
  31301. *
  31302. * @private
  31303. * @augments NumberUniform
  31304. */
  31305. class NumberNodeUniform extends NumberUniform {
  31306. /**
  31307. * Constructs a new node-based Number uniform.
  31308. *
  31309. * @param {NodeUniform} nodeUniform - The node uniform.
  31310. */
  31311. constructor( nodeUniform ) {
  31312. super( nodeUniform.name, nodeUniform.value );
  31313. /**
  31314. * The node uniform.
  31315. *
  31316. * @type {NodeUniform}
  31317. */
  31318. this.nodeUniform = nodeUniform;
  31319. }
  31320. /**
  31321. * Overwritten to return the value of the node uniform.
  31322. *
  31323. * @return {number} The value.
  31324. */
  31325. getValue() {
  31326. return this.nodeUniform.value;
  31327. }
  31328. /**
  31329. * Returns the node uniform data type.
  31330. *
  31331. * @return {string} The data type.
  31332. */
  31333. getType() {
  31334. return this.nodeUniform.type;
  31335. }
  31336. }
  31337. /**
  31338. * A special form of Vector2 uniform binding type.
  31339. * It's value is managed by a node object.
  31340. *
  31341. * @private
  31342. * @augments Vector2Uniform
  31343. */
  31344. class Vector2NodeUniform extends Vector2Uniform {
  31345. /**
  31346. * Constructs a new node-based Vector2 uniform.
  31347. *
  31348. * @param {NodeUniform} nodeUniform - The node uniform.
  31349. */
  31350. constructor( nodeUniform ) {
  31351. super( nodeUniform.name, nodeUniform.value );
  31352. /**
  31353. * The node uniform.
  31354. *
  31355. * @type {NodeUniform}
  31356. */
  31357. this.nodeUniform = nodeUniform;
  31358. }
  31359. /**
  31360. * Overwritten to return the value of the node uniform.
  31361. *
  31362. * @return {Vector2} The value.
  31363. */
  31364. getValue() {
  31365. return this.nodeUniform.value;
  31366. }
  31367. /**
  31368. * Returns the node uniform data type.
  31369. *
  31370. * @return {string} The data type.
  31371. */
  31372. getType() {
  31373. return this.nodeUniform.type;
  31374. }
  31375. }
  31376. /**
  31377. * A special form of Vector3 uniform binding type.
  31378. * It's value is managed by a node object.
  31379. *
  31380. * @private
  31381. * @augments Vector3Uniform
  31382. */
  31383. class Vector3NodeUniform extends Vector3Uniform {
  31384. /**
  31385. * Constructs a new node-based Vector3 uniform.
  31386. *
  31387. * @param {NodeUniform} nodeUniform - The node uniform.
  31388. */
  31389. constructor( nodeUniform ) {
  31390. super( nodeUniform.name, nodeUniform.value );
  31391. /**
  31392. * The node uniform.
  31393. *
  31394. * @type {NodeUniform}
  31395. */
  31396. this.nodeUniform = nodeUniform;
  31397. }
  31398. /**
  31399. * Overwritten to return the value of the node uniform.
  31400. *
  31401. * @return {Vector3} The value.
  31402. */
  31403. getValue() {
  31404. return this.nodeUniform.value;
  31405. }
  31406. /**
  31407. * Returns the node uniform data type.
  31408. *
  31409. * @return {string} The data type.
  31410. */
  31411. getType() {
  31412. return this.nodeUniform.type;
  31413. }
  31414. }
  31415. /**
  31416. * A special form of Vector4 uniform binding type.
  31417. * It's value is managed by a node object.
  31418. *
  31419. * @private
  31420. * @augments Vector4Uniform
  31421. */
  31422. class Vector4NodeUniform extends Vector4Uniform {
  31423. /**
  31424. * Constructs a new node-based Vector4 uniform.
  31425. *
  31426. * @param {NodeUniform} nodeUniform - The node uniform.
  31427. */
  31428. constructor( nodeUniform ) {
  31429. super( nodeUniform.name, nodeUniform.value );
  31430. /**
  31431. * The node uniform.
  31432. *
  31433. * @type {NodeUniform}
  31434. */
  31435. this.nodeUniform = nodeUniform;
  31436. }
  31437. /**
  31438. * Overwritten to return the value of the node uniform.
  31439. *
  31440. * @return {Vector4} The value.
  31441. */
  31442. getValue() {
  31443. return this.nodeUniform.value;
  31444. }
  31445. /**
  31446. * Returns the node uniform data type.
  31447. *
  31448. * @return {string} The data type.
  31449. */
  31450. getType() {
  31451. return this.nodeUniform.type;
  31452. }
  31453. }
  31454. /**
  31455. * A special form of Color uniform binding type.
  31456. * It's value is managed by a node object.
  31457. *
  31458. * @private
  31459. * @augments ColorUniform
  31460. */
  31461. class ColorNodeUniform extends ColorUniform {
  31462. /**
  31463. * Constructs a new node-based Color uniform.
  31464. *
  31465. * @param {NodeUniform} nodeUniform - The node uniform.
  31466. */
  31467. constructor( nodeUniform ) {
  31468. super( nodeUniform.name, nodeUniform.value );
  31469. /**
  31470. * The node uniform.
  31471. *
  31472. * @type {NodeUniform}
  31473. */
  31474. this.nodeUniform = nodeUniform;
  31475. }
  31476. /**
  31477. * Overwritten to return the value of the node uniform.
  31478. *
  31479. * @return {Color} The value.
  31480. */
  31481. getValue() {
  31482. return this.nodeUniform.value;
  31483. }
  31484. /**
  31485. * Returns the node uniform data type.
  31486. *
  31487. * @return {string} The data type.
  31488. */
  31489. getType() {
  31490. return this.nodeUniform.type;
  31491. }
  31492. }
  31493. /**
  31494. * A special form of Matrix2 uniform binding type.
  31495. * It's value is managed by a node object.
  31496. *
  31497. * @private
  31498. * @augments Matrix2Uniform
  31499. */
  31500. class Matrix2NodeUniform extends Matrix2Uniform {
  31501. /**
  31502. * Constructs a new node-based Matrix2 uniform.
  31503. *
  31504. * @param {NodeUniform} nodeUniform - The node uniform.
  31505. */
  31506. constructor( nodeUniform ) {
  31507. super( nodeUniform.name, nodeUniform.value );
  31508. /**
  31509. * The node uniform.
  31510. *
  31511. * @type {NodeUniform}
  31512. */
  31513. this.nodeUniform = nodeUniform;
  31514. }
  31515. /**
  31516. * Overwritten to return the value of the node uniform.
  31517. *
  31518. * @return {Matrix2} The value.
  31519. */
  31520. getValue() {
  31521. return this.nodeUniform.value;
  31522. }
  31523. /**
  31524. * Returns the node uniform data type.
  31525. *
  31526. * @return {string} The data type.
  31527. */
  31528. getType() {
  31529. return this.nodeUniform.type;
  31530. }
  31531. }
  31532. /**
  31533. * A special form of Matrix3 uniform binding type.
  31534. * It's value is managed by a node object.
  31535. *
  31536. * @private
  31537. * @augments Matrix3Uniform
  31538. */
  31539. class Matrix3NodeUniform extends Matrix3Uniform {
  31540. /**
  31541. * Constructs a new node-based Matrix3 uniform.
  31542. *
  31543. * @param {NodeUniform} nodeUniform - The node uniform.
  31544. */
  31545. constructor( nodeUniform ) {
  31546. super( nodeUniform.name, nodeUniform.value );
  31547. /**
  31548. * The node uniform.
  31549. *
  31550. * @type {NodeUniform}
  31551. */
  31552. this.nodeUniform = nodeUniform;
  31553. }
  31554. /**
  31555. * Overwritten to return the value of the node uniform.
  31556. *
  31557. * @return {Matrix3} The value.
  31558. */
  31559. getValue() {
  31560. return this.nodeUniform.value;
  31561. }
  31562. /**
  31563. * Returns the node uniform data type.
  31564. *
  31565. * @return {string} The data type.
  31566. */
  31567. getType() {
  31568. return this.nodeUniform.type;
  31569. }
  31570. }
  31571. /**
  31572. * A special form of Matrix4 uniform binding type.
  31573. * It's value is managed by a node object.
  31574. *
  31575. * @private
  31576. * @augments Matrix4Uniform
  31577. */
  31578. class Matrix4NodeUniform extends Matrix4Uniform {
  31579. /**
  31580. * Constructs a new node-based Matrix4 uniform.
  31581. *
  31582. * @param {NodeUniform} nodeUniform - The node uniform.
  31583. */
  31584. constructor( nodeUniform ) {
  31585. super( nodeUniform.name, nodeUniform.value );
  31586. /**
  31587. * The node uniform.
  31588. *
  31589. * @type {NodeUniform}
  31590. */
  31591. this.nodeUniform = nodeUniform;
  31592. }
  31593. /**
  31594. * Overwritten to return the value of the node uniform.
  31595. *
  31596. * @return {Matrix4} The value.
  31597. */
  31598. getValue() {
  31599. return this.nodeUniform.value;
  31600. }
  31601. /**
  31602. * Returns the node uniform data type.
  31603. *
  31604. * @return {string} The data type.
  31605. */
  31606. getType() {
  31607. return this.nodeUniform.type;
  31608. }
  31609. }
  31610. const rendererCache = new WeakMap();
  31611. const typeFromArray = new Map( [
  31612. [ Int8Array, 'int' ],
  31613. [ Int16Array, 'int' ],
  31614. [ Int32Array, 'int' ],
  31615. [ Uint8Array, 'uint' ],
  31616. [ Uint16Array, 'uint' ],
  31617. [ Uint32Array, 'uint' ],
  31618. [ Float32Array, 'float' ]
  31619. ] );
  31620. const toFloat = ( value ) => {
  31621. if ( /e/g.test( value ) ) {
  31622. return String( value ).replace( /\+/g, '' );
  31623. } else {
  31624. value = Number( value );
  31625. return value + ( value % 1 ? '' : '.0' );
  31626. }
  31627. };
  31628. /**
  31629. * Base class for builders which generate a shader program based
  31630. * on a 3D object and its node material definition.
  31631. */
  31632. class NodeBuilder {
  31633. /**
  31634. * Constructs a new node builder.
  31635. *
  31636. * @param {Object3D} object - The 3D object.
  31637. * @param {Renderer} renderer - The current renderer.
  31638. * @param {NodeParser} parser - A reference to a node parser.
  31639. */
  31640. constructor( object, renderer, parser ) {
  31641. /**
  31642. * The 3D object.
  31643. *
  31644. * @type {Object3D}
  31645. */
  31646. this.object = object;
  31647. /**
  31648. * The material of the 3D object.
  31649. *
  31650. * @type {?Material}
  31651. */
  31652. this.material = ( object && object.material ) || null;
  31653. /**
  31654. * The geometry of the 3D object.
  31655. *
  31656. * @type {?BufferGeometry}
  31657. */
  31658. this.geometry = ( object && object.geometry ) || null;
  31659. /**
  31660. * The current renderer.
  31661. *
  31662. * @type {Renderer}
  31663. */
  31664. this.renderer = renderer;
  31665. /**
  31666. * A reference to a node parser.
  31667. *
  31668. * @type {NodeParser}
  31669. */
  31670. this.parser = parser;
  31671. /**
  31672. * The scene the 3D object belongs to.
  31673. *
  31674. * @type {?Scene}
  31675. * @default null
  31676. */
  31677. this.scene = null;
  31678. /**
  31679. * The camera the 3D object is rendered with.
  31680. *
  31681. * @type {?Camera}
  31682. * @default null
  31683. */
  31684. this.camera = null;
  31685. /**
  31686. * A list of all nodes the builder is processing
  31687. * for this 3D object.
  31688. *
  31689. * @type {Array<Node>}
  31690. */
  31691. this.nodes = [];
  31692. /**
  31693. * A list of all sequential nodes.
  31694. *
  31695. * @type {Array<Node>}
  31696. */
  31697. this.sequentialNodes = [];
  31698. /**
  31699. * A list of all nodes which {@link Node#update} method should be executed.
  31700. *
  31701. * @type {Array<Node>}
  31702. */
  31703. this.updateNodes = [];
  31704. /**
  31705. * A list of all nodes which {@link Node#updateBefore} method should be executed.
  31706. *
  31707. * @type {Array<Node>}
  31708. */
  31709. this.updateBeforeNodes = [];
  31710. /**
  31711. * A list of all nodes which {@link Node#updateAfter} method should be executed.
  31712. *
  31713. * @type {Array<Node>}
  31714. */
  31715. this.updateAfterNodes = [];
  31716. /**
  31717. * A dictionary that assigns each node to a unique hash.
  31718. *
  31719. * @type {Object<number,Node>}
  31720. */
  31721. this.hashNodes = {};
  31722. /**
  31723. * A reference to a node material observer.
  31724. *
  31725. * @type {?NodeMaterialObserver}
  31726. * @default null
  31727. */
  31728. this.observer = null;
  31729. /**
  31730. * A reference to the current lights node.
  31731. *
  31732. * @type {?LightsNode}
  31733. * @default null
  31734. */
  31735. this.lightsNode = null;
  31736. /**
  31737. * A reference to the current environment node.
  31738. *
  31739. * @type {?Node}
  31740. * @default null
  31741. */
  31742. this.environmentNode = null;
  31743. /**
  31744. * A reference to the current fog node.
  31745. *
  31746. * @type {?FogNode}
  31747. * @default null
  31748. */
  31749. this.fogNode = null;
  31750. /**
  31751. * The current clipping context.
  31752. *
  31753. * @type {?ClippingContext}
  31754. */
  31755. this.clippingContext = null;
  31756. /**
  31757. * The generated vertex shader.
  31758. *
  31759. * @type {?string}
  31760. */
  31761. this.vertexShader = null;
  31762. /**
  31763. * The generated fragment shader.
  31764. *
  31765. * @type {?string}
  31766. */
  31767. this.fragmentShader = null;
  31768. /**
  31769. * The generated compute shader.
  31770. *
  31771. * @type {?string}
  31772. */
  31773. this.computeShader = null;
  31774. /**
  31775. * Nodes used in the primary flow of code generation.
  31776. *
  31777. * @type {Object<string,Array<Node>>}
  31778. */
  31779. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  31780. /**
  31781. * Nodes code from `.flowNodes`.
  31782. *
  31783. * @type {Object<string,string>}
  31784. */
  31785. this.flowCode = { vertex: '', fragment: '', compute: '' };
  31786. /**
  31787. * This dictionary holds the node uniforms of the builder.
  31788. * The uniforms are maintained in an array for each shader stage.
  31789. *
  31790. * @type {Object}
  31791. */
  31792. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  31793. /**
  31794. * This dictionary holds the output structs of the builder.
  31795. * The structs are maintained in an array for each shader stage.
  31796. *
  31797. * @type {Object}
  31798. */
  31799. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  31800. /**
  31801. * This dictionary holds the bindings for each shader stage.
  31802. *
  31803. * @type {Object}
  31804. */
  31805. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  31806. /**
  31807. * This dictionary maintains the binding indices per bind group.
  31808. *
  31809. * @type {Object}
  31810. */
  31811. this.bindingsIndexes = {};
  31812. /**
  31813. * Reference to the array of bind groups.
  31814. *
  31815. * @type {?Array<BindGroup>}
  31816. */
  31817. this.bindGroups = null;
  31818. /**
  31819. * This array holds the node attributes of this builder
  31820. * created via {@link AttributeNode}.
  31821. *
  31822. * @type {Array<NodeAttribute>}
  31823. */
  31824. this.attributes = [];
  31825. /**
  31826. * This array holds the node attributes of this builder
  31827. * created via {@link BufferAttributeNode}.
  31828. *
  31829. * @type {Array<NodeAttribute>}
  31830. */
  31831. this.bufferAttributes = [];
  31832. /**
  31833. * This array holds the node varyings of this builder.
  31834. *
  31835. * @type {Array<NodeVarying>}
  31836. */
  31837. this.varyings = [];
  31838. /**
  31839. * This dictionary holds the (native) node codes of this builder.
  31840. * The codes are maintained in an array for each shader stage.
  31841. *
  31842. * @type {Object<string,Array<NodeCode>>}
  31843. */
  31844. this.codes = {};
  31845. /**
  31846. * This dictionary holds the node variables of this builder.
  31847. * The variables are maintained in an array for each shader stage.
  31848. * This dictionary is also used to count the number of variables
  31849. * according to their type (const, vars).
  31850. *
  31851. * @type {Object<string,Array<NodeVar>|number>}
  31852. */
  31853. this.vars = {};
  31854. /**
  31855. * This dictionary holds the declarations for each shader stage.
  31856. *
  31857. * @type {Object}
  31858. */
  31859. this.declarations = {};
  31860. /**
  31861. * Current code flow.
  31862. * All code generated in this stack will be stored in `.flow`.
  31863. *
  31864. * @type {{code: string}}
  31865. */
  31866. this.flow = { code: '' };
  31867. /**
  31868. * A chain of nodes.
  31869. * Used to check recursive calls in node-graph.
  31870. *
  31871. * @type {Array<Node>}
  31872. */
  31873. this.chaining = [];
  31874. /**
  31875. * The current stack.
  31876. * This reflects the current process in the code block hierarchy,
  31877. * it is useful to know if the current process is inside a conditional for example.
  31878. *
  31879. * @type {StackNode}
  31880. */
  31881. this.stack = stack();
  31882. /**
  31883. * List of stack nodes.
  31884. * The current stack hierarchy is stored in an array.
  31885. *
  31886. * @type {Array<StackNode>}
  31887. */
  31888. this.stacks = [];
  31889. /**
  31890. * A tab value. Used for shader string generation.
  31891. *
  31892. * @type {string}
  31893. * @default '\t'
  31894. */
  31895. this.tab = '\t';
  31896. /**
  31897. * Reference to the current function node.
  31898. *
  31899. * @type {?FunctionNode}
  31900. * @default null
  31901. */
  31902. this.currentFunctionNode = null;
  31903. /**
  31904. * The builder's context.
  31905. *
  31906. * @type {Object}
  31907. */
  31908. this.context = {
  31909. material: this.material
  31910. };
  31911. /**
  31912. * The builder's cache.
  31913. *
  31914. * @type {NodeCache}
  31915. */
  31916. this.cache = new NodeCache();
  31917. /**
  31918. * Since the {@link NodeBuilder#cache} might be temporarily
  31919. * overwritten by other caches, this member retains the reference
  31920. * to the builder's own cache.
  31921. *
  31922. * @type {NodeCache}
  31923. * @default this.cache
  31924. */
  31925. this.globalCache = this.cache;
  31926. this.flowsData = new WeakMap();
  31927. /**
  31928. * The current shader stage.
  31929. *
  31930. * @type {?('vertex'|'fragment'|'compute'|'any')}
  31931. */
  31932. this.shaderStage = null;
  31933. /**
  31934. * The current build stage.
  31935. *
  31936. * @type {?('setup'|'analyze'|'generate')}
  31937. */
  31938. this.buildStage = null;
  31939. }
  31940. /**
  31941. * Returns the bind groups of the current renderer.
  31942. *
  31943. * @return {ChainMap} The cache.
  31944. */
  31945. getBindGroupsCache() {
  31946. let bindGroupsCache = rendererCache.get( this.renderer );
  31947. if ( bindGroupsCache === undefined ) {
  31948. bindGroupsCache = new ChainMap();
  31949. rendererCache.set( this.renderer, bindGroupsCache );
  31950. }
  31951. return bindGroupsCache;
  31952. }
  31953. /**
  31954. * Factory method for creating an instance of {@link RenderTarget} with the given
  31955. * dimensions and options.
  31956. *
  31957. * @param {number} width - The width of the render target.
  31958. * @param {number} height - The height of the render target.
  31959. * @param {Object} options - The options of the render target.
  31960. * @return {RenderTarget} The render target.
  31961. */
  31962. createRenderTarget( width, height, options ) {
  31963. return new RenderTarget( width, height, options );
  31964. }
  31965. /**
  31966. * Factory method for creating an instance of {@link CubeRenderTarget} with the given
  31967. * dimensions and options.
  31968. *
  31969. * @param {number} size - The size of the cube render target.
  31970. * @param {Object} options - The options of the cube render target.
  31971. * @return {CubeRenderTarget} The cube render target.
  31972. */
  31973. createCubeRenderTarget( size, options ) {
  31974. return new CubeRenderTarget( size, options );
  31975. }
  31976. /**
  31977. * Whether the given node is included in the internal array of nodes or not.
  31978. *
  31979. * @param {Node} node - The node to test.
  31980. * @return {boolean} Whether the given node is included in the internal array of nodes or not.
  31981. */
  31982. includes( node ) {
  31983. return this.nodes.includes( node );
  31984. }
  31985. /**
  31986. * Returns the output struct name which is required by
  31987. * {@link OutputStructNode}.
  31988. *
  31989. * @abstract
  31990. * @return {string} The name of the output struct.
  31991. */
  31992. getOutputStructName() {}
  31993. /**
  31994. * Returns a bind group for the given group name and binding.
  31995. *
  31996. * @private
  31997. * @param {string} groupName - The group name.
  31998. * @param {Array<NodeUniformsGroup>} bindings - List of bindings.
  31999. * @return {BindGroup} The bind group
  32000. */
  32001. _getBindGroup( groupName, bindings ) {
  32002. const bindGroupsCache = this.getBindGroupsCache();
  32003. //
  32004. const bindingsArray = [];
  32005. let sharedGroup = true;
  32006. for ( const binding of bindings ) {
  32007. bindingsArray.push( binding );
  32008. sharedGroup = sharedGroup && binding.groupNode.shared !== true;
  32009. }
  32010. //
  32011. let bindGroup;
  32012. if ( sharedGroup ) {
  32013. bindGroup = bindGroupsCache.get( bindingsArray );
  32014. if ( bindGroup === undefined ) {
  32015. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  32016. bindGroupsCache.set( bindingsArray, bindGroup );
  32017. }
  32018. } else {
  32019. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  32020. }
  32021. return bindGroup;
  32022. }
  32023. /**
  32024. * Returns an array of node uniform groups for the given group name and shader stage.
  32025. *
  32026. * @param {string} groupName - The group name.
  32027. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  32028. * @return {Array<NodeUniformsGroup>} The array of node uniform groups.
  32029. */
  32030. getBindGroupArray( groupName, shaderStage ) {
  32031. const bindings = this.bindings[ shaderStage ];
  32032. let bindGroup = bindings[ groupName ];
  32033. if ( bindGroup === undefined ) {
  32034. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  32035. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  32036. }
  32037. bindings[ groupName ] = bindGroup = [];
  32038. }
  32039. return bindGroup;
  32040. }
  32041. /**
  32042. * Returns a list bindings of all shader stages separated by groups.
  32043. *
  32044. * @return {Array<BindGroup>} The list of bindings.
  32045. */
  32046. getBindings() {
  32047. let bindingsGroups = this.bindGroups;
  32048. if ( bindingsGroups === null ) {
  32049. const groups = {};
  32050. const bindings = this.bindings;
  32051. for ( const shaderStage of shaderStages ) {
  32052. for ( const groupName in bindings[ shaderStage ] ) {
  32053. const uniforms = bindings[ shaderStage ][ groupName ];
  32054. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  32055. groupUniforms.push( ...uniforms );
  32056. }
  32057. }
  32058. bindingsGroups = [];
  32059. for ( const groupName in groups ) {
  32060. const group = groups[ groupName ];
  32061. const bindingsGroup = this._getBindGroup( groupName, group );
  32062. bindingsGroups.push( bindingsGroup );
  32063. }
  32064. this.bindGroups = bindingsGroups;
  32065. }
  32066. return bindingsGroups;
  32067. }
  32068. /**
  32069. * Sorts the bind groups and updates {@link NodeBuilder#bindingsIndexes}.
  32070. */
  32071. sortBindingGroups() {
  32072. const bindingsGroups = this.getBindings();
  32073. bindingsGroups.sort( ( a, b ) => ( a.bindings[ 0 ].groupNode.order - b.bindings[ 0 ].groupNode.order ) );
  32074. for ( let i = 0; i < bindingsGroups.length; i ++ ) {
  32075. const bindingGroup = bindingsGroups[ i ];
  32076. this.bindingsIndexes[ bindingGroup.name ].group = i;
  32077. bindingGroup.index = i;
  32078. }
  32079. }
  32080. /**
  32081. * The builder maintains each node in a hash-based dictionary.
  32082. * This method sets the given node (value) with the given hash (key) into this dictionary.
  32083. *
  32084. * @param {Node} node - The node to add.
  32085. * @param {number} hash - The hash of the node.
  32086. */
  32087. setHashNode( node, hash ) {
  32088. this.hashNodes[ hash ] = node;
  32089. }
  32090. /**
  32091. * Adds a node to this builder.
  32092. *
  32093. * @param {Node} node - The node to add.
  32094. */
  32095. addNode( node ) {
  32096. if ( this.nodes.includes( node ) === false ) {
  32097. this.nodes.push( node );
  32098. this.setHashNode( node, node.getHash( this ) );
  32099. }
  32100. }
  32101. /**
  32102. * It is used to add Nodes that will be used as FRAME and RENDER events,
  32103. * and need to follow a certain sequence in the calls to work correctly.
  32104. * This function should be called after 'setup()' in the 'build()' process to ensure that the child nodes are processed first.
  32105. *
  32106. * @param {Node} node - The node to add.
  32107. */
  32108. addSequentialNode( node ) {
  32109. if ( this.sequentialNodes.includes( node ) === false ) {
  32110. this.sequentialNodes.push( node );
  32111. }
  32112. }
  32113. /**
  32114. * Checks the update types of nodes
  32115. */
  32116. buildUpdateNodes() {
  32117. for ( const node of this.nodes ) {
  32118. const updateType = node.getUpdateType();
  32119. if ( updateType !== NodeUpdateType.NONE ) {
  32120. this.updateNodes.push( node.getSelf() );
  32121. }
  32122. }
  32123. for ( const node of this.sequentialNodes ) {
  32124. const updateBeforeType = node.getUpdateBeforeType();
  32125. const updateAfterType = node.getUpdateAfterType();
  32126. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  32127. this.updateBeforeNodes.push( node.getSelf() );
  32128. }
  32129. if ( updateAfterType !== NodeUpdateType.NONE ) {
  32130. this.updateAfterNodes.push( node.getSelf() );
  32131. }
  32132. }
  32133. }
  32134. /**
  32135. * A reference the current node which is the
  32136. * last node in the chain of nodes.
  32137. *
  32138. * @type {Node}
  32139. */
  32140. get currentNode() {
  32141. return this.chaining[ this.chaining.length - 1 ];
  32142. }
  32143. /**
  32144. * Whether the given texture is filtered or not.
  32145. *
  32146. * @param {Texture} texture - The texture to check.
  32147. * @return {boolean} Whether the given texture is filtered or not.
  32148. */
  32149. isFilteredTexture( texture ) {
  32150. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  32151. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  32152. }
  32153. /**
  32154. * Adds the given node to the internal node chain.
  32155. * This is used to check recursive calls in node-graph.
  32156. *
  32157. * @param {Node} node - The node to add.
  32158. */
  32159. addChain( node ) {
  32160. /*
  32161. if ( this.chaining.indexOf( node ) !== - 1 ) {
  32162. console.warn( 'Recursive node: ', node );
  32163. }
  32164. */
  32165. this.chaining.push( node );
  32166. }
  32167. /**
  32168. * Removes the given node from the internal node chain.
  32169. *
  32170. * @param {Node} node - The node to remove.
  32171. */
  32172. removeChain( node ) {
  32173. const lastChain = this.chaining.pop();
  32174. if ( lastChain !== node ) {
  32175. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  32176. }
  32177. }
  32178. /**
  32179. * Returns the native shader method name for a given generic name. E.g.
  32180. * the method name `textureDimensions` matches the WGSL name but must be
  32181. * resolved to `textureSize` in GLSL.
  32182. *
  32183. * @abstract
  32184. * @param {string} method - The method name to resolve.
  32185. * @return {string} The resolved method name.
  32186. */
  32187. getMethod( method ) {
  32188. return method;
  32189. }
  32190. /**
  32191. * Returns a node for the given hash, see {@link NodeBuilder#setHashNode}.
  32192. *
  32193. * @param {number} hash - The hash of the node.
  32194. * @return {Node} The found node.
  32195. */
  32196. getNodeFromHash( hash ) {
  32197. return this.hashNodes[ hash ];
  32198. }
  32199. /**
  32200. * Adds the Node to a target flow so that it can generate code in the 'generate' process.
  32201. *
  32202. * @param {('vertex'|'fragment'|'compute')} shaderStage - The shader stage.
  32203. * @param {Node} node - The node to add.
  32204. * @return {Node} The node.
  32205. */
  32206. addFlow( shaderStage, node ) {
  32207. this.flowNodes[ shaderStage ].push( node );
  32208. return node;
  32209. }
  32210. /**
  32211. * Sets builder's context.
  32212. *
  32213. * @param {Object} context - The context to set.
  32214. */
  32215. setContext( context ) {
  32216. this.context = context;
  32217. }
  32218. /**
  32219. * Returns the builder's current context.
  32220. *
  32221. * @return {Object} The builder's current context.
  32222. */
  32223. getContext() {
  32224. return this.context;
  32225. }
  32226. /**
  32227. * Gets a context used in shader construction that can be shared across different materials.
  32228. * This is necessary since the renderer cache can reuse shaders generated in one material and use them in another.
  32229. *
  32230. * @return {Object} The builder's current context without material.
  32231. */
  32232. getSharedContext() {
  32233. ({ ...this.context });
  32234. return this.context;
  32235. }
  32236. /**
  32237. * Sets builder's cache.
  32238. *
  32239. * @param {NodeCache} cache - The cache to set.
  32240. */
  32241. setCache( cache ) {
  32242. this.cache = cache;
  32243. }
  32244. /**
  32245. * Returns the builder's current cache.
  32246. *
  32247. * @return {NodeCache} The builder's current cache.
  32248. */
  32249. getCache() {
  32250. return this.cache;
  32251. }
  32252. /**
  32253. * Returns a cache for the given node.
  32254. *
  32255. * @param {Node} node - The node.
  32256. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  32257. * @return {NodeCache} The cache.
  32258. */
  32259. getCacheFromNode( node, parent = true ) {
  32260. const data = this.getDataFromNode( node );
  32261. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  32262. return data.cache;
  32263. }
  32264. /**
  32265. * Whether the requested feature is available or not.
  32266. *
  32267. * @abstract
  32268. * @param {string} name - The requested feature.
  32269. * @return {boolean} Whether the requested feature is supported or not.
  32270. */
  32271. isAvailable( /*name*/ ) {
  32272. return false;
  32273. }
  32274. /**
  32275. * Returns the vertexIndex input variable as a native shader string.
  32276. *
  32277. * @abstract
  32278. * @return {string} The instanceIndex shader string.
  32279. */
  32280. getVertexIndex() {
  32281. console.warn( 'Abstract function.' );
  32282. }
  32283. /**
  32284. * Returns the instanceIndex input variable as a native shader string.
  32285. *
  32286. * @abstract
  32287. * @return {string} The instanceIndex shader string.
  32288. */
  32289. getInstanceIndex() {
  32290. console.warn( 'Abstract function.' );
  32291. }
  32292. /**
  32293. * Returns the drawIndex input variable as a native shader string.
  32294. * Only relevant for WebGL and its `WEBGL_multi_draw` extension.
  32295. *
  32296. * @abstract
  32297. * @return {?string} The drawIndex shader string.
  32298. */
  32299. getDrawIndex() {
  32300. console.warn( 'Abstract function.' );
  32301. }
  32302. /**
  32303. * Returns the frontFacing input variable as a native shader string.
  32304. *
  32305. * @abstract
  32306. * @return {string} The frontFacing shader string.
  32307. */
  32308. getFrontFacing() {
  32309. console.warn( 'Abstract function.' );
  32310. }
  32311. /**
  32312. * Returns the fragCoord input variable as a native shader string.
  32313. *
  32314. * @abstract
  32315. * @return {string} The fragCoord shader string.
  32316. */
  32317. getFragCoord() {
  32318. console.warn( 'Abstract function.' );
  32319. }
  32320. /**
  32321. * Whether to flip texture data along its vertical axis or not. WebGL needs
  32322. * this method evaluate to `true`, WebGPU to `false`.
  32323. *
  32324. * @abstract
  32325. * @return {boolean} Whether to flip texture data along its vertical axis or not.
  32326. */
  32327. isFlipY() {
  32328. return false;
  32329. }
  32330. /**
  32331. * Calling this method increases the usage count for the given node by one.
  32332. *
  32333. * @param {Node} node - The node to increase the usage count for.
  32334. * @return {number} The updated usage count.
  32335. */
  32336. increaseUsage( node ) {
  32337. const nodeData = this.getDataFromNode( node );
  32338. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  32339. return nodeData.usageCount;
  32340. }
  32341. /**
  32342. * Generates a texture sample shader string for the given texture data.
  32343. *
  32344. * @abstract
  32345. * @param {Texture} texture - The texture.
  32346. * @param {string} textureProperty - The texture property name.
  32347. * @param {string} uvSnippet - Snippet defining the texture coordinates.
  32348. * @return {string} The generated shader string.
  32349. */
  32350. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  32351. console.warn( 'Abstract function.' );
  32352. }
  32353. /**
  32354. * Generates a texture LOD shader string for the given texture data.
  32355. *
  32356. * @abstract
  32357. * @param {Texture} texture - The texture.
  32358. * @param {string} textureProperty - The texture property name.
  32359. * @param {string} uvSnippet - Snippet defining the texture coordinates.
  32360. * @param {?string} depthSnippet - Snippet defining the 0-based texture array index to sample.
  32361. * @param {string} levelSnippet - Snippet defining the mip level.
  32362. * @return {string} The generated shader string.
  32363. */
  32364. generateTextureLod( /* texture, textureProperty, uvSnippet, depthSnippet, levelSnippet */ ) {
  32365. console.warn( 'Abstract function.' );
  32366. }
  32367. /**
  32368. * Generates the array declaration string.
  32369. *
  32370. * @param {string} type - The type.
  32371. * @param {?number} [count] - The count.
  32372. * @return {string} The generated value as a shader string.
  32373. */
  32374. generateArrayDeclaration( type, count ) {
  32375. return this.getType( type ) + '[ ' + count + ' ]';
  32376. }
  32377. /**
  32378. * Generates the array shader string for the given type and value.
  32379. *
  32380. * @param {string} type - The type.
  32381. * @param {?number} [count] - The count.
  32382. * @param {?Array<Node>} [values=null] - The default values.
  32383. * @return {string} The generated value as a shader string.
  32384. */
  32385. generateArray( type, count, values = null ) {
  32386. let snippet = this.generateArrayDeclaration( type, count ) + '( ';
  32387. for ( let i = 0; i < count; i ++ ) {
  32388. const value = values ? values[ i ] : null;
  32389. if ( value !== null ) {
  32390. snippet += value.build( this, type );
  32391. } else {
  32392. snippet += this.generateConst( type );
  32393. }
  32394. if ( i < count - 1 ) snippet += ', ';
  32395. }
  32396. snippet += ' )';
  32397. return snippet;
  32398. }
  32399. /**
  32400. * Generates the struct shader string.
  32401. *
  32402. * @param {string} type - The type.
  32403. * @param {Array<Object>} [membersLayout] - The count.
  32404. * @param {?Array<Node>} [values=null] - The default values.
  32405. * @return {string} The generated value as a shader string.
  32406. */
  32407. generateStruct( type, membersLayout, values = null ) {
  32408. const snippets = [];
  32409. for ( const member of membersLayout ) {
  32410. const { name, type } = member;
  32411. if ( values && values[ name ] && values[ name ].isNode ) {
  32412. snippets.push( values[ name ].build( this, type ) );
  32413. } else {
  32414. snippets.push( this.generateConst( type ) );
  32415. }
  32416. }
  32417. return type + '( ' + snippets.join( ', ' ) + ' )';
  32418. }
  32419. /**
  32420. * Generates the shader string for the given type and value.
  32421. *
  32422. * @param {string} type - The type.
  32423. * @param {?any} [value=null] - The value.
  32424. * @return {string} The generated value as a shader string.
  32425. */
  32426. generateConst( type, value = null ) {
  32427. if ( value === null ) {
  32428. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  32429. else if ( type === 'bool' ) value = false;
  32430. else if ( type === 'color' ) value = new Color();
  32431. else if ( type === 'vec2' ) value = new Vector2();
  32432. else if ( type === 'vec3' ) value = new Vector3();
  32433. else if ( type === 'vec4' ) value = new Vector4();
  32434. }
  32435. if ( type === 'float' ) return toFloat( value );
  32436. if ( type === 'int' ) return `${ Math.round( value ) }`;
  32437. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  32438. if ( type === 'bool' ) return value ? 'true' : 'false';
  32439. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  32440. const typeLength = this.getTypeLength( type );
  32441. const componentType = this.getComponentType( type );
  32442. const generateConst = value => this.generateConst( componentType, value );
  32443. if ( typeLength === 2 ) {
  32444. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  32445. } else if ( typeLength === 3 ) {
  32446. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  32447. } else if ( typeLength === 4 && type !== 'mat2' ) {
  32448. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  32449. } else if ( typeLength >= 4 && value && ( value.isMatrix2 || value.isMatrix3 || value.isMatrix4 ) ) {
  32450. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  32451. } else if ( typeLength > 4 ) {
  32452. return `${ this.getType( type ) }()`;
  32453. }
  32454. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  32455. }
  32456. /**
  32457. * It might be necessary to convert certain data types to different ones
  32458. * so this method can be used to hide the conversion.
  32459. *
  32460. * @param {string} type - The type.
  32461. * @return {string} The updated type.
  32462. */
  32463. getType( type ) {
  32464. if ( type === 'color' ) return 'vec3';
  32465. return type;
  32466. }
  32467. /**
  32468. * Whether the given attribute name is defined in the geometry or not.
  32469. *
  32470. * @param {string} name - The attribute name.
  32471. * @return {boolean} Whether the given attribute name is defined in the geometry.
  32472. */
  32473. hasGeometryAttribute( name ) {
  32474. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  32475. }
  32476. /**
  32477. * Returns a node attribute for the given name and type.
  32478. *
  32479. * @param {string} name - The attribute's name.
  32480. * @param {string} type - The attribute's type.
  32481. * @return {NodeAttribute} The node attribute.
  32482. */
  32483. getAttribute( name, type ) {
  32484. const attributes = this.attributes;
  32485. // find attribute
  32486. for ( const attribute of attributes ) {
  32487. if ( attribute.name === name ) {
  32488. return attribute;
  32489. }
  32490. }
  32491. // create a new if no exist
  32492. const attribute = new NodeAttribute( name, type );
  32493. this.registerDeclaration( attribute );
  32494. attributes.push( attribute );
  32495. return attribute;
  32496. }
  32497. /**
  32498. * Returns for the given node and shader stage the property name for the shader.
  32499. *
  32500. * @param {Node} node - The node.
  32501. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  32502. * @return {string} The property name.
  32503. */
  32504. getPropertyName( node/*, shaderStage*/ ) {
  32505. return node.name;
  32506. }
  32507. /**
  32508. * Whether the given type is a vector type or not.
  32509. *
  32510. * @param {string} type - The type to check.
  32511. * @return {boolean} Whether the given type is a vector type or not.
  32512. */
  32513. isVector( type ) {
  32514. return /vec\d/.test( type );
  32515. }
  32516. /**
  32517. * Whether the given type is a matrix type or not.
  32518. *
  32519. * @param {string} type - The type to check.
  32520. * @return {boolean} Whether the given type is a matrix type or not.
  32521. */
  32522. isMatrix( type ) {
  32523. return /mat\d/.test( type );
  32524. }
  32525. /**
  32526. * Whether the given type is a reference type or not.
  32527. *
  32528. * @param {string} type - The type to check.
  32529. * @return {boolean} Whether the given type is a reference type or not.
  32530. */
  32531. isReference( type ) {
  32532. return type === 'void' || type === 'property' || type === 'sampler' || type === 'samplerComparison' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  32533. }
  32534. /**
  32535. * Checks if the given texture requires a manual conversion to the working color space.
  32536. *
  32537. * @abstract
  32538. * @param {Texture} texture - The texture to check.
  32539. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  32540. */
  32541. needsToWorkingColorSpace( /*texture*/ ) {
  32542. return false;
  32543. }
  32544. /**
  32545. * Returns the component type of a given texture.
  32546. *
  32547. * @param {Texture} texture - The texture.
  32548. * @return {string} The component type.
  32549. */
  32550. getComponentTypeFromTexture( texture ) {
  32551. const type = texture.type;
  32552. if ( texture.isDataTexture ) {
  32553. if ( type === IntType ) return 'int';
  32554. if ( type === UnsignedIntType ) return 'uint';
  32555. }
  32556. return 'float';
  32557. }
  32558. /**
  32559. * Returns the element type for a given type.
  32560. *
  32561. * @param {string} type - The type.
  32562. * @return {string} The element type.
  32563. */
  32564. getElementType( type ) {
  32565. if ( type === 'mat2' ) return 'vec2';
  32566. if ( type === 'mat3' ) return 'vec3';
  32567. if ( type === 'mat4' ) return 'vec4';
  32568. return this.getComponentType( type );
  32569. }
  32570. /**
  32571. * Returns the component type for a given type.
  32572. *
  32573. * @param {string} type - The type.
  32574. * @return {string} The component type.
  32575. */
  32576. getComponentType( type ) {
  32577. type = this.getVectorType( type );
  32578. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  32579. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  32580. if ( componentType === null ) return null;
  32581. if ( componentType[ 1 ] === 'b' ) return 'bool';
  32582. if ( componentType[ 1 ] === 'i' ) return 'int';
  32583. if ( componentType[ 1 ] === 'u' ) return 'uint';
  32584. return 'float';
  32585. }
  32586. /**
  32587. * Returns the vector type for a given type.
  32588. *
  32589. * @param {string} type - The type.
  32590. * @return {string} The vector type.
  32591. */
  32592. getVectorType( type ) {
  32593. if ( type === 'color' ) return 'vec3';
  32594. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  32595. return type;
  32596. }
  32597. /**
  32598. * Returns the data type for the given the length and component type.
  32599. *
  32600. * @param {number} length - The length.
  32601. * @param {string} [componentType='float'] - The component type.
  32602. * @return {string} The type.
  32603. */
  32604. getTypeFromLength( length, componentType = 'float' ) {
  32605. if ( length === 1 ) return componentType;
  32606. let baseType = getTypeFromLength( length );
  32607. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  32608. // fix edge case for mat2x2 being same size as vec4
  32609. if ( /mat2/.test( componentType ) === true ) {
  32610. baseType = baseType.replace( 'vec', 'mat' );
  32611. }
  32612. return prefix + baseType;
  32613. }
  32614. /**
  32615. * Returns the type for a given typed array.
  32616. *
  32617. * @param {TypedArray} array - The typed array.
  32618. * @return {string} The type.
  32619. */
  32620. getTypeFromArray( array ) {
  32621. return typeFromArray.get( array.constructor );
  32622. }
  32623. /**
  32624. * Returns the type is an integer type.
  32625. *
  32626. * @param {string} type - The type.
  32627. * @return {boolean} Whether the type is an integer type or not.
  32628. */
  32629. isInteger( type ) {
  32630. return /int|uint|(i|u)vec/.test( type );
  32631. }
  32632. /**
  32633. * Returns the type for a given buffer attribute.
  32634. *
  32635. * @param {BufferAttribute} attribute - The buffer attribute.
  32636. * @return {string} The type.
  32637. */
  32638. getTypeFromAttribute( attribute ) {
  32639. let dataAttribute = attribute;
  32640. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  32641. const array = dataAttribute.array;
  32642. const itemSize = attribute.itemSize;
  32643. const normalized = attribute.normalized;
  32644. let arrayType;
  32645. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  32646. arrayType = this.getTypeFromArray( array );
  32647. }
  32648. return this.getTypeFromLength( itemSize, arrayType );
  32649. }
  32650. /**
  32651. * Returns the length for the given data type.
  32652. *
  32653. * @param {string} type - The data type.
  32654. * @return {number} The length.
  32655. */
  32656. getTypeLength( type ) {
  32657. const vecType = this.getVectorType( type );
  32658. const vecNum = /vec([2-4])/.exec( vecType );
  32659. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  32660. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  32661. if ( /mat2/.test( type ) === true ) return 4;
  32662. if ( /mat3/.test( type ) === true ) return 9;
  32663. if ( /mat4/.test( type ) === true ) return 16;
  32664. return 0;
  32665. }
  32666. /**
  32667. * Returns the vector type for a given matrix type.
  32668. *
  32669. * @param {string} type - The matrix type.
  32670. * @return {string} The vector type.
  32671. */
  32672. getVectorFromMatrix( type ) {
  32673. return type.replace( 'mat', 'vec' );
  32674. }
  32675. /**
  32676. * For a given type this method changes the component type to the
  32677. * given value. E.g. `vec4` should be changed to the new component type
  32678. * `uint` which results in `uvec4`.
  32679. *
  32680. * @param {string} type - The type.
  32681. * @param {string} newComponentType - The new component type.
  32682. * @return {string} The new type.
  32683. */
  32684. changeComponentType( type, newComponentType ) {
  32685. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  32686. }
  32687. /**
  32688. * Returns the integer type pendant for the given type.
  32689. *
  32690. * @param {string} type - The type.
  32691. * @return {string} The integer type.
  32692. */
  32693. getIntegerType( type ) {
  32694. const componentType = this.getComponentType( type );
  32695. if ( componentType === 'int' || componentType === 'uint' ) return type;
  32696. return this.changeComponentType( type, 'int' );
  32697. }
  32698. /**
  32699. * Adds a stack node to the internal stack.
  32700. *
  32701. * @return {StackNode} The added stack node.
  32702. */
  32703. addStack() {
  32704. this.stack = stack( this.stack );
  32705. this.stacks.push( getCurrentStack() || this.stack );
  32706. setCurrentStack( this.stack );
  32707. return this.stack;
  32708. }
  32709. /**
  32710. * Removes the last stack node from the internal stack.
  32711. *
  32712. * @return {StackNode} The removed stack node.
  32713. */
  32714. removeStack() {
  32715. const lastStack = this.stack;
  32716. this.stack = lastStack.parent;
  32717. setCurrentStack( this.stacks.pop() );
  32718. return lastStack;
  32719. }
  32720. /**
  32721. * The builder maintains (cached) data for each node during the building process. This method
  32722. * can be used to get these data for a specific shader stage and cache.
  32723. *
  32724. * @param {Node} node - The node to get the data for.
  32725. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  32726. * @param {?NodeCache} cache - An optional cache.
  32727. * @return {Object} The node data.
  32728. */
  32729. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  32730. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  32731. let nodeData = cache.getData( node );
  32732. if ( nodeData === undefined ) {
  32733. nodeData = {};
  32734. cache.setData( node, nodeData );
  32735. }
  32736. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  32737. return nodeData[ shaderStage ];
  32738. }
  32739. /**
  32740. * Returns the properties for the given node and shader stage.
  32741. *
  32742. * @param {Node} node - The node to get the properties for.
  32743. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage='any'] - The shader stage.
  32744. * @return {Object} The node properties.
  32745. */
  32746. getNodeProperties( node, shaderStage = 'any' ) {
  32747. const nodeData = this.getDataFromNode( node, shaderStage );
  32748. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  32749. }
  32750. /**
  32751. * Returns an instance of {@link NodeAttribute} for the given buffer attribute node.
  32752. *
  32753. * @param {BufferAttributeNode} node - The buffer attribute node.
  32754. * @param {string} type - The node type.
  32755. * @return {NodeAttribute} The node attribute.
  32756. */
  32757. getBufferAttributeFromNode( node, type ) {
  32758. const nodeData = this.getDataFromNode( node );
  32759. let bufferAttribute = nodeData.bufferAttribute;
  32760. if ( bufferAttribute === undefined ) {
  32761. const index = this.uniforms.index ++;
  32762. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  32763. this.bufferAttributes.push( bufferAttribute );
  32764. nodeData.bufferAttribute = bufferAttribute;
  32765. }
  32766. return bufferAttribute;
  32767. }
  32768. /**
  32769. * Returns an instance of {@link StructType} for the given output struct node.
  32770. *
  32771. * @param {OutputStructNode} node - The output struct node.
  32772. * @param {Array<Object>} membersLayout - The output struct types.
  32773. * @param {?string} [name=null] - The name of the struct.
  32774. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  32775. * @return {StructType} The struct type attribute.
  32776. */
  32777. getStructTypeFromNode( node, membersLayout, name = null, shaderStage = this.shaderStage ) {
  32778. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  32779. let structType = nodeData.structType;
  32780. if ( structType === undefined ) {
  32781. const index = this.structs.index ++;
  32782. if ( name === null ) name = 'StructType' + index;
  32783. structType = new StructType( name, membersLayout );
  32784. this.structs[ shaderStage ].push( structType );
  32785. nodeData.structType = structType;
  32786. }
  32787. return structType;
  32788. }
  32789. /**
  32790. * Returns an instance of {@link StructType} for the given output struct node.
  32791. *
  32792. * @param {OutputStructNode} node - The output struct node.
  32793. * @param {Array<Object>} membersLayout - The output struct types.
  32794. * @return {StructType} The struct type attribute.
  32795. */
  32796. getOutputStructTypeFromNode( node, membersLayout ) {
  32797. const structType = this.getStructTypeFromNode( node, membersLayout, 'OutputType', 'fragment' );
  32798. structType.output = true;
  32799. return structType;
  32800. }
  32801. /**
  32802. * Returns an instance of {@link NodeUniform} for the given uniform node.
  32803. *
  32804. * @param {UniformNode} node - The uniform node.
  32805. * @param {string} type - The uniform type.
  32806. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  32807. * @param {?string} name - The name of the uniform.
  32808. * @return {NodeUniform} The node uniform.
  32809. */
  32810. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  32811. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  32812. let nodeUniform = nodeData.uniform;
  32813. if ( nodeUniform === undefined ) {
  32814. const index = this.uniforms.index ++;
  32815. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  32816. this.uniforms[ shaderStage ].push( nodeUniform );
  32817. this.registerDeclaration( nodeUniform );
  32818. nodeData.uniform = nodeUniform;
  32819. }
  32820. return nodeUniform;
  32821. }
  32822. /**
  32823. * Returns the array length.
  32824. *
  32825. * @param {Node} node - The node.
  32826. * @return {?number} The array length.
  32827. */
  32828. getArrayCount( node ) {
  32829. let count = null;
  32830. if ( node.isArrayNode ) count = node.count;
  32831. else if ( node.isVarNode && node.node.isArrayNode ) count = node.node.count;
  32832. return count;
  32833. }
  32834. /**
  32835. * Returns an instance of {@link NodeVar} for the given variable node.
  32836. *
  32837. * @param {VarNode} node - The variable node.
  32838. * @param {?string} name - The variable's name.
  32839. * @param {string} [type=node.getNodeType( this )] - The variable's type.
  32840. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  32841. * @param {boolean} [readOnly=false] - Whether the variable is read-only or not.
  32842. *
  32843. * @return {NodeVar} The node variable.
  32844. */
  32845. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage, readOnly = false ) {
  32846. const nodeData = this.getDataFromNode( node, shaderStage );
  32847. let nodeVar = nodeData.variable;
  32848. if ( nodeVar === undefined ) {
  32849. const idNS = readOnly ? '_const' : '_var';
  32850. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  32851. const id = this.vars[ idNS ] || ( this.vars[ idNS ] = 0 );
  32852. if ( name === null ) {
  32853. name = ( readOnly ? 'nodeConst' : 'nodeVar' ) + id;
  32854. this.vars[ idNS ] ++;
  32855. }
  32856. //
  32857. const count = this.getArrayCount( node );
  32858. nodeVar = new NodeVar( name, type, readOnly, count );
  32859. if ( ! readOnly ) {
  32860. vars.push( nodeVar );
  32861. }
  32862. this.registerDeclaration( nodeVar );
  32863. nodeData.variable = nodeVar;
  32864. }
  32865. return nodeVar;
  32866. }
  32867. /**
  32868. * Returns whether a Node or its flow is deterministic, useful for use in `const`.
  32869. *
  32870. * @param {Node} node - The varying node.
  32871. * @return {boolean} Returns true if deterministic.
  32872. */
  32873. isDeterministic( node ) {
  32874. if ( node.isMathNode ) {
  32875. return this.isDeterministic( node.aNode ) &&
  32876. ( node.bNode ? this.isDeterministic( node.bNode ) : true ) &&
  32877. ( node.cNode ? this.isDeterministic( node.cNode ) : true );
  32878. } else if ( node.isOperatorNode ) {
  32879. return this.isDeterministic( node.aNode ) &&
  32880. ( node.bNode ? this.isDeterministic( node.bNode ) : true );
  32881. } else if ( node.isArrayNode ) {
  32882. if ( node.values !== null ) {
  32883. for ( const n of node.values ) {
  32884. if ( ! this.isDeterministic( n ) ) {
  32885. return false;
  32886. }
  32887. }
  32888. }
  32889. return true;
  32890. } else if ( node.isConstNode ) {
  32891. return true;
  32892. }
  32893. return false;
  32894. }
  32895. /**
  32896. * Returns an instance of {@link NodeVarying} for the given varying node.
  32897. *
  32898. * @param {(VaryingNode|PropertyNode)} node - The varying node.
  32899. * @param {?string} name - The varying's name.
  32900. * @param {string} [type=node.getNodeType( this )] - The varying's type.
  32901. * @param {?string} interpolationType - The interpolation type of the varying.
  32902. * @param {?string} interpolationSampling - The interpolation sampling type of the varying.
  32903. * @return {NodeVar} The node varying.
  32904. */
  32905. getVaryingFromNode( node, name = null, type = node.getNodeType( this ), interpolationType = null, interpolationSampling = null ) {
  32906. const nodeData = this.getDataFromNode( node, 'any' );
  32907. let nodeVarying = nodeData.varying;
  32908. if ( nodeVarying === undefined ) {
  32909. const varyings = this.varyings;
  32910. const index = varyings.length;
  32911. if ( name === null ) name = 'nodeVarying' + index;
  32912. nodeVarying = new NodeVarying( name, type, interpolationType, interpolationSampling );
  32913. varyings.push( nodeVarying );
  32914. this.registerDeclaration( nodeVarying );
  32915. nodeData.varying = nodeVarying;
  32916. }
  32917. return nodeVarying;
  32918. }
  32919. /**
  32920. * Returns the current namespace for the node builder.
  32921. *
  32922. * @return {string} The current namespace.
  32923. */
  32924. get namespace() {
  32925. return this.context.namespace;
  32926. }
  32927. /**
  32928. * Returns the output namespace for the node builder, which is used for the current output node.
  32929. *
  32930. * @return {string} The output namespace.
  32931. */
  32932. getOutputNamespace() {
  32933. return this.getNamespace( 'outputNode' );
  32934. }
  32935. /**
  32936. * Returns the namespace for the given property.
  32937. *
  32938. * If the property name is not set, it returns the namespace only.
  32939. * If the namespace is not set, it returns the property name.
  32940. * If the namespace is set, it returns the namespace concatenated with the property name.
  32941. *
  32942. * @param {string} [property=''] - The property name.
  32943. * @return {string} The namespace for the property.
  32944. */
  32945. getNamespace( property = '' ) {
  32946. const ns = this.namespace;
  32947. let nsName;
  32948. if ( ns ) {
  32949. nsName = property ? ( ns + '_' + property ) : ns;
  32950. } else {
  32951. nsName = property;
  32952. }
  32953. return nsName;
  32954. }
  32955. /**
  32956. * Registers a node declaration in the current shader stage.
  32957. *
  32958. * @param {Object} node - The node to be registered.
  32959. */
  32960. registerDeclaration( node ) {
  32961. const shaderStage = this.shaderStage;
  32962. const declarations = this.declarations[ shaderStage ] || ( this.declarations[ shaderStage ] = {} );
  32963. const property = this.getPropertyName( node );
  32964. let index = 1;
  32965. let name = property;
  32966. // Automatically renames the property if the name is already in use.
  32967. while ( declarations[ name ] !== undefined ) {
  32968. name = property + '_' + index ++;
  32969. }
  32970. if ( index > 1 ) {
  32971. node.name = name;
  32972. console.warn( `THREE.TSL: Declaration name '${ property }' of '${ node.type }' already in use. Renamed to '${ name }'.` );
  32973. }
  32974. declarations[ name ] = node;
  32975. }
  32976. /**
  32977. * Returns an instance of {@link NodeCode} for the given code node.
  32978. *
  32979. * @param {CodeNode} node - The code node.
  32980. * @param {string} type - The node type.
  32981. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  32982. * @return {NodeCode} The node code.
  32983. */
  32984. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  32985. const nodeData = this.getDataFromNode( node );
  32986. let nodeCode = nodeData.code;
  32987. if ( nodeCode === undefined ) {
  32988. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  32989. const index = codes.length;
  32990. nodeCode = new NodeCode( 'nodeCode' + index, type );
  32991. codes.push( nodeCode );
  32992. nodeData.code = nodeCode;
  32993. }
  32994. return nodeCode;
  32995. }
  32996. /**
  32997. * Adds a code flow based on the code-block hierarchy.
  32998. * This is used so that code-blocks like If,Else create their variables locally if the Node
  32999. * is only used inside one of these conditionals in the current shader stage.
  33000. *
  33001. * @param {Node} node - The node to add.
  33002. * @param {Node} nodeBlock - Node-based code-block. Usually 'ConditionalNode'.
  33003. */
  33004. addFlowCodeHierarchy( node, nodeBlock ) {
  33005. const { flowCodes, flowCodeBlock } = this.getDataFromNode( node );
  33006. let needsFlowCode = true;
  33007. let nodeBlockHierarchy = nodeBlock;
  33008. while ( nodeBlockHierarchy ) {
  33009. if ( flowCodeBlock.get( nodeBlockHierarchy ) === true ) {
  33010. needsFlowCode = false;
  33011. break;
  33012. }
  33013. nodeBlockHierarchy = this.getDataFromNode( nodeBlockHierarchy ).parentNodeBlock;
  33014. }
  33015. if ( needsFlowCode ) {
  33016. for ( const flowCode of flowCodes ) {
  33017. this.addLineFlowCode( flowCode );
  33018. }
  33019. }
  33020. }
  33021. /**
  33022. * Add a inline-code to the current flow code-block.
  33023. *
  33024. * @param {Node} node - The node to add.
  33025. * @param {string} code - The code to add.
  33026. * @param {Node} nodeBlock - Current ConditionalNode
  33027. */
  33028. addLineFlowCodeBlock( node, code, nodeBlock ) {
  33029. const nodeData = this.getDataFromNode( node );
  33030. const flowCodes = nodeData.flowCodes || ( nodeData.flowCodes = [] );
  33031. const codeBlock = nodeData.flowCodeBlock || ( nodeData.flowCodeBlock = new WeakMap() );
  33032. flowCodes.push( code );
  33033. codeBlock.set( nodeBlock, true );
  33034. }
  33035. /**
  33036. * Add a inline-code to the current flow.
  33037. *
  33038. * @param {string} code - The code to add.
  33039. * @param {?Node} [node= null] - Optional Node, can help the system understand if the Node is part of a code-block.
  33040. * @return {NodeBuilder} A reference to this node builder.
  33041. */
  33042. addLineFlowCode( code, node = null ) {
  33043. if ( code === '' ) return this;
  33044. if ( node !== null && this.context.nodeBlock ) {
  33045. this.addLineFlowCodeBlock( node, code, this.context.nodeBlock );
  33046. }
  33047. code = this.tab + code;
  33048. if ( ! /;\s*$/.test( code ) ) {
  33049. code = code + ';\n';
  33050. }
  33051. this.flow.code += code;
  33052. return this;
  33053. }
  33054. /**
  33055. * Adds a code to the current code flow.
  33056. *
  33057. * @param {string} code - Shader code.
  33058. * @return {NodeBuilder} A reference to this node builder.
  33059. */
  33060. addFlowCode( code ) {
  33061. this.flow.code += code;
  33062. return this;
  33063. }
  33064. /**
  33065. * Add tab in the code that will be generated so that other snippets respect the current tabulation.
  33066. * Typically used in codes with If,Else.
  33067. *
  33068. * @return {NodeBuilder} A reference to this node builder.
  33069. */
  33070. addFlowTab() {
  33071. this.tab += '\t';
  33072. return this;
  33073. }
  33074. /**
  33075. * Removes a tab.
  33076. *
  33077. * @return {NodeBuilder} A reference to this node builder.
  33078. */
  33079. removeFlowTab() {
  33080. this.tab = this.tab.slice( 0, -1 );
  33081. return this;
  33082. }
  33083. /**
  33084. * Gets the current flow data based on a Node.
  33085. *
  33086. * @param {Node} node - Node that the flow was started.
  33087. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  33088. * @return {Object} The flow data.
  33089. */
  33090. getFlowData( node/*, shaderStage*/ ) {
  33091. return this.flowsData.get( node );
  33092. }
  33093. /**
  33094. * Executes the node flow based on a root node to generate the final shader code.
  33095. *
  33096. * @param {Node} node - The node to execute.
  33097. * @return {Object} The code flow.
  33098. */
  33099. flowNode( node ) {
  33100. const output = node.getNodeType( this );
  33101. const flowData = this.flowChildNode( node, output );
  33102. this.flowsData.set( node, flowData );
  33103. return flowData;
  33104. }
  33105. /**
  33106. * Includes a node in the current function node.
  33107. *
  33108. * @param {Node} node - The node to include.
  33109. * @returns {void}
  33110. */
  33111. addInclude( node ) {
  33112. if ( this.currentFunctionNode !== null ) {
  33113. this.currentFunctionNode.includes.push( node );
  33114. }
  33115. }
  33116. /**
  33117. * Returns the native shader operator name for a given generic name.
  33118. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  33119. *
  33120. * @param {ShaderNodeInternal} shaderNode - The shader node to build the function node with.
  33121. * @return {FunctionNode} The build function node.
  33122. */
  33123. buildFunctionNode( shaderNode ) {
  33124. const fn = new FunctionNode();
  33125. const previous = this.currentFunctionNode;
  33126. this.currentFunctionNode = fn;
  33127. fn.code = this.buildFunctionCode( shaderNode );
  33128. this.currentFunctionNode = previous;
  33129. return fn;
  33130. }
  33131. /**
  33132. * Generates a code flow based on a TSL function: Fn().
  33133. *
  33134. * @param {ShaderNodeInternal} shaderNode - A function code will be generated based on the input.
  33135. * @return {Object}
  33136. */
  33137. flowShaderNode( shaderNode ) {
  33138. const layout = shaderNode.layout;
  33139. const inputs = {
  33140. [ Symbol.iterator ]() {
  33141. let index = 0;
  33142. const values = Object.values( this );
  33143. return {
  33144. next: () => ( {
  33145. value: values[ index ],
  33146. done: index ++ >= values.length
  33147. } )
  33148. };
  33149. }
  33150. };
  33151. for ( const input of layout.inputs ) {
  33152. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  33153. }
  33154. //
  33155. shaderNode.layout = null;
  33156. const callNode = shaderNode.call( inputs );
  33157. const flowData = this.flowStagesNode( callNode, layout.type );
  33158. shaderNode.layout = layout;
  33159. return flowData;
  33160. }
  33161. /**
  33162. * Runs the node flow through all the steps of creation, 'setup', 'analyze', 'generate'.
  33163. *
  33164. * @param {Node} node - The node to execute.
  33165. * @param {?string} output - Expected output type. For example 'vec3'.
  33166. * @return {Object}
  33167. */
  33168. flowStagesNode( node, output = null ) {
  33169. const previousFlow = this.flow;
  33170. const previousVars = this.vars;
  33171. const previousDeclarations = this.declarations;
  33172. const previousCache = this.cache;
  33173. const previousBuildStage = this.buildStage;
  33174. const previousStack = this.stack;
  33175. const flow = {
  33176. code: ''
  33177. };
  33178. this.flow = flow;
  33179. this.vars = {};
  33180. this.declarations = {};
  33181. this.cache = new NodeCache();
  33182. this.stack = stack();
  33183. for ( const buildStage of defaultBuildStages ) {
  33184. this.setBuildStage( buildStage );
  33185. flow.result = node.build( this, output );
  33186. }
  33187. flow.vars = this.getVars( this.shaderStage );
  33188. this.flow = previousFlow;
  33189. this.vars = previousVars;
  33190. this.declarations = previousDeclarations;
  33191. this.cache = previousCache;
  33192. this.stack = previousStack;
  33193. this.setBuildStage( previousBuildStage );
  33194. return flow;
  33195. }
  33196. /**
  33197. * Returns the native shader operator name for a given generic name.
  33198. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  33199. *
  33200. * @abstract
  33201. * @param {string} op - The operator name to resolve.
  33202. * @return {?string} The resolved operator name.
  33203. */
  33204. getFunctionOperator( /* op */ ) {
  33205. return null;
  33206. }
  33207. /**
  33208. * Builds the given shader node.
  33209. *
  33210. * @abstract
  33211. * @param {ShaderNodeInternal} shaderNode - The shader node.
  33212. * @return {string} The function code.
  33213. */
  33214. buildFunctionCode( /* shaderNode */ ) {
  33215. console.warn( 'Abstract function.' );
  33216. }
  33217. /**
  33218. * Generates a code flow based on a child Node.
  33219. *
  33220. * @param {Node} node - The node to execute.
  33221. * @param {?string} output - Expected output type. For example 'vec3'.
  33222. * @return {Object} The code flow.
  33223. */
  33224. flowChildNode( node, output = null ) {
  33225. const previousFlow = this.flow;
  33226. const flow = {
  33227. code: ''
  33228. };
  33229. this.flow = flow;
  33230. flow.result = node.build( this, output );
  33231. this.flow = previousFlow;
  33232. return flow;
  33233. }
  33234. /**
  33235. * Executes a flow of code in a different stage.
  33236. *
  33237. * Some nodes like `varying()` have the ability to compute code in vertex-stage and
  33238. * return the value in fragment-stage even if it is being executed in an input fragment.
  33239. *
  33240. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  33241. * @param {Node} node - The node to execute.
  33242. * @param {?string} output - Expected output type. For example 'vec3'.
  33243. * @param {?string} propertyName - The property name to assign the result.
  33244. * @return {Object|Node|null} The code flow or node.build() result.
  33245. */
  33246. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  33247. const previousTab = this.tab;
  33248. const previousCache = this.cache;
  33249. const previousShaderStage = this.shaderStage;
  33250. const previousContext = this.context;
  33251. this.setShaderStage( shaderStage );
  33252. const context = { ...this.context };
  33253. delete context.nodeBlock;
  33254. this.cache = this.globalCache;
  33255. this.tab = '\t';
  33256. this.context = context;
  33257. let result = null;
  33258. if ( this.buildStage === 'generate' ) {
  33259. const flowData = this.flowChildNode( node, output );
  33260. if ( propertyName !== null ) {
  33261. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  33262. }
  33263. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  33264. result = flowData;
  33265. } else {
  33266. result = node.build( this );
  33267. }
  33268. this.setShaderStage( previousShaderStage );
  33269. this.cache = previousCache;
  33270. this.tab = previousTab;
  33271. this.context = previousContext;
  33272. return result;
  33273. }
  33274. /**
  33275. * Returns an array holding all node attributes of this node builder.
  33276. *
  33277. * @return {Array<NodeAttribute>} The node attributes of this builder.
  33278. */
  33279. getAttributesArray() {
  33280. return this.attributes.concat( this.bufferAttributes );
  33281. }
  33282. /**
  33283. * Returns the attribute definitions as a shader string for the given shader stage.
  33284. *
  33285. * @abstract
  33286. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  33287. * @return {string} The attribute code section.
  33288. */
  33289. getAttributes( /*shaderStage*/ ) {
  33290. console.warn( 'Abstract function.' );
  33291. }
  33292. /**
  33293. * Returns the varying definitions as a shader string for the given shader stage.
  33294. *
  33295. * @abstract
  33296. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  33297. * @return {string} The varying code section.
  33298. */
  33299. getVaryings( /*shaderStage*/ ) {
  33300. console.warn( 'Abstract function.' );
  33301. }
  33302. /**
  33303. * Returns a single variable definition as a shader string for the given variable type and name.
  33304. *
  33305. * @param {string} type - The variable's type.
  33306. * @param {string} name - The variable's name.
  33307. * @param {?number} [count=null] - The array length.
  33308. * @return {string} The shader string.
  33309. */
  33310. getVar( type, name, count = null ) {
  33311. return `${ count !== null ? this.generateArrayDeclaration( type, count ) : this.getType( type ) } ${ name }`;
  33312. }
  33313. /**
  33314. * Returns the variable definitions as a shader string for the given shader stage.
  33315. *
  33316. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  33317. * @return {string} The variable code section.
  33318. */
  33319. getVars( shaderStage ) {
  33320. let snippet = '';
  33321. const vars = this.vars[ shaderStage ];
  33322. if ( vars !== undefined ) {
  33323. for ( const variable of vars ) {
  33324. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  33325. }
  33326. }
  33327. return snippet;
  33328. }
  33329. /**
  33330. * Returns the uniform definitions as a shader string for the given shader stage.
  33331. *
  33332. * @abstract
  33333. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  33334. * @return {string} The uniform code section.
  33335. */
  33336. getUniforms( /*shaderStage*/ ) {
  33337. console.warn( 'Abstract function.' );
  33338. }
  33339. /**
  33340. * Returns the native code definitions as a shader string for the given shader stage.
  33341. *
  33342. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  33343. * @return {string} The native code section.
  33344. */
  33345. getCodes( shaderStage ) {
  33346. const codes = this.codes[ shaderStage ];
  33347. let code = '';
  33348. if ( codes !== undefined ) {
  33349. for ( const nodeCode of codes ) {
  33350. code += nodeCode.code + '\n';
  33351. }
  33352. }
  33353. return code;
  33354. }
  33355. /**
  33356. * Returns the hash of this node builder.
  33357. *
  33358. * @return {string} The hash.
  33359. */
  33360. getHash() {
  33361. return this.vertexShader + this.fragmentShader + this.computeShader;
  33362. }
  33363. /**
  33364. * Sets the current shader stage.
  33365. *
  33366. * @param {?('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage to set.
  33367. */
  33368. setShaderStage( shaderStage ) {
  33369. this.shaderStage = shaderStage;
  33370. }
  33371. /**
  33372. * Returns the current shader stage.
  33373. *
  33374. * @return {?('vertex'|'fragment'|'compute'|'any')} The current shader stage.
  33375. */
  33376. getShaderStage() {
  33377. return this.shaderStage;
  33378. }
  33379. /**
  33380. * Sets the current build stage.
  33381. *
  33382. * @param {?('setup'|'analyze'|'generate')} buildStage - The build stage to set.
  33383. */
  33384. setBuildStage( buildStage ) {
  33385. this.buildStage = buildStage;
  33386. }
  33387. /**
  33388. * Returns the current build stage.
  33389. *
  33390. * @return {?('setup'|'analyze'|'generate')} The current build stage.
  33391. */
  33392. getBuildStage() {
  33393. return this.buildStage;
  33394. }
  33395. /**
  33396. * Controls the code build of the shader stages.
  33397. *
  33398. * @abstract
  33399. */
  33400. buildCode() {
  33401. console.warn( 'Abstract function.' );
  33402. }
  33403. /**
  33404. * Central build method which controls the build for the given object.
  33405. *
  33406. * @return {NodeBuilder} A reference to this node builder.
  33407. */
  33408. build() {
  33409. const { object, material, renderer } = this;
  33410. if ( material !== null ) {
  33411. let nodeMaterial = renderer.library.fromMaterial( material );
  33412. if ( nodeMaterial === null ) {
  33413. console.error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  33414. nodeMaterial = new NodeMaterial();
  33415. }
  33416. nodeMaterial.build( this );
  33417. } else {
  33418. this.addFlow( 'compute', object );
  33419. }
  33420. // setup() -> stage 1: create possible new nodes and returns an output reference node
  33421. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  33422. // generate() -> stage 3: generate shader
  33423. for ( const buildStage of defaultBuildStages ) {
  33424. this.setBuildStage( buildStage );
  33425. if ( this.context.vertex && this.context.vertex.isNode ) {
  33426. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  33427. }
  33428. for ( const shaderStage of shaderStages ) {
  33429. this.setShaderStage( shaderStage );
  33430. const flowNodes = this.flowNodes[ shaderStage ];
  33431. for ( const node of flowNodes ) {
  33432. if ( buildStage === 'generate' ) {
  33433. this.flowNode( node );
  33434. } else {
  33435. node.build( this );
  33436. }
  33437. }
  33438. }
  33439. }
  33440. this.setBuildStage( null );
  33441. this.setShaderStage( null );
  33442. // stage 4: build code for a specific output
  33443. this.buildCode();
  33444. this.buildUpdateNodes();
  33445. return this;
  33446. }
  33447. /**
  33448. * Returns a uniform representation which is later used for UBO generation and rendering.
  33449. *
  33450. * @param {NodeUniform} uniformNode - The uniform node.
  33451. * @param {string} type - The requested type.
  33452. * @return {Uniform} The uniform.
  33453. */
  33454. getNodeUniform( uniformNode, type ) {
  33455. if ( type === 'float' || type === 'int' || type === 'uint' ) return new NumberNodeUniform( uniformNode );
  33456. if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) return new Vector2NodeUniform( uniformNode );
  33457. if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) return new Vector3NodeUniform( uniformNode );
  33458. if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) return new Vector4NodeUniform( uniformNode );
  33459. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  33460. if ( type === 'mat2' ) return new Matrix2NodeUniform( uniformNode );
  33461. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  33462. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  33463. throw new Error( `Uniform "${type}" not declared.` );
  33464. }
  33465. /**
  33466. * Formats the given shader snippet from a given type into another one. E.g.
  33467. * this method might be used to convert a simple float string `"1.0"` into a
  33468. * `vec3` representation: `"vec3<f32>( 1.0 )"`.
  33469. *
  33470. * @param {string} snippet - The shader snippet.
  33471. * @param {string} fromType - The source type.
  33472. * @param {string} toType - The target type.
  33473. * @return {string} The updated shader string.
  33474. */
  33475. format( snippet, fromType, toType ) {
  33476. fromType = this.getVectorType( fromType );
  33477. toType = this.getVectorType( toType );
  33478. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  33479. return snippet;
  33480. }
  33481. const fromTypeLength = this.getTypeLength( fromType );
  33482. const toTypeLength = this.getTypeLength( toType );
  33483. if ( fromTypeLength === 16 && toTypeLength === 9 ) {
  33484. return `${ this.getType( toType ) }( ${ snippet }[ 0 ].xyz, ${ snippet }[ 1 ].xyz, ${ snippet }[ 2 ].xyz )`;
  33485. }
  33486. if ( fromTypeLength === 9 && toTypeLength === 4 ) {
  33487. return `${ this.getType( toType ) }( ${ snippet }[ 0 ].xy, ${ snippet }[ 1 ].xy )`;
  33488. }
  33489. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  33490. // @TODO: ignore for now
  33491. return snippet;
  33492. }
  33493. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  33494. // @TODO: ignore for now
  33495. return snippet;
  33496. }
  33497. if ( fromTypeLength === toTypeLength ) {
  33498. return `${ this.getType( toType ) }( ${ snippet } )`;
  33499. }
  33500. if ( fromTypeLength > toTypeLength ) {
  33501. snippet = toType === 'bool' ? `all( ${ snippet } )` : `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`;
  33502. return this.format( snippet, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  33503. }
  33504. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  33505. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  33506. }
  33507. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  33508. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  33509. }
  33510. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  33511. // convert a number value to vector type, e.g:
  33512. // vec3( 1u ) -> vec3( float( 1u ) )
  33513. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  33514. }
  33515. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  33516. }
  33517. /**
  33518. * Returns a signature with the engine's current revision.
  33519. *
  33520. * @return {string} The signature.
  33521. */
  33522. getSignature() {
  33523. return `// Three.js r${ REVISION } - Node System\n`;
  33524. }
  33525. /**
  33526. * Prevents the node builder from being used as an iterable in TSL.Fn(), avoiding potential runtime errors.
  33527. */
  33528. *[ Symbol.iterator ]() { }
  33529. // Deprecated
  33530. /**
  33531. * @function
  33532. * @deprecated since r168. Use `new NodeMaterial()` instead, with targeted node material name.
  33533. *
  33534. * @param {string} [type='NodeMaterial'] - The node material type.
  33535. * @throws {Error}
  33536. */
  33537. createNodeMaterial( type = 'NodeMaterial' ) { // @deprecated, r168
  33538. throw new Error( `THREE.NodeBuilder: createNodeMaterial() was deprecated. Use new ${ type }() instead.` );
  33539. }
  33540. }
  33541. /**
  33542. * Management class for updating nodes. The module tracks metrics like
  33543. * the elapsed time, delta time, the render and frame ID to correctly
  33544. * call the node update methods {@link Node#updateBefore}, {@link Node#update}
  33545. * and {@link Node#updateAfter} depending on the node's configuration.
  33546. */
  33547. class NodeFrame {
  33548. /**
  33549. * Constructs a new node fame.
  33550. */
  33551. constructor() {
  33552. /**
  33553. * The elapsed time in seconds.
  33554. *
  33555. * @type {number}
  33556. * @default 0
  33557. */
  33558. this.time = 0;
  33559. /**
  33560. * The delta time in seconds.
  33561. *
  33562. * @type {number}
  33563. * @default 0
  33564. */
  33565. this.deltaTime = 0;
  33566. /**
  33567. * The frame ID.
  33568. *
  33569. * @type {number}
  33570. * @default 0
  33571. */
  33572. this.frameId = 0;
  33573. /**
  33574. * The render ID.
  33575. *
  33576. * @type {number}
  33577. * @default 0
  33578. */
  33579. this.renderId = 0;
  33580. /**
  33581. * Used to control the {@link Node#update} call.
  33582. *
  33583. * @type {WeakMap<Node, Object>}
  33584. */
  33585. this.updateMap = new WeakMap();
  33586. /**
  33587. * Used to control the {@link Node#updateBefore} call.
  33588. *
  33589. * @type {WeakMap<Node, Object>}
  33590. */
  33591. this.updateBeforeMap = new WeakMap();
  33592. /**
  33593. * Used to control the {@link Node#updateAfter} call.
  33594. *
  33595. * @type {WeakMap<Node, Object>}
  33596. */
  33597. this.updateAfterMap = new WeakMap();
  33598. /**
  33599. * A reference to the current renderer.
  33600. *
  33601. * @type {?Renderer}
  33602. * @default null
  33603. */
  33604. this.renderer = null;
  33605. /**
  33606. * A reference to the current material.
  33607. *
  33608. * @type {?Material}
  33609. * @default null
  33610. */
  33611. this.material = null;
  33612. /**
  33613. * A reference to the current camera.
  33614. *
  33615. * @type {?Camera}
  33616. * @default null
  33617. */
  33618. this.camera = null;
  33619. /**
  33620. * A reference to the current 3D object.
  33621. *
  33622. * @type {?Object3D}
  33623. * @default null
  33624. */
  33625. this.object = null;
  33626. /**
  33627. * A reference to the current scene.
  33628. *
  33629. * @type {?Scene}
  33630. * @default null
  33631. */
  33632. this.scene = null;
  33633. }
  33634. /**
  33635. * Returns a dictionary for a given node and update map which
  33636. * is used to correctly call node update methods per frame or render.
  33637. *
  33638. * @private
  33639. * @param {WeakMap<Node, Object>} referenceMap - The reference weak map.
  33640. * @param {Node} nodeRef - The reference to the current node.
  33641. * @return {Object<string,WeakMap>} The dictionary.
  33642. */
  33643. _getMaps( referenceMap, nodeRef ) {
  33644. let maps = referenceMap.get( nodeRef );
  33645. if ( maps === undefined ) {
  33646. maps = {
  33647. renderMap: new WeakMap(),
  33648. frameMap: new WeakMap()
  33649. };
  33650. referenceMap.set( nodeRef, maps );
  33651. }
  33652. return maps;
  33653. }
  33654. /**
  33655. * This method executes the {@link Node#updateBefore} for the given node.
  33656. * It makes sure {@link Node#updateBeforeType} is honored meaning the update
  33657. * is only executed once per frame, render or object depending on the update
  33658. * type.
  33659. *
  33660. * @param {Node} node - The node that should be updated.
  33661. */
  33662. updateBeforeNode( node ) {
  33663. const updateType = node.getUpdateBeforeType();
  33664. const reference = node.updateReference( this );
  33665. if ( updateType === NodeUpdateType.FRAME ) {
  33666. const { frameMap } = this._getMaps( this.updateBeforeMap, reference );
  33667. if ( frameMap.get( reference ) !== this.frameId ) {
  33668. if ( node.updateBefore( this ) !== false ) {
  33669. frameMap.set( reference, this.frameId );
  33670. }
  33671. }
  33672. } else if ( updateType === NodeUpdateType.RENDER ) {
  33673. const { renderMap } = this._getMaps( this.updateBeforeMap, reference );
  33674. if ( renderMap.get( reference ) !== this.renderId ) {
  33675. if ( node.updateBefore( this ) !== false ) {
  33676. renderMap.set( reference, this.renderId );
  33677. }
  33678. }
  33679. } else if ( updateType === NodeUpdateType.OBJECT ) {
  33680. node.updateBefore( this );
  33681. }
  33682. }
  33683. /**
  33684. * This method executes the {@link Node#updateAfter} for the given node.
  33685. * It makes sure {@link Node#updateAfterType} is honored meaning the update
  33686. * is only executed once per frame, render or object depending on the update
  33687. * type.
  33688. *
  33689. * @param {Node} node - The node that should be updated.
  33690. */
  33691. updateAfterNode( node ) {
  33692. const updateType = node.getUpdateAfterType();
  33693. const reference = node.updateReference( this );
  33694. if ( updateType === NodeUpdateType.FRAME ) {
  33695. const { frameMap } = this._getMaps( this.updateAfterMap, reference );
  33696. if ( frameMap.get( reference ) !== this.frameId ) {
  33697. if ( node.updateAfter( this ) !== false ) {
  33698. frameMap.set( reference, this.frameId );
  33699. }
  33700. }
  33701. } else if ( updateType === NodeUpdateType.RENDER ) {
  33702. const { renderMap } = this._getMaps( this.updateAfterMap, reference );
  33703. if ( renderMap.get( reference ) !== this.renderId ) {
  33704. if ( node.updateAfter( this ) !== false ) {
  33705. renderMap.set( reference, this.renderId );
  33706. }
  33707. }
  33708. } else if ( updateType === NodeUpdateType.OBJECT ) {
  33709. node.updateAfter( this );
  33710. }
  33711. }
  33712. /**
  33713. * This method executes the {@link Node#update} for the given node.
  33714. * It makes sure {@link Node#updateType} is honored meaning the update
  33715. * is only executed once per frame, render or object depending on the update
  33716. * type.
  33717. *
  33718. * @param {Node} node - The node that should be updated.
  33719. */
  33720. updateNode( node ) {
  33721. const updateType = node.getUpdateType();
  33722. const reference = node.updateReference( this );
  33723. if ( updateType === NodeUpdateType.FRAME ) {
  33724. const { frameMap } = this._getMaps( this.updateMap, reference );
  33725. if ( frameMap.get( reference ) !== this.frameId ) {
  33726. if ( node.update( this ) !== false ) {
  33727. frameMap.set( reference, this.frameId );
  33728. }
  33729. }
  33730. } else if ( updateType === NodeUpdateType.RENDER ) {
  33731. const { renderMap } = this._getMaps( this.updateMap, reference );
  33732. if ( renderMap.get( reference ) !== this.renderId ) {
  33733. if ( node.update( this ) !== false ) {
  33734. renderMap.set( reference, this.renderId );
  33735. }
  33736. }
  33737. } else if ( updateType === NodeUpdateType.OBJECT ) {
  33738. node.update( this );
  33739. }
  33740. }
  33741. /**
  33742. * Updates the internal state of the node frame. This method is
  33743. * called by the renderer in its internal animation loop.
  33744. */
  33745. update() {
  33746. this.frameId ++;
  33747. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  33748. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  33749. this.lastTime = performance.now();
  33750. this.time += this.deltaTime;
  33751. }
  33752. }
  33753. /**
  33754. * Describes the input of a {@link NodeFunction}.
  33755. */
  33756. class NodeFunctionInput {
  33757. /**
  33758. * Constructs a new node function input.
  33759. *
  33760. * @param {string} type - The input type.
  33761. * @param {string} name - The input name.
  33762. * @param {?number} [count=null] - If the input is an Array, count will be the length.
  33763. * @param {('in'|'out'|'inout')} [qualifier=''] - The parameter qualifier (only relevant for GLSL).
  33764. * @param {boolean} [isConst=false] - Whether the input uses a const qualifier or not (only relevant for GLSL).
  33765. */
  33766. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  33767. /**
  33768. * The input type.
  33769. *
  33770. * @type {string}
  33771. */
  33772. this.type = type;
  33773. /**
  33774. * The input name.
  33775. *
  33776. * @type {string}
  33777. */
  33778. this.name = name;
  33779. /**
  33780. * If the input is an Array, count will be the length.
  33781. *
  33782. * @type {?number}
  33783. * @default null
  33784. */
  33785. this.count = count;
  33786. /**
  33787. *The parameter qualifier (only relevant for GLSL).
  33788. *
  33789. * @type {('in'|'out'|'inout')}
  33790. * @default ''
  33791. */
  33792. this.qualifier = qualifier;
  33793. /**
  33794. * Whether the input uses a const qualifier or not (only relevant for GLSL).
  33795. *
  33796. * @type {boolean}
  33797. * @default false
  33798. */
  33799. this.isConst = isConst;
  33800. }
  33801. }
  33802. NodeFunctionInput.isNodeFunctionInput = true;
  33803. /**
  33804. * Module for representing directional lights as nodes.
  33805. *
  33806. * @augments AnalyticLightNode
  33807. */
  33808. class DirectionalLightNode extends AnalyticLightNode {
  33809. static get type() {
  33810. return 'DirectionalLightNode';
  33811. }
  33812. /**
  33813. * Constructs a new directional light node.
  33814. *
  33815. * @param {?DirectionalLight} [light=null] - The directional light source.
  33816. */
  33817. constructor( light = null ) {
  33818. super( light );
  33819. }
  33820. setupDirect() {
  33821. const lightColor = this.colorNode;
  33822. const lightDirection = lightTargetDirection( this.light );
  33823. return { lightDirection, lightColor };
  33824. }
  33825. }
  33826. const _matrix41 = /*@__PURE__*/ new Matrix4();
  33827. const _matrix42 = /*@__PURE__*/ new Matrix4();
  33828. let _ltcLib = null;
  33829. /**
  33830. * Module for representing rect area lights as nodes.
  33831. *
  33832. * @augments AnalyticLightNode
  33833. */
  33834. class RectAreaLightNode extends AnalyticLightNode {
  33835. static get type() {
  33836. return 'RectAreaLightNode';
  33837. }
  33838. /**
  33839. * Constructs a new rect area light node.
  33840. *
  33841. * @param {?RectAreaLight} [light=null] - The rect area light source.
  33842. */
  33843. constructor( light = null ) {
  33844. super( light );
  33845. /**
  33846. * Uniform node representing the half height of the are light.
  33847. *
  33848. * @type {UniformNode<vec3>}
  33849. */
  33850. this.halfHeight = uniform( new Vector3() ).setGroup( renderGroup );
  33851. /**
  33852. * Uniform node representing the half width of the are light.
  33853. *
  33854. * @type {UniformNode<vec3>}
  33855. */
  33856. this.halfWidth = uniform( new Vector3() ).setGroup( renderGroup );
  33857. /**
  33858. * The `updateType` is set to `NodeUpdateType.RENDER` since the light
  33859. * relies on `viewMatrix` which might vary per render call.
  33860. *
  33861. * @type {string}
  33862. * @default 'render'
  33863. */
  33864. this.updateType = NodeUpdateType.RENDER;
  33865. }
  33866. /**
  33867. * Overwritten to updated rect area light specific uniforms.
  33868. *
  33869. * @param {NodeFrame} frame - A reference to the current node frame.
  33870. */
  33871. update( frame ) {
  33872. super.update( frame );
  33873. const { light } = this;
  33874. const viewMatrix = frame.camera.matrixWorldInverse;
  33875. _matrix42.identity();
  33876. _matrix41.copy( light.matrixWorld );
  33877. _matrix41.premultiply( viewMatrix );
  33878. _matrix42.extractRotation( _matrix41 );
  33879. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  33880. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  33881. this.halfWidth.value.applyMatrix4( _matrix42 );
  33882. this.halfHeight.value.applyMatrix4( _matrix42 );
  33883. }
  33884. setupDirectRectArea( builder ) {
  33885. let ltc_1, ltc_2;
  33886. if ( builder.isAvailable( 'float32Filterable' ) ) {
  33887. ltc_1 = texture( _ltcLib.LTC_FLOAT_1 );
  33888. ltc_2 = texture( _ltcLib.LTC_FLOAT_2 );
  33889. } else {
  33890. ltc_1 = texture( _ltcLib.LTC_HALF_1 );
  33891. ltc_2 = texture( _ltcLib.LTC_HALF_2 );
  33892. }
  33893. const { colorNode, light } = this;
  33894. const lightPosition = lightViewPosition( light );
  33895. return {
  33896. lightColor: colorNode,
  33897. lightPosition,
  33898. halfWidth: this.halfWidth,
  33899. halfHeight: this.halfHeight,
  33900. ltc_1,
  33901. ltc_2
  33902. };
  33903. }
  33904. /**
  33905. * Used to configure the internal BRDF approximation texture data.
  33906. *
  33907. * @param {RectAreaLightTexturesLib} ltc - The BRDF approximation texture data.
  33908. */
  33909. static setLTC( ltc ) {
  33910. _ltcLib = ltc;
  33911. }
  33912. }
  33913. /**
  33914. * Module for representing spot lights as nodes.
  33915. *
  33916. * @augments AnalyticLightNode
  33917. */
  33918. class SpotLightNode extends AnalyticLightNode {
  33919. static get type() {
  33920. return 'SpotLightNode';
  33921. }
  33922. /**
  33923. * Constructs a new spot light node.
  33924. *
  33925. * @param {?SpotLight} [light=null] - The spot light source.
  33926. */
  33927. constructor( light = null ) {
  33928. super( light );
  33929. /**
  33930. * Uniform node representing the cone cosine.
  33931. *
  33932. * @type {UniformNode<float>}
  33933. */
  33934. this.coneCosNode = uniform( 0 ).setGroup( renderGroup );
  33935. /**
  33936. * Uniform node representing the penumbra cosine.
  33937. *
  33938. * @type {UniformNode<float>}
  33939. */
  33940. this.penumbraCosNode = uniform( 0 ).setGroup( renderGroup );
  33941. /**
  33942. * Uniform node representing the cutoff distance.
  33943. *
  33944. * @type {UniformNode<float>}
  33945. */
  33946. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  33947. /**
  33948. * Uniform node representing the decay exponent.
  33949. *
  33950. * @type {UniformNode<float>}
  33951. */
  33952. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  33953. /**
  33954. * Uniform node representing the light color.
  33955. *
  33956. * @type {UniformNode<Color>}
  33957. */
  33958. this.colorNode = uniform( this.color ).setGroup( renderGroup );
  33959. }
  33960. /**
  33961. * Overwritten to updated spot light specific uniforms.
  33962. *
  33963. * @param {NodeFrame} frame - A reference to the current node frame.
  33964. */
  33965. update( frame ) {
  33966. super.update( frame );
  33967. const { light } = this;
  33968. this.coneCosNode.value = Math.cos( light.angle );
  33969. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  33970. this.cutoffDistanceNode.value = light.distance;
  33971. this.decayExponentNode.value = light.decay;
  33972. }
  33973. /**
  33974. * Computes the spot attenuation for the given angle.
  33975. *
  33976. * @param {NodeBuilder} builder - The node builder.
  33977. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  33978. * @return {Node<float>} The spot attenuation.
  33979. */
  33980. getSpotAttenuation( builder, angleCosine ) {
  33981. const { coneCosNode, penumbraCosNode } = this;
  33982. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  33983. }
  33984. getLightCoord( builder ) {
  33985. const properties = builder.getNodeProperties( this );
  33986. let projectionUV = properties.projectionUV;
  33987. if ( projectionUV === undefined ) {
  33988. projectionUV = lightProjectionUV( this.light, builder.context.positionWorld );
  33989. properties.projectionUV = projectionUV;
  33990. }
  33991. return projectionUV;
  33992. }
  33993. setupDirect( builder ) {
  33994. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  33995. const lightVector = this.getLightVector( builder );
  33996. const lightDirection = lightVector.normalize();
  33997. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  33998. const spotAttenuation = this.getSpotAttenuation( builder, angleCos );
  33999. const lightDistance = lightVector.length();
  34000. const lightAttenuation = getDistanceAttenuation( {
  34001. lightDistance,
  34002. cutoffDistance: cutoffDistanceNode,
  34003. decayExponent: decayExponentNode
  34004. } );
  34005. let lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  34006. let projected, lightCoord;
  34007. if ( light.colorNode ) {
  34008. lightCoord = this.getLightCoord( builder );
  34009. projected = light.colorNode( lightCoord );
  34010. } else if ( light.map ) {
  34011. lightCoord = this.getLightCoord( builder );
  34012. projected = texture( light.map, lightCoord.xy ).onRenderUpdate( () => light.map );
  34013. }
  34014. if ( projected ) {
  34015. const inSpotLightMap = lightCoord.mul( 2. ).sub( 1. ).abs().lessThan( 1. ).all();
  34016. lightColor = inSpotLightMap.select( lightColor.mul( projected ), lightColor );
  34017. }
  34018. return { lightColor, lightDirection };
  34019. }
  34020. }
  34021. /**
  34022. * An IES version of the default spot light node.
  34023. *
  34024. * @augments SpotLightNode
  34025. */
  34026. class IESSpotLightNode extends SpotLightNode {
  34027. static get type() {
  34028. return 'IESSpotLightNode';
  34029. }
  34030. /**
  34031. * Overwrites the default implementation to compute an IES conform spot attenuation.
  34032. *
  34033. * @param {NodeBuilder} builder - The node builder.
  34034. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  34035. * @return {Node<float>} The spot attenuation.
  34036. */
  34037. getSpotAttenuation( builder, angleCosine ) {
  34038. const iesMap = this.light.iesMap;
  34039. let spotAttenuation = null;
  34040. if ( iesMap && iesMap.isTexture === true ) {
  34041. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  34042. spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r;
  34043. } else {
  34044. spotAttenuation = super.getSpotAttenuation( angleCosine );
  34045. }
  34046. return spotAttenuation;
  34047. }
  34048. }
  34049. const sdBox = /*@__PURE__*/ Fn( ( [ p, b ] ) => {
  34050. const d = p.abs().sub( b );
  34051. return length( max$1( d, 0.0 ) ).add( min$1( max$1( d.x, d.y ), 0.0 ) );
  34052. } );
  34053. /**
  34054. * An implementation of a projector light node.
  34055. *
  34056. * @augments SpotLightNode
  34057. */
  34058. class ProjectorLightNode extends SpotLightNode {
  34059. static get type() {
  34060. return 'ProjectorLightNode';
  34061. }
  34062. update( frame ) {
  34063. super.update( frame );
  34064. const light = this.light;
  34065. this.penumbraCosNode.value = Math.min( Math.cos( light.angle * ( 1 - light.penumbra ) ), .99999 );
  34066. if ( light.aspect === null ) {
  34067. let aspect = 1;
  34068. if ( light.map !== null ) {
  34069. aspect = light.map.width / light.map.height;
  34070. }
  34071. light.shadow.aspect = aspect;
  34072. } else {
  34073. light.shadow.aspect = light.aspect;
  34074. }
  34075. }
  34076. /**
  34077. * Overwrites the default implementation to compute projection attenuation.
  34078. *
  34079. * @param {NodeBuilder} builder - The node builder.
  34080. * @return {Node<float>} The spot attenuation.
  34081. */
  34082. getSpotAttenuation( builder ) {
  34083. const penumbraCos = this.penumbraCosNode;
  34084. const spotLightCoord = this.getLightCoord( builder );
  34085. const coord = spotLightCoord.xyz.div( spotLightCoord.w );
  34086. const boxDist = sdBox( coord.xy.sub( vec2( 0.5 ) ), vec2( 0.5 ) );
  34087. const angleFactor = div( -1, sub( 1.0, acos( penumbraCos ) ).sub( 1.0 ) );
  34088. const attenuation = saturate( boxDist.mul( -2 ).mul( angleFactor ) );
  34089. return attenuation;
  34090. }
  34091. }
  34092. /**
  34093. * Module for representing ambient lights as nodes.
  34094. *
  34095. * @augments AnalyticLightNode
  34096. */
  34097. class AmbientLightNode extends AnalyticLightNode {
  34098. static get type() {
  34099. return 'AmbientLightNode';
  34100. }
  34101. /**
  34102. * Constructs a new ambient light node.
  34103. *
  34104. * @param {?AmbientLight} [light=null] - The ambient light source.
  34105. */
  34106. constructor( light = null ) {
  34107. super( light );
  34108. }
  34109. setup( { context } ) {
  34110. context.irradiance.addAssign( this.colorNode );
  34111. }
  34112. }
  34113. /**
  34114. * Module for representing hemisphere lights as nodes.
  34115. *
  34116. * @augments AnalyticLightNode
  34117. */
  34118. class HemisphereLightNode extends AnalyticLightNode {
  34119. static get type() {
  34120. return 'HemisphereLightNode';
  34121. }
  34122. /**
  34123. * Constructs a new hemisphere light node.
  34124. *
  34125. * @param {?HemisphereLight} [light=null] - The hemisphere light source.
  34126. */
  34127. constructor( light = null ) {
  34128. super( light );
  34129. /**
  34130. * Uniform node representing the light's position.
  34131. *
  34132. * @type {UniformNode<vec3>}
  34133. */
  34134. this.lightPositionNode = lightPosition( light );
  34135. /**
  34136. * A node representing the light's direction.
  34137. *
  34138. * @type {Node<vec3>}
  34139. */
  34140. this.lightDirectionNode = this.lightPositionNode.normalize();
  34141. /**
  34142. * Uniform node representing the light's ground color.
  34143. *
  34144. * @type {UniformNode<vec3>}
  34145. */
  34146. this.groundColorNode = uniform( new Color() ).setGroup( renderGroup );
  34147. }
  34148. /**
  34149. * Overwritten to updated hemisphere light specific uniforms.
  34150. *
  34151. * @param {NodeFrame} frame - A reference to the current node frame.
  34152. */
  34153. update( frame ) {
  34154. const { light } = this;
  34155. super.update( frame );
  34156. this.lightPositionNode.object3d = light;
  34157. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  34158. }
  34159. setup( builder ) {
  34160. const { colorNode, groundColorNode, lightDirectionNode } = this;
  34161. const dotNL = normalWorld.dot( lightDirectionNode );
  34162. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  34163. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  34164. builder.context.irradiance.addAssign( irradiance );
  34165. }
  34166. }
  34167. /**
  34168. * Module for representing light probes as nodes.
  34169. *
  34170. * @augments AnalyticLightNode
  34171. */
  34172. class LightProbeNode extends AnalyticLightNode {
  34173. static get type() {
  34174. return 'LightProbeNode';
  34175. }
  34176. /**
  34177. * Constructs a new light probe node.
  34178. *
  34179. * @param {?LightProbe} [light=null] - The light probe.
  34180. */
  34181. constructor( light = null ) {
  34182. super( light );
  34183. const array = [];
  34184. for ( let i = 0; i < 9; i ++ ) array.push( new Vector3() );
  34185. /**
  34186. * Light probe represented as a uniform of spherical harmonics.
  34187. *
  34188. * @type {UniformArrayNode}
  34189. */
  34190. this.lightProbe = uniformArray( array );
  34191. }
  34192. /**
  34193. * Overwritten to updated light probe specific uniforms.
  34194. *
  34195. * @param {NodeFrame} frame - A reference to the current node frame.
  34196. */
  34197. update( frame ) {
  34198. const { light } = this;
  34199. super.update( frame );
  34200. //
  34201. for ( let i = 0; i < 9; i ++ ) {
  34202. this.lightProbe.array[ i ].copy( light.sh.coefficients[ i ] ).multiplyScalar( light.intensity );
  34203. }
  34204. }
  34205. setup( builder ) {
  34206. const irradiance = getShIrradianceAt( normalWorld, this.lightProbe );
  34207. builder.context.irradiance.addAssign( irradiance );
  34208. }
  34209. }
  34210. /**
  34211. * Base class for node parsers. A derived parser must be implemented
  34212. * for each supported native shader language.
  34213. */
  34214. class NodeParser {
  34215. /**
  34216. * The method parses the given native code an returns a node function.
  34217. *
  34218. * @abstract
  34219. * @param {string} source - The native shader code.
  34220. * @return {NodeFunction} A node function.
  34221. */
  34222. parseFunction( /*source*/ ) {
  34223. console.warn( 'Abstract function.' );
  34224. }
  34225. }
  34226. /**
  34227. * Base class for node functions. A derived module must be implemented
  34228. * for each supported native shader language. Similar to other `Node*` modules,
  34229. * this class is only relevant during the building process and not used
  34230. * in user-level code.
  34231. */
  34232. class NodeFunction {
  34233. /**
  34234. * Constructs a new node function.
  34235. *
  34236. * @param {string} type - The node type. This type is the return type of the node function.
  34237. * @param {Array<NodeFunctionInput>} inputs - The function's inputs.
  34238. * @param {string} [name=''] - The function's name.
  34239. * @param {string} [precision=''] - The precision qualifier.
  34240. */
  34241. constructor( type, inputs, name = '', precision = '' ) {
  34242. /**
  34243. * The node type. This type is the return type of the node function.
  34244. *
  34245. * @type {string}
  34246. */
  34247. this.type = type;
  34248. /**
  34249. * The function's inputs.
  34250. *
  34251. * @type {Array<NodeFunctionInput>}
  34252. */
  34253. this.inputs = inputs;
  34254. /**
  34255. * The name of the uniform.
  34256. *
  34257. * @type {string}
  34258. * @default ''
  34259. */
  34260. this.name = name;
  34261. /**
  34262. * The precision qualifier.
  34263. *
  34264. * @type {string}
  34265. * @default ''
  34266. */
  34267. this.precision = precision;
  34268. }
  34269. /**
  34270. * This method returns the native code of the node function.
  34271. *
  34272. * @abstract
  34273. * @param {string} name - The function's name.
  34274. * @return {string} A shader code.
  34275. */
  34276. getCode( /*name = this.name*/ ) {
  34277. console.warn( 'Abstract function.' );
  34278. }
  34279. }
  34280. NodeFunction.isNodeFunction = true;
  34281. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  34282. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  34283. const pragmaMain = '#pragma main';
  34284. const parse$1 = ( source ) => {
  34285. source = source.trim();
  34286. const pragmaMainIndex = source.indexOf( pragmaMain );
  34287. const mainCode = pragmaMainIndex !== -1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  34288. const declaration = mainCode.match( declarationRegexp$1 );
  34289. if ( declaration !== null && declaration.length === 5 ) {
  34290. // tokenizer
  34291. const inputsCode = declaration[ 4 ];
  34292. const propsMatches = [];
  34293. let nameMatch = null;
  34294. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  34295. propsMatches.push( nameMatch );
  34296. }
  34297. // parser
  34298. const inputs = [];
  34299. let i = 0;
  34300. while ( i < propsMatches.length ) {
  34301. const isConst = propsMatches[ i ][ 0 ] === 'const';
  34302. if ( isConst === true ) {
  34303. i ++;
  34304. }
  34305. let qualifier = propsMatches[ i ][ 0 ];
  34306. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  34307. i ++;
  34308. } else {
  34309. qualifier = '';
  34310. }
  34311. const type = propsMatches[ i ++ ][ 0 ];
  34312. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  34313. if ( Number.isNaN( count ) === false ) i ++;
  34314. else count = null;
  34315. const name = propsMatches[ i ++ ][ 0 ];
  34316. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  34317. }
  34318. //
  34319. const blockCode = mainCode.substring( declaration[ 0 ].length );
  34320. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  34321. const type = declaration[ 2 ];
  34322. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  34323. const headerCode = pragmaMainIndex !== -1 ? source.slice( 0, pragmaMainIndex ) : '';
  34324. return {
  34325. type,
  34326. inputs,
  34327. name,
  34328. precision,
  34329. inputsCode,
  34330. blockCode,
  34331. headerCode
  34332. };
  34333. } else {
  34334. throw new Error( 'FunctionNode: Function is not a GLSL code.' );
  34335. }
  34336. };
  34337. /**
  34338. * This class represents a GLSL node function.
  34339. *
  34340. * @augments NodeFunction
  34341. */
  34342. class GLSLNodeFunction extends NodeFunction {
  34343. /**
  34344. * Constructs a new GLSL node function.
  34345. *
  34346. * @param {string} source - The GLSL source.
  34347. */
  34348. constructor( source ) {
  34349. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  34350. super( type, inputs, name, precision );
  34351. this.inputsCode = inputsCode;
  34352. this.blockCode = blockCode;
  34353. this.headerCode = headerCode;
  34354. }
  34355. /**
  34356. * This method returns the GLSL code of the node function.
  34357. *
  34358. * @param {string} [name=this.name] - The function's name.
  34359. * @return {string} The shader code.
  34360. */
  34361. getCode( name = this.name ) {
  34362. let code;
  34363. const blockCode = this.blockCode;
  34364. if ( blockCode !== '' ) {
  34365. const { type, inputsCode, headerCode, precision } = this;
  34366. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  34367. if ( precision !== '' ) {
  34368. declarationCode = `${ precision } ${ declarationCode }`;
  34369. }
  34370. code = headerCode + declarationCode + blockCode;
  34371. } else {
  34372. // interface function
  34373. code = '';
  34374. }
  34375. return code;
  34376. }
  34377. }
  34378. /**
  34379. * A GLSL node parser.
  34380. *
  34381. * @augments NodeParser
  34382. */
  34383. class GLSLNodeParser extends NodeParser {
  34384. /**
  34385. * The method parses the given GLSL code an returns a node function.
  34386. *
  34387. * @param {string} source - The GLSL code.
  34388. * @return {GLSLNodeFunction} A node function.
  34389. */
  34390. parseFunction( source ) {
  34391. return new GLSLNodeFunction( source );
  34392. }
  34393. }
  34394. const _outputNodeMap = new WeakMap();
  34395. const _chainKeys$2 = [];
  34396. const _cacheKeyValues = [];
  34397. /**
  34398. * This renderer module manages node-related objects and is the
  34399. * primary interface between the renderer and the node system.
  34400. *
  34401. * @private
  34402. * @augments DataMap
  34403. */
  34404. class Nodes extends DataMap {
  34405. /**
  34406. * Constructs a new nodes management component.
  34407. *
  34408. * @param {Renderer} renderer - The renderer.
  34409. * @param {Backend} backend - The renderer's backend.
  34410. */
  34411. constructor( renderer, backend ) {
  34412. super();
  34413. /**
  34414. * The renderer.
  34415. *
  34416. * @type {Renderer}
  34417. */
  34418. this.renderer = renderer;
  34419. /**
  34420. * The renderer's backend.
  34421. *
  34422. * @type {Backend}
  34423. */
  34424. this.backend = backend;
  34425. /**
  34426. * The node frame.
  34427. *
  34428. * @type {Renderer}
  34429. */
  34430. this.nodeFrame = new NodeFrame();
  34431. /**
  34432. * A cache for managing node builder states.
  34433. *
  34434. * @type {Map<number,NodeBuilderState>}
  34435. */
  34436. this.nodeBuilderCache = new Map();
  34437. /**
  34438. * A cache for managing data cache key data.
  34439. *
  34440. * @type {ChainMap}
  34441. */
  34442. this.callHashCache = new ChainMap();
  34443. /**
  34444. * A cache for managing node uniforms group data.
  34445. *
  34446. * @type {ChainMap}
  34447. */
  34448. this.groupsData = new ChainMap();
  34449. /**
  34450. * A cache for managing node objects of
  34451. * scene properties like fog or environments.
  34452. *
  34453. * @type {Object<string,WeakMap>}
  34454. */
  34455. this.cacheLib = {};
  34456. }
  34457. /**
  34458. * Returns `true` if the given node uniforms group must be updated or not.
  34459. *
  34460. * @param {NodeUniformsGroup} nodeUniformsGroup - The node uniforms group.
  34461. * @return {boolean} Whether the node uniforms group requires an update or not.
  34462. */
  34463. updateGroup( nodeUniformsGroup ) {
  34464. const groupNode = nodeUniformsGroup.groupNode;
  34465. const name = groupNode.name;
  34466. // objectGroup is always updated
  34467. if ( name === objectGroup.name ) return true;
  34468. // renderGroup is updated once per render/compute call
  34469. if ( name === renderGroup.name ) {
  34470. const uniformsGroupData = this.get( nodeUniformsGroup );
  34471. const renderId = this.nodeFrame.renderId;
  34472. if ( uniformsGroupData.renderId !== renderId ) {
  34473. uniformsGroupData.renderId = renderId;
  34474. return true;
  34475. }
  34476. return false;
  34477. }
  34478. // frameGroup is updated once per frame
  34479. if ( name === frameGroup.name ) {
  34480. const uniformsGroupData = this.get( nodeUniformsGroup );
  34481. const frameId = this.nodeFrame.frameId;
  34482. if ( uniformsGroupData.frameId !== frameId ) {
  34483. uniformsGroupData.frameId = frameId;
  34484. return true;
  34485. }
  34486. return false;
  34487. }
  34488. // other groups are updated just when groupNode.needsUpdate is true
  34489. _chainKeys$2[ 0 ] = groupNode;
  34490. _chainKeys$2[ 1 ] = nodeUniformsGroup;
  34491. let groupData = this.groupsData.get( _chainKeys$2 );
  34492. if ( groupData === undefined ) this.groupsData.set( _chainKeys$2, groupData = {} );
  34493. _chainKeys$2.length = 0;
  34494. if ( groupData.version !== groupNode.version ) {
  34495. groupData.version = groupNode.version;
  34496. return true;
  34497. }
  34498. return false;
  34499. }
  34500. /**
  34501. * Returns the cache key for the given render object.
  34502. *
  34503. * @param {RenderObject} renderObject - The render object.
  34504. * @return {number} The cache key.
  34505. */
  34506. getForRenderCacheKey( renderObject ) {
  34507. return renderObject.initialCacheKey;
  34508. }
  34509. /**
  34510. * Returns a node builder state for the given render object.
  34511. *
  34512. * @param {RenderObject} renderObject - The render object.
  34513. * @return {NodeBuilderState} The node builder state.
  34514. */
  34515. getForRender( renderObject ) {
  34516. const renderObjectData = this.get( renderObject );
  34517. let nodeBuilderState = renderObjectData.nodeBuilderState;
  34518. if ( nodeBuilderState === undefined ) {
  34519. const { nodeBuilderCache } = this;
  34520. const cacheKey = this.getForRenderCacheKey( renderObject );
  34521. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  34522. if ( nodeBuilderState === undefined ) {
  34523. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  34524. nodeBuilder.scene = renderObject.scene;
  34525. nodeBuilder.material = renderObject.material;
  34526. nodeBuilder.camera = renderObject.camera;
  34527. nodeBuilder.context.material = renderObject.material;
  34528. nodeBuilder.lightsNode = renderObject.lightsNode;
  34529. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  34530. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  34531. nodeBuilder.clippingContext = renderObject.clippingContext;
  34532. if ( this.renderer.getOutputRenderTarget() ? this.renderer.getOutputRenderTarget().multiview : false ) {
  34533. nodeBuilder.enableMultiview();
  34534. }
  34535. nodeBuilder.build();
  34536. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  34537. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  34538. }
  34539. nodeBuilderState.usedTimes ++;
  34540. renderObjectData.nodeBuilderState = nodeBuilderState;
  34541. }
  34542. return nodeBuilderState;
  34543. }
  34544. /**
  34545. * Deletes the given object from the internal data map
  34546. *
  34547. * @param {any} object - The object to delete.
  34548. * @return {?Object} The deleted dictionary.
  34549. */
  34550. delete( object ) {
  34551. if ( object.isRenderObject ) {
  34552. const nodeBuilderState = this.get( object ).nodeBuilderState;
  34553. nodeBuilderState.usedTimes --;
  34554. if ( nodeBuilderState.usedTimes === 0 ) {
  34555. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  34556. }
  34557. }
  34558. return super.delete( object );
  34559. }
  34560. /**
  34561. * Returns a node builder state for the given compute node.
  34562. *
  34563. * @param {Node} computeNode - The compute node.
  34564. * @return {NodeBuilderState} The node builder state.
  34565. */
  34566. getForCompute( computeNode ) {
  34567. const computeData = this.get( computeNode );
  34568. let nodeBuilderState = computeData.nodeBuilderState;
  34569. if ( nodeBuilderState === undefined ) {
  34570. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  34571. nodeBuilder.build();
  34572. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  34573. computeData.nodeBuilderState = nodeBuilderState;
  34574. }
  34575. return nodeBuilderState;
  34576. }
  34577. /**
  34578. * Creates a node builder state for the given node builder.
  34579. *
  34580. * @private
  34581. * @param {NodeBuilder} nodeBuilder - The node builder.
  34582. * @return {NodeBuilderState} The node builder state.
  34583. */
  34584. _createNodeBuilderState( nodeBuilder ) {
  34585. return new NodeBuilderState(
  34586. nodeBuilder.vertexShader,
  34587. nodeBuilder.fragmentShader,
  34588. nodeBuilder.computeShader,
  34589. nodeBuilder.getAttributesArray(),
  34590. nodeBuilder.getBindings(),
  34591. nodeBuilder.updateNodes,
  34592. nodeBuilder.updateBeforeNodes,
  34593. nodeBuilder.updateAfterNodes,
  34594. nodeBuilder.observer,
  34595. nodeBuilder.transforms
  34596. );
  34597. }
  34598. /**
  34599. * Returns an environment node for the current configured
  34600. * scene environment.
  34601. *
  34602. * @param {Scene} scene - The scene.
  34603. * @return {Node} A node representing the current scene environment.
  34604. */
  34605. getEnvironmentNode( scene ) {
  34606. this.updateEnvironment( scene );
  34607. let environmentNode = null;
  34608. if ( scene.environmentNode && scene.environmentNode.isNode ) {
  34609. environmentNode = scene.environmentNode;
  34610. } else {
  34611. const sceneData = this.get( scene );
  34612. if ( sceneData.environmentNode ) {
  34613. environmentNode = sceneData.environmentNode;
  34614. }
  34615. }
  34616. return environmentNode;
  34617. }
  34618. /**
  34619. * Returns a background node for the current configured
  34620. * scene background.
  34621. *
  34622. * @param {Scene} scene - The scene.
  34623. * @return {Node} A node representing the current scene background.
  34624. */
  34625. getBackgroundNode( scene ) {
  34626. this.updateBackground( scene );
  34627. let backgroundNode = null;
  34628. if ( scene.backgroundNode && scene.backgroundNode.isNode ) {
  34629. backgroundNode = scene.backgroundNode;
  34630. } else {
  34631. const sceneData = this.get( scene );
  34632. if ( sceneData.backgroundNode ) {
  34633. backgroundNode = sceneData.backgroundNode;
  34634. }
  34635. }
  34636. return backgroundNode;
  34637. }
  34638. /**
  34639. * Returns a fog node for the current configured scene fog.
  34640. *
  34641. * @param {Scene} scene - The scene.
  34642. * @return {Node} A node representing the current scene fog.
  34643. */
  34644. getFogNode( scene ) {
  34645. this.updateFog( scene );
  34646. return scene.fogNode || this.get( scene ).fogNode || null;
  34647. }
  34648. /**
  34649. * Returns a cache key for the given scene and lights node.
  34650. * This key is used by `RenderObject` as a part of the dynamic
  34651. * cache key (a key that must be checked every time the render
  34652. * objects is drawn).
  34653. *
  34654. * @param {Scene} scene - The scene.
  34655. * @param {LightsNode} lightsNode - The lights node.
  34656. * @return {number} The cache key.
  34657. */
  34658. getCacheKey( scene, lightsNode ) {
  34659. _chainKeys$2[ 0 ] = scene;
  34660. _chainKeys$2[ 1 ] = lightsNode;
  34661. const callId = this.renderer.info.calls;
  34662. const cacheKeyData = this.callHashCache.get( _chainKeys$2 ) || {};
  34663. if ( cacheKeyData.callId !== callId ) {
  34664. const environmentNode = this.getEnvironmentNode( scene );
  34665. const fogNode = this.getFogNode( scene );
  34666. if ( lightsNode ) _cacheKeyValues.push( lightsNode.getCacheKey( true ) );
  34667. if ( environmentNode ) _cacheKeyValues.push( environmentNode.getCacheKey() );
  34668. if ( fogNode ) _cacheKeyValues.push( fogNode.getCacheKey() );
  34669. _cacheKeyValues.push( this.renderer.getOutputRenderTarget() && this.renderer.getOutputRenderTarget().multiview ? 1 : 0 );
  34670. _cacheKeyValues.push( this.renderer.shadowMap.enabled ? 1 : 0 );
  34671. cacheKeyData.callId = callId;
  34672. cacheKeyData.cacheKey = hashArray( _cacheKeyValues );
  34673. this.callHashCache.set( _chainKeys$2, cacheKeyData );
  34674. _cacheKeyValues.length = 0;
  34675. }
  34676. _chainKeys$2.length = 0;
  34677. return cacheKeyData.cacheKey;
  34678. }
  34679. /**
  34680. * A boolean that indicates whether tone mapping should be enabled
  34681. * or not.
  34682. *
  34683. * @type {boolean}
  34684. */
  34685. get isToneMappingState() {
  34686. return this.renderer.getRenderTarget() ? false : true;
  34687. }
  34688. /**
  34689. * If a scene background is configured, this method makes sure to
  34690. * represent the background with a corresponding node-based implementation.
  34691. *
  34692. * @param {Scene} scene - The scene.
  34693. */
  34694. updateBackground( scene ) {
  34695. const sceneData = this.get( scene );
  34696. const background = scene.background;
  34697. if ( background ) {
  34698. const forceUpdate = ( scene.backgroundBlurriness === 0 && sceneData.backgroundBlurriness > 0 ) || ( scene.backgroundBlurriness > 0 && sceneData.backgroundBlurriness === 0 );
  34699. if ( sceneData.background !== background || forceUpdate ) {
  34700. const backgroundNode = this.getCacheNode( 'background', background, () => {
  34701. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping || background.mapping === CubeUVReflectionMapping ) ) {
  34702. if ( scene.backgroundBlurriness > 0 || background.mapping === CubeUVReflectionMapping ) {
  34703. return pmremTexture( background );
  34704. } else {
  34705. let envMap;
  34706. if ( background.isCubeTexture === true ) {
  34707. envMap = cubeTexture( background );
  34708. } else {
  34709. envMap = texture( background );
  34710. }
  34711. return cubeMapNode( envMap );
  34712. }
  34713. } else if ( background.isTexture === true ) {
  34714. return texture( background, screenUV.flipY() ).setUpdateMatrix( true );
  34715. } else if ( background.isColor !== true ) {
  34716. console.error( 'WebGPUNodes: Unsupported background configuration.', background );
  34717. }
  34718. }, forceUpdate );
  34719. sceneData.backgroundNode = backgroundNode;
  34720. sceneData.background = background;
  34721. sceneData.backgroundBlurriness = scene.backgroundBlurriness;
  34722. }
  34723. } else if ( sceneData.backgroundNode ) {
  34724. delete sceneData.backgroundNode;
  34725. delete sceneData.background;
  34726. }
  34727. }
  34728. /**
  34729. * This method is part of the caching of nodes which are used to represents the
  34730. * scene's background, fog or environment.
  34731. *
  34732. * @param {string} type - The type of object to cache.
  34733. * @param {Object} object - The object.
  34734. * @param {Function} callback - A callback that produces a node representation for the given object.
  34735. * @param {boolean} [forceUpdate=false] - Whether an update should be enforced or not.
  34736. * @return {Node} The node representation.
  34737. */
  34738. getCacheNode( type, object, callback, forceUpdate = false ) {
  34739. const nodeCache = this.cacheLib[ type ] || ( this.cacheLib[ type ] = new WeakMap() );
  34740. let node = nodeCache.get( object );
  34741. if ( node === undefined || forceUpdate ) {
  34742. node = callback();
  34743. nodeCache.set( object, node );
  34744. }
  34745. return node;
  34746. }
  34747. /**
  34748. * If a scene fog is configured, this method makes sure to
  34749. * represent the fog with a corresponding node-based implementation.
  34750. *
  34751. * @param {Scene} scene - The scene.
  34752. */
  34753. updateFog( scene ) {
  34754. const sceneData = this.get( scene );
  34755. const sceneFog = scene.fog;
  34756. if ( sceneFog ) {
  34757. if ( sceneData.fog !== sceneFog ) {
  34758. const fogNode = this.getCacheNode( 'fog', sceneFog, () => {
  34759. if ( sceneFog.isFogExp2 ) {
  34760. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  34761. const density = reference( 'density', 'float', sceneFog ).setGroup( renderGroup );
  34762. return fog( color, densityFogFactor( density ) );
  34763. } else if ( sceneFog.isFog ) {
  34764. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  34765. const near = reference( 'near', 'float', sceneFog ).setGroup( renderGroup );
  34766. const far = reference( 'far', 'float', sceneFog ).setGroup( renderGroup );
  34767. return fog( color, rangeFogFactor( near, far ) );
  34768. } else {
  34769. console.error( 'THREE.Renderer: Unsupported fog configuration.', sceneFog );
  34770. }
  34771. } );
  34772. sceneData.fogNode = fogNode;
  34773. sceneData.fog = sceneFog;
  34774. }
  34775. } else {
  34776. delete sceneData.fogNode;
  34777. delete sceneData.fog;
  34778. }
  34779. }
  34780. /**
  34781. * If a scene environment is configured, this method makes sure to
  34782. * represent the environment with a corresponding node-based implementation.
  34783. *
  34784. * @param {Scene} scene - The scene.
  34785. */
  34786. updateEnvironment( scene ) {
  34787. const sceneData = this.get( scene );
  34788. const environment = scene.environment;
  34789. if ( environment ) {
  34790. if ( sceneData.environment !== environment ) {
  34791. const environmentNode = this.getCacheNode( 'environment', environment, () => {
  34792. if ( environment.isCubeTexture === true ) {
  34793. return cubeTexture( environment );
  34794. } else if ( environment.isTexture === true ) {
  34795. return texture( environment );
  34796. } else {
  34797. console.error( 'Nodes: Unsupported environment configuration.', environment );
  34798. }
  34799. } );
  34800. sceneData.environmentNode = environmentNode;
  34801. sceneData.environment = environment;
  34802. }
  34803. } else if ( sceneData.environmentNode ) {
  34804. delete sceneData.environmentNode;
  34805. delete sceneData.environment;
  34806. }
  34807. }
  34808. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  34809. const nodeFrame = this.nodeFrame;
  34810. nodeFrame.renderer = renderer;
  34811. nodeFrame.scene = scene;
  34812. nodeFrame.object = object;
  34813. nodeFrame.camera = camera;
  34814. nodeFrame.material = material;
  34815. return nodeFrame;
  34816. }
  34817. getNodeFrameForRender( renderObject ) {
  34818. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  34819. }
  34820. /**
  34821. * Returns the current output cache key.
  34822. *
  34823. * @return {string} The output cache key.
  34824. */
  34825. getOutputCacheKey() {
  34826. const renderer = this.renderer;
  34827. return renderer.toneMapping + ',' + renderer.currentColorSpace + ',' + renderer.xr.isPresenting;
  34828. }
  34829. /**
  34830. * Checks if the output configuration (tone mapping and color space) for
  34831. * the given target has changed.
  34832. *
  34833. * @param {Texture} outputTarget - The output target.
  34834. * @return {boolean} Whether the output configuration has changed or not.
  34835. */
  34836. hasOutputChange( outputTarget ) {
  34837. const cacheKey = _outputNodeMap.get( outputTarget );
  34838. return cacheKey !== this.getOutputCacheKey();
  34839. }
  34840. /**
  34841. * Returns a node that represents the output configuration (tone mapping and
  34842. * color space) for the current target.
  34843. *
  34844. * @param {Texture} outputTarget - The output target.
  34845. * @return {Node} The output node.
  34846. */
  34847. getOutputNode( outputTarget ) {
  34848. const renderer = this.renderer;
  34849. const cacheKey = this.getOutputCacheKey();
  34850. const output = outputTarget.isArrayTexture ?
  34851. texture3D( outputTarget, vec3( screenUV, builtin( 'gl_ViewID_OVR' ) ) ).renderOutput( renderer.toneMapping, renderer.currentColorSpace ) :
  34852. texture( outputTarget, screenUV ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  34853. _outputNodeMap.set( outputTarget, cacheKey );
  34854. return output;
  34855. }
  34856. /**
  34857. * Triggers the call of `updateBefore()` methods
  34858. * for all nodes of the given render object.
  34859. *
  34860. * @param {RenderObject} renderObject - The render object.
  34861. */
  34862. updateBefore( renderObject ) {
  34863. const nodeBuilder = renderObject.getNodeBuilderState();
  34864. for ( const node of nodeBuilder.updateBeforeNodes ) {
  34865. // update frame state for each node
  34866. this.getNodeFrameForRender( renderObject ).updateBeforeNode( node );
  34867. }
  34868. }
  34869. /**
  34870. * Triggers the call of `updateAfter()` methods
  34871. * for all nodes of the given render object.
  34872. *
  34873. * @param {RenderObject} renderObject - The render object.
  34874. */
  34875. updateAfter( renderObject ) {
  34876. const nodeBuilder = renderObject.getNodeBuilderState();
  34877. for ( const node of nodeBuilder.updateAfterNodes ) {
  34878. // update frame state for each node
  34879. this.getNodeFrameForRender( renderObject ).updateAfterNode( node );
  34880. }
  34881. }
  34882. /**
  34883. * Triggers the call of `update()` methods
  34884. * for all nodes of the given compute node.
  34885. *
  34886. * @param {Node} computeNode - The compute node.
  34887. */
  34888. updateForCompute( computeNode ) {
  34889. const nodeFrame = this.getNodeFrame();
  34890. const nodeBuilder = this.getForCompute( computeNode );
  34891. for ( const node of nodeBuilder.updateNodes ) {
  34892. nodeFrame.updateNode( node );
  34893. }
  34894. }
  34895. /**
  34896. * Triggers the call of `update()` methods
  34897. * for all nodes of the given compute node.
  34898. *
  34899. * @param {RenderObject} renderObject - The render object.
  34900. */
  34901. updateForRender( renderObject ) {
  34902. const nodeFrame = this.getNodeFrameForRender( renderObject );
  34903. const nodeBuilder = renderObject.getNodeBuilderState();
  34904. for ( const node of nodeBuilder.updateNodes ) {
  34905. nodeFrame.updateNode( node );
  34906. }
  34907. }
  34908. /**
  34909. * Returns `true` if the given render object requires a refresh.
  34910. *
  34911. * @param {RenderObject} renderObject - The render object.
  34912. * @return {boolean} Whether the given render object requires a refresh or not.
  34913. */
  34914. needsRefresh( renderObject ) {
  34915. const nodeFrame = this.getNodeFrameForRender( renderObject );
  34916. const monitor = renderObject.getMonitor();
  34917. return monitor.needsRefresh( renderObject, nodeFrame );
  34918. }
  34919. /**
  34920. * Frees the internal resources.
  34921. */
  34922. dispose() {
  34923. super.dispose();
  34924. this.nodeFrame = new NodeFrame();
  34925. this.nodeBuilderCache = new Map();
  34926. this.cacheLib = {};
  34927. }
  34928. }
  34929. const _plane = /*@__PURE__*/ new Plane();
  34930. /**
  34931. * Represents the state that is used to perform clipping via clipping planes.
  34932. * There is a default clipping context for each render context. When the
  34933. * scene holds instances of `ClippingGroup`, there will be a context for each
  34934. * group.
  34935. *
  34936. * @private
  34937. */
  34938. class ClippingContext {
  34939. /**
  34940. * Constructs a new clipping context.
  34941. *
  34942. * @param {?ClippingContext} [parentContext=null] - A reference to the parent clipping context.
  34943. */
  34944. constructor( parentContext = null ) {
  34945. /**
  34946. * The clipping context's version.
  34947. *
  34948. * @type {number}
  34949. * @readonly
  34950. */
  34951. this.version = 0;
  34952. /**
  34953. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  34954. *
  34955. * @type {?boolean}
  34956. * @default null
  34957. */
  34958. this.clipIntersection = null;
  34959. /**
  34960. * The clipping context's cache key.
  34961. *
  34962. * @type {string}
  34963. */
  34964. this.cacheKey = '';
  34965. /**
  34966. * Whether the shadow pass is active or not.
  34967. *
  34968. * @type {boolean}
  34969. * @default false
  34970. */
  34971. this.shadowPass = false;
  34972. /**
  34973. * The view normal matrix.
  34974. *
  34975. * @type {Matrix3}
  34976. */
  34977. this.viewNormalMatrix = new Matrix3();
  34978. /**
  34979. * Internal cache for maintaining clipping contexts.
  34980. *
  34981. * @type {WeakMap<ClippingGroup,ClippingContext>}
  34982. */
  34983. this.clippingGroupContexts = new WeakMap();
  34984. /**
  34985. * The intersection planes.
  34986. *
  34987. * @type {Array<Vector4>}
  34988. */
  34989. this.intersectionPlanes = [];
  34990. /**
  34991. * The intersection planes.
  34992. *
  34993. * @type {Array<Vector4>}
  34994. */
  34995. this.unionPlanes = [];
  34996. /**
  34997. * The version of the clipping context's parent context.
  34998. *
  34999. * @type {?number}
  35000. * @readonly
  35001. */
  35002. this.parentVersion = null;
  35003. if ( parentContext !== null ) {
  35004. this.viewNormalMatrix = parentContext.viewNormalMatrix;
  35005. this.clippingGroupContexts = parentContext.clippingGroupContexts;
  35006. this.shadowPass = parentContext.shadowPass;
  35007. this.viewMatrix = parentContext.viewMatrix;
  35008. }
  35009. }
  35010. /**
  35011. * Projects the given source clipping planes and writes the result into the
  35012. * destination array.
  35013. *
  35014. * @param {Array<Plane>} source - The source clipping planes.
  35015. * @param {Array<Vector4>} destination - The destination.
  35016. * @param {number} offset - The offset.
  35017. */
  35018. projectPlanes( source, destination, offset ) {
  35019. const l = source.length;
  35020. for ( let i = 0; i < l; i ++ ) {
  35021. _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, this.viewNormalMatrix );
  35022. const v = destination[ offset + i ];
  35023. const normal = _plane.normal;
  35024. v.x = - normal.x;
  35025. v.y = - normal.y;
  35026. v.z = - normal.z;
  35027. v.w = _plane.constant;
  35028. }
  35029. }
  35030. /**
  35031. * Updates the root clipping context of a scene.
  35032. *
  35033. * @param {Scene} scene - The scene.
  35034. * @param {Camera} camera - The camera that is used to render the scene.
  35035. */
  35036. updateGlobal( scene, camera ) {
  35037. this.shadowPass = ( scene.overrideMaterial !== null && scene.overrideMaterial.isShadowPassMaterial );
  35038. this.viewMatrix = camera.matrixWorldInverse;
  35039. this.viewNormalMatrix.getNormalMatrix( this.viewMatrix );
  35040. }
  35041. /**
  35042. * Updates the clipping context.
  35043. *
  35044. * @param {ClippingContext} parentContext - The parent context.
  35045. * @param {ClippingGroup} clippingGroup - The clipping group this context belongs to.
  35046. */
  35047. update( parentContext, clippingGroup ) {
  35048. let update = false;
  35049. if ( parentContext.version !== this.parentVersion ) {
  35050. this.intersectionPlanes = Array.from( parentContext.intersectionPlanes );
  35051. this.unionPlanes = Array.from( parentContext.unionPlanes );
  35052. this.parentVersion = parentContext.version;
  35053. }
  35054. if ( this.clipIntersection !== clippingGroup.clipIntersection ) {
  35055. this.clipIntersection = clippingGroup.clipIntersection;
  35056. if ( this.clipIntersection ) {
  35057. this.unionPlanes.length = parentContext.unionPlanes.length;
  35058. } else {
  35059. this.intersectionPlanes.length = parentContext.intersectionPlanes.length;
  35060. }
  35061. }
  35062. const srcClippingPlanes = clippingGroup.clippingPlanes;
  35063. const l = srcClippingPlanes.length;
  35064. let dstClippingPlanes;
  35065. let offset;
  35066. if ( this.clipIntersection ) {
  35067. dstClippingPlanes = this.intersectionPlanes;
  35068. offset = parentContext.intersectionPlanes.length;
  35069. } else {
  35070. dstClippingPlanes = this.unionPlanes;
  35071. offset = parentContext.unionPlanes.length;
  35072. }
  35073. if ( dstClippingPlanes.length !== offset + l ) {
  35074. dstClippingPlanes.length = offset + l;
  35075. for ( let i = 0; i < l; i ++ ) {
  35076. dstClippingPlanes[ offset + i ] = new Vector4();
  35077. }
  35078. update = true;
  35079. }
  35080. this.projectPlanes( srcClippingPlanes, dstClippingPlanes, offset );
  35081. if ( update ) {
  35082. this.version ++;
  35083. this.cacheKey = `${ this.intersectionPlanes.length }:${ this.unionPlanes.length }`;
  35084. }
  35085. }
  35086. /**
  35087. * Returns a clipping context for the given clipping group.
  35088. *
  35089. * @param {ClippingGroup} clippingGroup - The clipping group.
  35090. * @return {ClippingContext} The clipping context.
  35091. */
  35092. getGroupContext( clippingGroup ) {
  35093. if ( this.shadowPass && ! clippingGroup.clipShadows ) return this;
  35094. let context = this.clippingGroupContexts.get( clippingGroup );
  35095. if ( context === undefined ) {
  35096. context = new ClippingContext( this );
  35097. this.clippingGroupContexts.set( clippingGroup, context );
  35098. }
  35099. context.update( this, clippingGroup );
  35100. return context;
  35101. }
  35102. /**
  35103. * The count of union clipping planes.
  35104. *
  35105. * @type {number}
  35106. * @readonly
  35107. */
  35108. get unionClippingCount() {
  35109. return this.unionPlanes.length;
  35110. }
  35111. }
  35112. /**
  35113. * This module is used to represent render bundles inside the renderer
  35114. * for further processing.
  35115. *
  35116. * @private
  35117. */
  35118. class RenderBundle {
  35119. /**
  35120. * Constructs a new bundle group.
  35121. *
  35122. * @param {BundleGroup} bundleGroup - The bundle group.
  35123. * @param {Camera} camera - The camera the bundle group is rendered with.
  35124. */
  35125. constructor( bundleGroup, camera ) {
  35126. this.bundleGroup = bundleGroup;
  35127. this.camera = camera;
  35128. }
  35129. }
  35130. const _chainKeys$1 = [];
  35131. /**
  35132. * This renderer module manages render bundles.
  35133. *
  35134. * @private
  35135. */
  35136. class RenderBundles {
  35137. /**
  35138. * Constructs a new render bundle management component.
  35139. */
  35140. constructor() {
  35141. /**
  35142. * A chain map for maintaining the render bundles.
  35143. *
  35144. * @type {ChainMap}
  35145. */
  35146. this.bundles = new ChainMap();
  35147. }
  35148. /**
  35149. * Returns a render bundle for the given bundle group and camera.
  35150. *
  35151. * @param {BundleGroup} bundleGroup - The bundle group.
  35152. * @param {Camera} camera - The camera the bundle group is rendered with.
  35153. * @return {RenderBundle} The render bundle.
  35154. */
  35155. get( bundleGroup, camera ) {
  35156. const bundles = this.bundles;
  35157. _chainKeys$1[ 0 ] = bundleGroup;
  35158. _chainKeys$1[ 1 ] = camera;
  35159. let bundle = bundles.get( _chainKeys$1 );
  35160. if ( bundle === undefined ) {
  35161. bundle = new RenderBundle( bundleGroup, camera );
  35162. bundles.set( _chainKeys$1, bundle );
  35163. }
  35164. _chainKeys$1.length = 0;
  35165. return bundle;
  35166. }
  35167. /**
  35168. * Frees all internal resources.
  35169. */
  35170. dispose() {
  35171. this.bundles = new ChainMap();
  35172. }
  35173. }
  35174. /**
  35175. * The purpose of a node library is to assign node implementations
  35176. * to existing library features. In `WebGPURenderer` lights, materials
  35177. * which are not based on `NodeMaterial` as well as tone mapping techniques
  35178. * are implemented with node-based modules.
  35179. *
  35180. * @private
  35181. */
  35182. class NodeLibrary {
  35183. /**
  35184. * Constructs a new node library.
  35185. */
  35186. constructor() {
  35187. /**
  35188. * A weak map that maps lights to light nodes.
  35189. *
  35190. * @type {WeakMap<Light.constructor,AnalyticLightNode.constructor>}
  35191. */
  35192. this.lightNodes = new WeakMap();
  35193. /**
  35194. * A map that maps materials to node materials.
  35195. *
  35196. * @type {Map<string,NodeMaterial.constructor>}
  35197. */
  35198. this.materialNodes = new Map();
  35199. /**
  35200. * A map that maps tone mapping techniques (constants)
  35201. * to tone mapping node functions.
  35202. *
  35203. * @type {Map<number,Function>}
  35204. */
  35205. this.toneMappingNodes = new Map();
  35206. }
  35207. /**
  35208. * Returns a matching node material instance for the given material object.
  35209. *
  35210. * This method also assigns/copies the properties of the given material object
  35211. * to the node material. This is done to make sure the current material
  35212. * configuration carries over to the node version.
  35213. *
  35214. * @param {Material} material - A material.
  35215. * @return {NodeMaterial} The corresponding node material.
  35216. */
  35217. fromMaterial( material ) {
  35218. if ( material.isNodeMaterial ) return material;
  35219. let nodeMaterial = null;
  35220. const nodeMaterialClass = this.getMaterialNodeClass( material.type );
  35221. if ( nodeMaterialClass !== null ) {
  35222. nodeMaterial = new nodeMaterialClass();
  35223. for ( const key in material ) {
  35224. nodeMaterial[ key ] = material[ key ];
  35225. }
  35226. }
  35227. return nodeMaterial;
  35228. }
  35229. /**
  35230. * Adds a tone mapping node function for a tone mapping technique (constant).
  35231. *
  35232. * @param {Function} toneMappingNode - The tone mapping node function.
  35233. * @param {number} toneMapping - The tone mapping.
  35234. */
  35235. addToneMapping( toneMappingNode, toneMapping ) {
  35236. this.addType( toneMappingNode, toneMapping, this.toneMappingNodes );
  35237. }
  35238. /**
  35239. * Returns a tone mapping node function for a tone mapping technique (constant).
  35240. *
  35241. * @param {number} toneMapping - The tone mapping.
  35242. * @return {?Function} The tone mapping node function. Returns `null` if no node function is found.
  35243. */
  35244. getToneMappingFunction( toneMapping ) {
  35245. return this.toneMappingNodes.get( toneMapping ) || null;
  35246. }
  35247. /**
  35248. * Returns a node material class definition for a material type.
  35249. *
  35250. * @param {string} materialType - The material type.
  35251. * @return {?NodeMaterial.constructor} The node material class definition. Returns `null` if no node material is found.
  35252. */
  35253. getMaterialNodeClass( materialType ) {
  35254. return this.materialNodes.get( materialType ) || null;
  35255. }
  35256. /**
  35257. * Adds a node material class definition for a given material type.
  35258. *
  35259. * @param {NodeMaterial.constructor} materialNodeClass - The node material class definition.
  35260. * @param {string} materialClassType - The material type.
  35261. */
  35262. addMaterial( materialNodeClass, materialClassType ) {
  35263. this.addType( materialNodeClass, materialClassType, this.materialNodes );
  35264. }
  35265. /**
  35266. * Returns a light node class definition for a light class definition.
  35267. *
  35268. * @param {Light.constructor} light - The light class definition.
  35269. * @return {?AnalyticLightNode.constructor} The light node class definition. Returns `null` if no light node is found.
  35270. */
  35271. getLightNodeClass( light ) {
  35272. return this.lightNodes.get( light ) || null;
  35273. }
  35274. /**
  35275. * Adds a light node class definition for a given light class definition.
  35276. *
  35277. * @param {AnalyticLightNode.constructor} lightNodeClass - The light node class definition.
  35278. * @param {Light.constructor} lightClass - The light class definition.
  35279. */
  35280. addLight( lightNodeClass, lightClass ) {
  35281. this.addClass( lightNodeClass, lightClass, this.lightNodes );
  35282. }
  35283. /**
  35284. * Adds a node class definition for the given type to the provided type library.
  35285. *
  35286. * @param {any} nodeClass - The node class definition.
  35287. * @param {number|string} type - The object type.
  35288. * @param {Map} library - The type library.
  35289. */
  35290. addType( nodeClass, type, library ) {
  35291. if ( library.has( type ) ) {
  35292. console.warn( `Redefinition of node ${ type }` );
  35293. return;
  35294. }
  35295. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  35296. if ( typeof type === 'function' || typeof type === 'object' ) throw new Error( `Base class ${ type } is not a class.` );
  35297. library.set( type, nodeClass );
  35298. }
  35299. /**
  35300. * Adds a node class definition for the given class definition to the provided type library.
  35301. *
  35302. * @param {any} nodeClass - The node class definition.
  35303. * @param {any} baseClass - The class definition.
  35304. * @param {WeakMap} library - The type library.
  35305. */
  35306. addClass( nodeClass, baseClass, library ) {
  35307. if ( library.has( baseClass ) ) {
  35308. console.warn( `Redefinition of node ${ baseClass.name }` );
  35309. return;
  35310. }
  35311. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  35312. if ( typeof baseClass !== 'function' ) throw new Error( `Base class ${ baseClass.name } is not a class.` );
  35313. library.set( baseClass, nodeClass );
  35314. }
  35315. }
  35316. const _defaultLights = /*@__PURE__*/ new LightsNode();
  35317. const _chainKeys = [];
  35318. /**
  35319. * This renderer module manages the lights nodes which are unique
  35320. * per scene and camera combination.
  35321. *
  35322. * The lights node itself is later configured in the render list
  35323. * with the actual lights from the scene.
  35324. *
  35325. * @private
  35326. * @augments ChainMap
  35327. */
  35328. class Lighting extends ChainMap {
  35329. /**
  35330. * Constructs a lighting management component.
  35331. */
  35332. constructor() {
  35333. super();
  35334. }
  35335. /**
  35336. * Creates a new lights node for the given array of lights.
  35337. *
  35338. * @param {Array<Light>} lights - The render object.
  35339. * @return {LightsNode} The lights node.
  35340. */
  35341. createNode( lights = [] ) {
  35342. return new LightsNode().setLights( lights );
  35343. }
  35344. /**
  35345. * Returns a lights node for the given scene and camera.
  35346. *
  35347. * @param {Scene} scene - The scene.
  35348. * @param {Camera} camera - The camera.
  35349. * @return {LightsNode} The lights node.
  35350. */
  35351. getNode( scene, camera ) {
  35352. // ignore post-processing
  35353. if ( scene.isQuadMesh ) return _defaultLights;
  35354. _chainKeys[ 0 ] = scene;
  35355. _chainKeys[ 1 ] = camera;
  35356. let node = this.get( _chainKeys );
  35357. if ( node === undefined ) {
  35358. node = this.createNode();
  35359. this.set( _chainKeys, node );
  35360. }
  35361. _chainKeys.length = 0;
  35362. return node;
  35363. }
  35364. }
  35365. /**
  35366. * A special type of render target that is used when rendering
  35367. * with the WebXR Device API.
  35368. *
  35369. * @private
  35370. * @augments RenderTarget
  35371. */
  35372. class XRRenderTarget extends RenderTarget {
  35373. /**
  35374. * Constructs a new XR render target.
  35375. *
  35376. * @param {number} [width=1] - The width of the render target.
  35377. * @param {number} [height=1] - The height of the render target.
  35378. * @param {Object} [options={}] - The configuration options.
  35379. */
  35380. constructor( width = 1, height = 1, options = {} ) {
  35381. super( width, height, options );
  35382. /**
  35383. * This flag can be used for type testing.
  35384. *
  35385. * @type {boolean}
  35386. * @readonly
  35387. * @default true
  35388. */
  35389. this.isXRRenderTarget = true;
  35390. /**
  35391. * Whether the attachments of the render target
  35392. * are defined by external textures. This flag is
  35393. * set to `true` when using the WebXR Layers API.
  35394. *
  35395. * @type {boolean}
  35396. * @default false
  35397. */
  35398. this.hasExternalTextures = false;
  35399. /**
  35400. * Whether a depth buffer should automatically be allocated
  35401. * for this XR render target or not.
  35402. *
  35403. * Allocating a depth buffer is the default behavior of XR render
  35404. * targets. However, when using the WebXR Layers API, this flag
  35405. * must be set to `false` when the `ignoreDepthValues` property of
  35406. * the projection layers evaluates to `false`.
  35407. *
  35408. * Reference: {@link https://www.w3.org/TR/webxrlayers-1/#dom-xrprojectionlayer-ignoredepthvalues}.
  35409. *
  35410. * @type {boolean}
  35411. * @default true
  35412. */
  35413. this.autoAllocateDepthBuffer = true;
  35414. }
  35415. copy( source ) {
  35416. super.copy( source );
  35417. this.hasExternalTextures = source.hasExternalTextures;
  35418. this.autoAllocateDepthBuffer = source.autoAllocateDepthBuffer;
  35419. return this;
  35420. }
  35421. }
  35422. const _cameraLPos = /*@__PURE__*/ new Vector3();
  35423. const _cameraRPos = /*@__PURE__*/ new Vector3();
  35424. /**
  35425. * The XR manager is built on top of the WebXR Device API to
  35426. * manage XR sessions with `WebGPURenderer`.
  35427. *
  35428. * XR is currently only supported with a WebGL 2 backend.
  35429. *
  35430. * @augments EventDispatcher
  35431. */
  35432. class XRManager extends EventDispatcher {
  35433. /**
  35434. * Constructs a new XR manager.
  35435. *
  35436. * @param {Renderer} renderer - The renderer.
  35437. * @param {boolean} [multiview=false] - Enables multiview if the device supports it.
  35438. */
  35439. constructor( renderer, multiview = false ) {
  35440. super();
  35441. /**
  35442. * This flag globally enables XR rendering.
  35443. *
  35444. * @type {boolean}
  35445. * @default false
  35446. */
  35447. this.enabled = false;
  35448. /**
  35449. * Whether the XR device is currently presenting or not.
  35450. *
  35451. * @type {boolean}
  35452. * @default false
  35453. * @readonly
  35454. */
  35455. this.isPresenting = false;
  35456. /**
  35457. * Whether the XR camera should automatically be updated or not.
  35458. *
  35459. * @type {boolean}
  35460. * @default true
  35461. */
  35462. this.cameraAutoUpdate = true;
  35463. /**
  35464. * The renderer.
  35465. *
  35466. * @private
  35467. * @type {Renderer}
  35468. */
  35469. this._renderer = renderer;
  35470. // camera
  35471. /**
  35472. * Represents the camera for the left eye.
  35473. *
  35474. * @private
  35475. * @type {PerspectiveCamera}
  35476. */
  35477. this._cameraL = new PerspectiveCamera();
  35478. this._cameraL.viewport = new Vector4();
  35479. /**
  35480. * Represents the camera for the right eye.
  35481. *
  35482. * @private
  35483. * @type {PerspectiveCamera}
  35484. */
  35485. this._cameraR = new PerspectiveCamera();
  35486. this._cameraR.viewport = new Vector4();
  35487. /**
  35488. * A list of cameras used for rendering the XR views.
  35489. *
  35490. * @private
  35491. * @type {Array<Camera>}
  35492. */
  35493. this._cameras = [ this._cameraL, this._cameraR ];
  35494. /**
  35495. * The main XR camera.
  35496. *
  35497. * @private
  35498. * @type {ArrayCamera}
  35499. */
  35500. this._cameraXR = new ArrayCamera();
  35501. /**
  35502. * The current near value of the XR camera.
  35503. *
  35504. * @private
  35505. * @type {?number}
  35506. * @default null
  35507. */
  35508. this._currentDepthNear = null;
  35509. /**
  35510. * The current far value of the XR camera.
  35511. *
  35512. * @private
  35513. * @type {?number}
  35514. * @default null
  35515. */
  35516. this._currentDepthFar = null;
  35517. /**
  35518. * A list of WebXR controllers requested by the application.
  35519. *
  35520. * @private
  35521. * @type {Array<WebXRController>}
  35522. */
  35523. this._controllers = [];
  35524. /**
  35525. * A list of XR input source. Each input source belongs to
  35526. * an instance of WebXRController.
  35527. *
  35528. * @private
  35529. * @type {Array<XRInputSource?>}
  35530. */
  35531. this._controllerInputSources = [];
  35532. /**
  35533. * The XR render target that represents the rendering destination
  35534. * during an active XR session.
  35535. *
  35536. * @private
  35537. * @type {?RenderTarget}
  35538. * @default null
  35539. */
  35540. this._xrRenderTarget = null;
  35541. /**
  35542. * An array holding all the non-projection layers
  35543. *
  35544. * @private
  35545. * @type {Array<Object>}
  35546. * @default []
  35547. */
  35548. this._layers = [];
  35549. /**
  35550. * Whether the device has support for all layer types.
  35551. *
  35552. * @type {boolean}
  35553. * @default false
  35554. */
  35555. this._supportsLayers = false;
  35556. this._frameBufferTargets = null;
  35557. /**
  35558. * Helper function to create native WebXR Layer.
  35559. *
  35560. * @private
  35561. * @type {Function}
  35562. */
  35563. this._createXRLayer = createXRLayer.bind( this );
  35564. /**
  35565. * The current WebGL context.
  35566. *
  35567. * @private
  35568. * @type {?WebGL2RenderingContext}
  35569. * @default null
  35570. */
  35571. this._gl = null;
  35572. /**
  35573. * The current animation context.
  35574. *
  35575. * @private
  35576. * @type {?Window}
  35577. * @default null
  35578. */
  35579. this._currentAnimationContext = null;
  35580. /**
  35581. * The current animation loop.
  35582. *
  35583. * @private
  35584. * @type {?Function}
  35585. * @default null
  35586. */
  35587. this._currentAnimationLoop = null;
  35588. /**
  35589. * The current pixel ratio.
  35590. *
  35591. * @private
  35592. * @type {?number}
  35593. * @default null
  35594. */
  35595. this._currentPixelRatio = null;
  35596. /**
  35597. * The current size of the renderer's canvas
  35598. * in logical pixel unit.
  35599. *
  35600. * @private
  35601. * @type {Vector2}
  35602. */
  35603. this._currentSize = new Vector2();
  35604. /**
  35605. * The default event listener for handling events inside a XR session.
  35606. *
  35607. * @private
  35608. * @type {Function}
  35609. */
  35610. this._onSessionEvent = onSessionEvent.bind( this );
  35611. /**
  35612. * The event listener for handling the end of a XR session.
  35613. *
  35614. * @private
  35615. * @type {Function}
  35616. */
  35617. this._onSessionEnd = onSessionEnd.bind( this );
  35618. /**
  35619. * The event listener for handling the `inputsourceschange` event.
  35620. *
  35621. * @private
  35622. * @type {Function}
  35623. */
  35624. this._onInputSourcesChange = onInputSourcesChange.bind( this );
  35625. /**
  35626. * The animation loop which is used as a replacement for the default
  35627. * animation loop of the application. It is only used when a XR session
  35628. * is active.
  35629. *
  35630. * @private
  35631. * @type {Function}
  35632. */
  35633. this._onAnimationFrame = onAnimationFrame.bind( this );
  35634. /**
  35635. * The current XR reference space.
  35636. *
  35637. * @private
  35638. * @type {?XRReferenceSpace}
  35639. * @default null
  35640. */
  35641. this._referenceSpace = null;
  35642. /**
  35643. * The current XR reference space type.
  35644. *
  35645. * @private
  35646. * @type {XRReferenceSpaceType}
  35647. * @default 'local-floor'
  35648. */
  35649. this._referenceSpaceType = 'local-floor';
  35650. /**
  35651. * A custom reference space defined by the application.
  35652. *
  35653. * @private
  35654. * @type {?XRReferenceSpace}
  35655. * @default null
  35656. */
  35657. this._customReferenceSpace = null;
  35658. /**
  35659. * The framebuffer scale factor.
  35660. *
  35661. * @private
  35662. * @type {number}
  35663. * @default 1
  35664. */
  35665. this._framebufferScaleFactor = 1;
  35666. /**
  35667. * The foveation factor.
  35668. *
  35669. * @private
  35670. * @type {number}
  35671. * @default 1
  35672. */
  35673. this._foveation = 1.0;
  35674. /**
  35675. * A reference to the current XR session.
  35676. *
  35677. * @private
  35678. * @type {?XRSession}
  35679. * @default null
  35680. */
  35681. this._session = null;
  35682. /**
  35683. * A reference to the current XR base layer.
  35684. *
  35685. * @private
  35686. * @type {?XRWebGLLayer}
  35687. * @default null
  35688. */
  35689. this._glBaseLayer = null;
  35690. /**
  35691. * A reference to the current XR binding.
  35692. *
  35693. * @private
  35694. * @type {?XRWebGLBinding}
  35695. * @default null
  35696. */
  35697. this._glBinding = null;
  35698. /**
  35699. * A reference to the current XR projection layer.
  35700. *
  35701. * @private
  35702. * @type {?XRProjectionLayer}
  35703. * @default null
  35704. */
  35705. this._glProjLayer = null;
  35706. /**
  35707. * A reference to the current XR frame.
  35708. *
  35709. * @private
  35710. * @type {?XRFrame}
  35711. * @default null
  35712. */
  35713. this._xrFrame = null;
  35714. /**
  35715. * Whether to use the WebXR Layers API or not.
  35716. *
  35717. * @private
  35718. * @type {boolean}
  35719. * @readonly
  35720. */
  35721. this._useLayers = ( typeof XRWebGLBinding !== 'undefined' && 'createProjectionLayer' in XRWebGLBinding.prototype ); // eslint-disable-line compat/compat
  35722. /**
  35723. * Whether the usage of multiview has been requested by the application or not.
  35724. *
  35725. * @private
  35726. * @type {boolean}
  35727. * @default false
  35728. * @readonly
  35729. */
  35730. this._useMultiviewIfPossible = multiview;
  35731. /**
  35732. * Whether the usage of multiview is actually enabled. This flag only evaluates to `true`
  35733. * if multiview has been requested by the application and the `OVR_multiview2` is available.
  35734. *
  35735. * @private
  35736. * @type {boolean}
  35737. * @readonly
  35738. */
  35739. this._useMultiview = false;
  35740. }
  35741. /**
  35742. * Returns an instance of `THREE.Group` that represents the transformation
  35743. * of a XR controller in target ray space. The requested controller is defined
  35744. * by the given index.
  35745. *
  35746. * @param {number} index - The index of the XR controller.
  35747. * @return {Group} A group that represents the controller's transformation.
  35748. */
  35749. getController( index ) {
  35750. const controller = this._getController( index );
  35751. return controller.getTargetRaySpace();
  35752. }
  35753. /**
  35754. * Returns an instance of `THREE.Group` that represents the transformation
  35755. * of a XR controller in grip space. The requested controller is defined
  35756. * by the given index.
  35757. *
  35758. * @param {number} index - The index of the XR controller.
  35759. * @return {Group} A group that represents the controller's transformation.
  35760. */
  35761. getControllerGrip( index ) {
  35762. const controller = this._getController( index );
  35763. return controller.getGripSpace();
  35764. }
  35765. /**
  35766. * Returns an instance of `THREE.Group` that represents the transformation
  35767. * of a XR controller in hand space. The requested controller is defined
  35768. * by the given index.
  35769. *
  35770. * @param {number} index - The index of the XR controller.
  35771. * @return {Group} A group that represents the controller's transformation.
  35772. */
  35773. getHand( index ) {
  35774. const controller = this._getController( index );
  35775. return controller.getHandSpace();
  35776. }
  35777. /**
  35778. * Returns the foveation value.
  35779. *
  35780. * @return {number|undefined} The foveation value. Returns `undefined` if no base or projection layer is defined.
  35781. */
  35782. getFoveation() {
  35783. if ( this._glProjLayer === null && this._glBaseLayer === null ) {
  35784. return undefined;
  35785. }
  35786. return this._foveation;
  35787. }
  35788. /**
  35789. * Sets the foveation value.
  35790. *
  35791. * @param {number} foveation - A number in the range `[0,1]` where `0` means no foveation (full resolution)
  35792. * and `1` means maximum foveation (the edges render at lower resolution).
  35793. */
  35794. setFoveation( foveation ) {
  35795. this._foveation = foveation;
  35796. if ( this._glProjLayer !== null ) {
  35797. this._glProjLayer.fixedFoveation = foveation;
  35798. }
  35799. if ( this._glBaseLayer !== null && this._glBaseLayer.fixedFoveation !== undefined ) {
  35800. this._glBaseLayer.fixedFoveation = foveation;
  35801. }
  35802. }
  35803. /**
  35804. * Returns the framebuffer scale factor.
  35805. *
  35806. * @return {number} The framebuffer scale factor.
  35807. */
  35808. getFramebufferScaleFactor() {
  35809. return this._framebufferScaleFactor;
  35810. }
  35811. /**
  35812. * Sets the framebuffer scale factor.
  35813. *
  35814. * This method can not be used during a XR session.
  35815. *
  35816. * @param {number} factor - The framebuffer scale factor.
  35817. */
  35818. setFramebufferScaleFactor( factor ) {
  35819. this._framebufferScaleFactor = factor;
  35820. if ( this.isPresenting === true ) {
  35821. console.warn( 'THREE.XRManager: Cannot change framebuffer scale while presenting.' );
  35822. }
  35823. }
  35824. /**
  35825. * Returns the reference space type.
  35826. *
  35827. * @return {XRReferenceSpaceType} The reference space type.
  35828. */
  35829. getReferenceSpaceType() {
  35830. return this._referenceSpaceType;
  35831. }
  35832. /**
  35833. * Sets the reference space type.
  35834. *
  35835. * This method can not be used during a XR session.
  35836. *
  35837. * @param {XRReferenceSpaceType} type - The reference space type.
  35838. */
  35839. setReferenceSpaceType( type ) {
  35840. this._referenceSpaceType = type;
  35841. if ( this.isPresenting === true ) {
  35842. console.warn( 'THREE.XRManager: Cannot change reference space type while presenting.' );
  35843. }
  35844. }
  35845. /**
  35846. * Returns the XR reference space.
  35847. *
  35848. * @return {XRReferenceSpace} The XR reference space.
  35849. */
  35850. getReferenceSpace() {
  35851. return this._customReferenceSpace || this._referenceSpace;
  35852. }
  35853. /**
  35854. * Sets a custom XR reference space.
  35855. *
  35856. * @param {XRReferenceSpace} space - The XR reference space.
  35857. */
  35858. setReferenceSpace( space ) {
  35859. this._customReferenceSpace = space;
  35860. }
  35861. /**
  35862. * Returns the XR camera.
  35863. *
  35864. * @return {ArrayCamera} The XR camera.
  35865. */
  35866. getCamera() {
  35867. return this._cameraXR;
  35868. }
  35869. /**
  35870. * Returns the environment blend mode from the current XR session.
  35871. *
  35872. * @return {'opaque'|'additive'|'alpha-blend'|undefined} The environment blend mode. Returns `undefined` when used outside of a XR session.
  35873. */
  35874. getEnvironmentBlendMode() {
  35875. if ( this._session !== null ) {
  35876. return this._session.environmentBlendMode;
  35877. }
  35878. }
  35879. /**
  35880. * Returns the current XR frame.
  35881. *
  35882. * @return {?XRFrame} The XR frame. Returns `null` when used outside a XR session.
  35883. */
  35884. getFrame() {
  35885. return this._xrFrame;
  35886. }
  35887. /**
  35888. * Returns `true` if the engine renders to a multiview target.
  35889. *
  35890. * @return {boolean} Whether the engine renders to a multiview render target or not.
  35891. */
  35892. useMultiview() {
  35893. return this._useMultiview;
  35894. }
  35895. /**
  35896. * This method can be used in XR applications to create a quadratic layer that presents a separate
  35897. * rendered scene.
  35898. *
  35899. * @param {number} width - The width of the layer plane in world units.
  35900. * @param {number} height - The height of the layer plane in world units.
  35901. * @param {Vector3} translation - The position/translation of the layer plane in world units.
  35902. * @param {Quaternion} quaternion - The orientation of the layer plane expressed as a quaternion.
  35903. * @param {number} pixelwidth - The width of the layer's render target in pixels.
  35904. * @param {number} pixelheight - The height of the layer's render target in pixels.
  35905. * @param {Function} rendercall - A callback function that renders the layer. Similar to code in
  35906. * the default animation loop, this method can be used to update/transform 3D object in the layer's scene.
  35907. * @param {Object} [attributes={}] - Allows to configure the layer's render target.
  35908. * @return {Mesh} A mesh representing the quadratic XR layer. This mesh should be added to the XR scene.
  35909. */
  35910. createQuadLayer( width, height, translation, quaternion, pixelwidth, pixelheight, rendercall, attributes = {} ) {
  35911. const geometry = new PlaneGeometry( width, height );
  35912. const renderTarget = new XRRenderTarget(
  35913. pixelwidth,
  35914. pixelheight,
  35915. {
  35916. format: RGBAFormat,
  35917. type: UnsignedByteType,
  35918. depthTexture: new DepthTexture(
  35919. pixelwidth,
  35920. pixelheight,
  35921. attributes.stencil ? UnsignedInt248Type : UnsignedIntType,
  35922. undefined,
  35923. undefined,
  35924. undefined,
  35925. undefined,
  35926. undefined,
  35927. undefined,
  35928. attributes.stencil ? DepthStencilFormat : DepthFormat
  35929. ),
  35930. stencilBuffer: attributes.stencil,
  35931. resolveDepthBuffer: false,
  35932. resolveStencilBuffer: false
  35933. } );
  35934. renderTarget.autoAllocateDepthBuffer = true;
  35935. const material = new MeshBasicMaterial( { color: 0xffffff, side: FrontSide } );
  35936. material.map = renderTarget.texture;
  35937. material.map.offset.y = 1;
  35938. material.map.repeat.y = -1;
  35939. const plane = new Mesh( geometry, material );
  35940. plane.position.copy( translation );
  35941. plane.quaternion.copy( quaternion );
  35942. const layer = {
  35943. type: 'quad',
  35944. width: width,
  35945. height: height,
  35946. translation: translation,
  35947. quaternion: quaternion,
  35948. pixelwidth: pixelwidth,
  35949. pixelheight: pixelheight,
  35950. plane: plane,
  35951. material: material,
  35952. rendercall: rendercall,
  35953. renderTarget: renderTarget };
  35954. this._layers.push( layer );
  35955. if ( this._session !== null ) {
  35956. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: FrontSide } );
  35957. layer.plane.material.blending = CustomBlending;
  35958. layer.plane.material.blendEquation = AddEquation;
  35959. layer.plane.material.blendSrc = ZeroFactor;
  35960. layer.plane.material.blendDst = ZeroFactor;
  35961. layer.xrlayer = this._createXRLayer( layer );
  35962. const xrlayers = this._session.renderState.layers;
  35963. xrlayers.unshift( layer.xrlayer );
  35964. this._session.updateRenderState( { layers: xrlayers } );
  35965. } else {
  35966. renderTarget.isXRRenderTarget = false;
  35967. }
  35968. return plane;
  35969. }
  35970. /**
  35971. * This method can be used in XR applications to create a cylindrical layer that presents a separate
  35972. * rendered scene.
  35973. *
  35974. * @param {number} radius - The radius of the cylinder in world units.
  35975. * @param {number} centralAngle - The central angle of the cylinder in radians.
  35976. * @param {number} aspectratio - The aspect ratio.
  35977. * @param {Vector3} translation - The position/translation of the layer plane in world units.
  35978. * @param {Quaternion} quaternion - The orientation of the layer plane expressed as a quaternion.
  35979. * @param {number} pixelwidth - The width of the layer's render target in pixels.
  35980. * @param {number} pixelheight - The height of the layer's render target in pixels.
  35981. * @param {Function} rendercall - A callback function that renders the layer. Similar to code in
  35982. * the default animation loop, this method can be used to update/transform 3D object in the layer's scene.
  35983. * @param {Object} [attributes={}] - Allows to configure the layer's render target.
  35984. * @return {Mesh} A mesh representing the cylindrical XR layer. This mesh should be added to the XR scene.
  35985. */
  35986. createCylinderLayer( radius, centralAngle, aspectratio, translation, quaternion, pixelwidth, pixelheight, rendercall, attributes = {} ) {
  35987. const geometry = new CylinderGeometry( radius, radius, radius * centralAngle / aspectratio, 64, 64, true, Math.PI - centralAngle / 2, centralAngle );
  35988. const renderTarget = new XRRenderTarget(
  35989. pixelwidth,
  35990. pixelheight,
  35991. {
  35992. format: RGBAFormat,
  35993. type: UnsignedByteType,
  35994. depthTexture: new DepthTexture(
  35995. pixelwidth,
  35996. pixelheight,
  35997. attributes.stencil ? UnsignedInt248Type : UnsignedIntType,
  35998. undefined,
  35999. undefined,
  36000. undefined,
  36001. undefined,
  36002. undefined,
  36003. undefined,
  36004. attributes.stencil ? DepthStencilFormat : DepthFormat
  36005. ),
  36006. stencilBuffer: attributes.stencil,
  36007. resolveDepthBuffer: false,
  36008. resolveStencilBuffer: false
  36009. } );
  36010. renderTarget.autoAllocateDepthBuffer = true;
  36011. const material = new MeshBasicMaterial( { color: 0xffffff, side: BackSide } );
  36012. material.map = renderTarget.texture;
  36013. material.map.offset.y = 1;
  36014. material.map.repeat.y = -1;
  36015. const plane = new Mesh( geometry, material );
  36016. plane.position.copy( translation );
  36017. plane.quaternion.copy( quaternion );
  36018. const layer = {
  36019. type: 'cylinder',
  36020. radius: radius,
  36021. centralAngle: centralAngle,
  36022. aspectratio: aspectratio,
  36023. translation: translation,
  36024. quaternion: quaternion,
  36025. pixelwidth: pixelwidth,
  36026. pixelheight: pixelheight,
  36027. plane: plane,
  36028. material: material,
  36029. rendercall: rendercall,
  36030. renderTarget: renderTarget };
  36031. this._layers.push( layer );
  36032. if ( this._session !== null ) {
  36033. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: BackSide } );
  36034. layer.plane.material.blending = CustomBlending;
  36035. layer.plane.material.blendEquation = AddEquation;
  36036. layer.plane.material.blendSrc = ZeroFactor;
  36037. layer.plane.material.blendDst = ZeroFactor;
  36038. layer.xrlayer = this._createXRLayer( layer );
  36039. const xrlayers = this._session.renderState.layers;
  36040. xrlayers.unshift( layer.xrlayer );
  36041. this._session.updateRenderState( { layers: xrlayers } );
  36042. } else {
  36043. renderTarget.isXRRenderTarget = false;
  36044. }
  36045. return plane;
  36046. }
  36047. /**
  36048. * Renders the XR layers that have been previously added to the scene.
  36049. *
  36050. * This method is usually called in your animation loop before rendering
  36051. * the actual scene via `renderer.render( scene, camera );`.
  36052. */
  36053. renderLayers( ) {
  36054. const translationObject = new Vector3();
  36055. const quaternionObject = new Quaternion();
  36056. const renderer = this._renderer;
  36057. const wasPresenting = this.isPresenting;
  36058. const rendererOutputTarget = renderer.getOutputRenderTarget();
  36059. const rendererFramebufferTarget = renderer._frameBufferTarget;
  36060. this.isPresenting = false;
  36061. const rendererSize = new Vector2();
  36062. renderer.getSize( rendererSize );
  36063. const rendererQuad = renderer._quad;
  36064. for ( const layer of this._layers ) {
  36065. layer.renderTarget.isXRRenderTarget = this._session !== null;
  36066. layer.renderTarget.hasExternalTextures = layer.renderTarget.isXRRenderTarget;
  36067. if ( layer.renderTarget.isXRRenderTarget && this._supportsLayers ) {
  36068. layer.xrlayer.transform = new XRRigidTransform( layer.plane.getWorldPosition( translationObject ), layer.plane.getWorldQuaternion( quaternionObject ) );
  36069. const glSubImage = this._glBinding.getSubImage( layer.xrlayer, this._xrFrame );
  36070. renderer.backend.setXRRenderTargetTextures(
  36071. layer.renderTarget,
  36072. glSubImage.colorTexture,
  36073. undefined );
  36074. renderer._setXRLayerSize( layer.renderTarget.width, layer.renderTarget.height );
  36075. renderer.setOutputRenderTarget( layer.renderTarget );
  36076. renderer.setRenderTarget( null );
  36077. renderer._frameBufferTarget = null;
  36078. this._frameBufferTargets || ( this._frameBufferTargets = new WeakMap() );
  36079. const { frameBufferTarget, quad } = this._frameBufferTargets.get( layer.renderTarget ) || { frameBufferTarget: null, quad: null };
  36080. if ( ! frameBufferTarget ) {
  36081. renderer._quad = new QuadMesh( new NodeMaterial() );
  36082. this._frameBufferTargets.set( layer.renderTarget, { frameBufferTarget: renderer._getFrameBufferTarget(), quad: renderer._quad } );
  36083. } else {
  36084. renderer._frameBufferTarget = frameBufferTarget;
  36085. renderer._quad = quad;
  36086. }
  36087. layer.rendercall();
  36088. renderer._frameBufferTarget = null;
  36089. } else {
  36090. renderer.setRenderTarget( layer.renderTarget );
  36091. layer.rendercall();
  36092. }
  36093. }
  36094. renderer.setRenderTarget( null );
  36095. renderer.setOutputRenderTarget( rendererOutputTarget );
  36096. renderer._frameBufferTarget = rendererFramebufferTarget;
  36097. renderer._setXRLayerSize( rendererSize.x, rendererSize.y );
  36098. renderer._quad = rendererQuad;
  36099. this.isPresenting = wasPresenting;
  36100. }
  36101. /**
  36102. * Returns the current XR session.
  36103. *
  36104. * @return {?XRSession} The XR session. Returns `null` when used outside a XR session.
  36105. */
  36106. getSession() {
  36107. return this._session;
  36108. }
  36109. /**
  36110. * After a XR session has been requested usually with one of the `*Button` modules, it
  36111. * is injected into the renderer with this method. This method triggers the start of
  36112. * the actual XR rendering.
  36113. *
  36114. * @async
  36115. * @param {XRSession} session - The XR session to set.
  36116. * @return {Promise} A Promise that resolves when the session has been set.
  36117. */
  36118. async setSession( session ) {
  36119. const renderer = this._renderer;
  36120. const backend = renderer.backend;
  36121. this._gl = renderer.getContext();
  36122. const gl = this._gl;
  36123. const attributes = gl.getContextAttributes();
  36124. this._session = session;
  36125. if ( session !== null ) {
  36126. 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.' );
  36127. session.addEventListener( 'select', this._onSessionEvent );
  36128. session.addEventListener( 'selectstart', this._onSessionEvent );
  36129. session.addEventListener( 'selectend', this._onSessionEvent );
  36130. session.addEventListener( 'squeeze', this._onSessionEvent );
  36131. session.addEventListener( 'squeezestart', this._onSessionEvent );
  36132. session.addEventListener( 'squeezeend', this._onSessionEvent );
  36133. session.addEventListener( 'end', this._onSessionEnd );
  36134. session.addEventListener( 'inputsourceschange', this._onInputSourcesChange );
  36135. await backend.makeXRCompatible();
  36136. this._currentPixelRatio = renderer.getPixelRatio();
  36137. renderer.getSize( this._currentSize );
  36138. this._currentAnimationContext = renderer._animation.getContext();
  36139. this._currentAnimationLoop = renderer._animation.getAnimationLoop();
  36140. renderer._animation.stop();
  36141. //
  36142. if ( this._useLayers === true ) {
  36143. // default path using XRWebGLBinding/XRProjectionLayer
  36144. let depthFormat = null;
  36145. let depthType = null;
  36146. let glDepthFormat = null;
  36147. if ( renderer.depth ) {
  36148. glDepthFormat = renderer.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  36149. depthFormat = renderer.stencil ? DepthStencilFormat : DepthFormat;
  36150. depthType = renderer.stencil ? UnsignedInt248Type : UnsignedIntType;
  36151. }
  36152. const projectionlayerInit = {
  36153. colorFormat: gl.RGBA8,
  36154. depthFormat: glDepthFormat,
  36155. scaleFactor: this._framebufferScaleFactor,
  36156. clearOnAccess: false
  36157. };
  36158. if ( this._useMultiviewIfPossible && renderer.hasFeature( 'OVR_multiview2' ) ) {
  36159. projectionlayerInit.textureType = 'texture-array';
  36160. this._useMultiview = true;
  36161. }
  36162. const glBinding = new XRWebGLBinding( session, gl );
  36163. const glProjLayer = glBinding.createProjectionLayer( projectionlayerInit );
  36164. const layersArray = [ glProjLayer ];
  36165. this._glBinding = glBinding;
  36166. this._glProjLayer = glProjLayer;
  36167. renderer.setPixelRatio( 1 );
  36168. renderer._setXRLayerSize( glProjLayer.textureWidth, glProjLayer.textureHeight );
  36169. const depth = this._useMultiview ? 2 : 1;
  36170. const depthTexture = new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat, depth );
  36171. this._xrRenderTarget = new XRRenderTarget(
  36172. glProjLayer.textureWidth,
  36173. glProjLayer.textureHeight,
  36174. {
  36175. format: RGBAFormat,
  36176. type: UnsignedByteType,
  36177. colorSpace: renderer.outputColorSpace,
  36178. depthTexture: depthTexture,
  36179. stencilBuffer: renderer.stencil,
  36180. samples: attributes.antialias ? 4 : 0,
  36181. resolveDepthBuffer: ( glProjLayer.ignoreDepthValues === false ),
  36182. resolveStencilBuffer: ( glProjLayer.ignoreDepthValues === false ),
  36183. depth: this._useMultiview ? 2 : 1,
  36184. multiview: this._useMultiview
  36185. } );
  36186. this._xrRenderTarget.hasExternalTextures = true;
  36187. this._xrRenderTarget.depth = this._useMultiview ? 2 : 1;
  36188. this._supportsLayers = session.enabledFeatures.includes( 'layers' );
  36189. this._referenceSpace = await session.requestReferenceSpace( this.getReferenceSpaceType() );
  36190. if ( this._supportsLayers ) {
  36191. // switch layers to native
  36192. for ( const layer of this._layers ) {
  36193. // change material so it "punches" out a hole to show the XR Layer.
  36194. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: layer.type === 'cylinder' ? BackSide : FrontSide } );
  36195. layer.plane.material.blending = CustomBlending;
  36196. layer.plane.material.blendEquation = AddEquation;
  36197. layer.plane.material.blendSrc = ZeroFactor;
  36198. layer.plane.material.blendDst = ZeroFactor;
  36199. layer.xrlayer = this._createXRLayer( layer );
  36200. layersArray.unshift( layer.xrlayer );
  36201. }
  36202. }
  36203. session.updateRenderState( { layers: layersArray } );
  36204. } else {
  36205. // fallback to XRWebGLLayer
  36206. const layerInit = {
  36207. antialias: renderer.samples > 0,
  36208. alpha: true,
  36209. depth: renderer.depth,
  36210. stencil: renderer.stencil,
  36211. framebufferScaleFactor: this.getFramebufferScaleFactor()
  36212. };
  36213. const glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  36214. this._glBaseLayer = glBaseLayer;
  36215. session.updateRenderState( { baseLayer: glBaseLayer } );
  36216. renderer.setPixelRatio( 1 );
  36217. renderer._setXRLayerSize( glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight );
  36218. this._xrRenderTarget = new XRRenderTarget(
  36219. glBaseLayer.framebufferWidth,
  36220. glBaseLayer.framebufferHeight,
  36221. {
  36222. format: RGBAFormat,
  36223. type: UnsignedByteType,
  36224. colorSpace: renderer.outputColorSpace,
  36225. stencilBuffer: renderer.stencil,
  36226. resolveDepthBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  36227. resolveStencilBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  36228. }
  36229. );
  36230. this._referenceSpace = await session.requestReferenceSpace( this.getReferenceSpaceType() );
  36231. }
  36232. //
  36233. this.setFoveation( this.getFoveation() );
  36234. renderer._animation.setAnimationLoop( this._onAnimationFrame );
  36235. renderer._animation.setContext( session );
  36236. renderer._animation.start();
  36237. this.isPresenting = true;
  36238. this.dispatchEvent( { type: 'sessionstart' } );
  36239. }
  36240. }
  36241. /**
  36242. * This method is called by the renderer per frame and updates the XR camera
  36243. * and it sub cameras based on the given camera. The given camera is the "user"
  36244. * camera created on application level and used for non-XR rendering.
  36245. *
  36246. * @param {PerspectiveCamera} camera - The camera.
  36247. */
  36248. updateCamera( camera ) {
  36249. const session = this._session;
  36250. if ( session === null ) return;
  36251. const depthNear = camera.near;
  36252. const depthFar = camera.far;
  36253. const cameraXR = this._cameraXR;
  36254. const cameraL = this._cameraL;
  36255. const cameraR = this._cameraR;
  36256. cameraXR.near = cameraR.near = cameraL.near = depthNear;
  36257. cameraXR.far = cameraR.far = cameraL.far = depthFar;
  36258. cameraXR.isMultiViewCamera = this._useMultiview;
  36259. if ( this._currentDepthNear !== cameraXR.near || this._currentDepthFar !== cameraXR.far ) {
  36260. // Note that the new renderState won't apply until the next frame. See #18320
  36261. session.updateRenderState( {
  36262. depthNear: cameraXR.near,
  36263. depthFar: cameraXR.far
  36264. } );
  36265. this._currentDepthNear = cameraXR.near;
  36266. this._currentDepthFar = cameraXR.far;
  36267. }
  36268. cameraL.layers.mask = camera.layers.mask | 0b010;
  36269. cameraR.layers.mask = camera.layers.mask | 0b100;
  36270. cameraXR.layers.mask = cameraL.layers.mask | cameraR.layers.mask;
  36271. const parent = camera.parent;
  36272. const cameras = cameraXR.cameras;
  36273. updateCamera( cameraXR, parent );
  36274. for ( let i = 0; i < cameras.length; i ++ ) {
  36275. updateCamera( cameras[ i ], parent );
  36276. }
  36277. // update projection matrix for proper view frustum culling
  36278. if ( cameras.length === 2 ) {
  36279. setProjectionFromUnion( cameraXR, cameraL, cameraR );
  36280. } else {
  36281. // assume single camera setup (AR)
  36282. cameraXR.projectionMatrix.copy( cameraL.projectionMatrix );
  36283. }
  36284. // update user camera and its children
  36285. updateUserCamera( camera, cameraXR, parent );
  36286. }
  36287. /**
  36288. * Returns a WebXR controller for the given controller index.
  36289. *
  36290. * @private
  36291. * @param {number} index - The controller index.
  36292. * @return {WebXRController} The XR controller.
  36293. */
  36294. _getController( index ) {
  36295. let controller = this._controllers[ index ];
  36296. if ( controller === undefined ) {
  36297. controller = new WebXRController();
  36298. this._controllers[ index ] = controller;
  36299. }
  36300. return controller;
  36301. }
  36302. }
  36303. /**
  36304. * Assumes 2 cameras that are parallel and share an X-axis, and that
  36305. * the cameras' projection and world matrices have already been set.
  36306. * And that near and far planes are identical for both cameras.
  36307. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  36308. *
  36309. * @param {ArrayCamera} camera - The camera to update.
  36310. * @param {PerspectiveCamera} cameraL - The left camera.
  36311. * @param {PerspectiveCamera} cameraR - The right camera.
  36312. */
  36313. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  36314. _cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  36315. _cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  36316. const ipd = _cameraLPos.distanceTo( _cameraRPos );
  36317. const projL = cameraL.projectionMatrix.elements;
  36318. const projR = cameraR.projectionMatrix.elements;
  36319. // VR systems will have identical far and near planes, and
  36320. // most likely identical top and bottom frustum extents.
  36321. // Use the left camera for these values.
  36322. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  36323. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  36324. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  36325. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  36326. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  36327. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  36328. const left = near * leftFov;
  36329. const right = near * rightFov;
  36330. // Calculate the new camera's position offset from the
  36331. // left camera. xOffset should be roughly half `ipd`.
  36332. const zOffset = ipd / ( - leftFov + rightFov );
  36333. const xOffset = zOffset * - leftFov;
  36334. // TODO: Better way to apply this offset?
  36335. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  36336. camera.translateX( xOffset );
  36337. camera.translateZ( zOffset );
  36338. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  36339. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  36340. // Check if the projection uses an infinite far plane.
  36341. if ( projL[ 10 ] === -1 ) {
  36342. // Use the projection matrix from the left eye.
  36343. // The camera offset is sufficient to include the view volumes
  36344. // of both eyes (assuming symmetric projections).
  36345. camera.projectionMatrix.copy( cameraL.projectionMatrix );
  36346. camera.projectionMatrixInverse.copy( cameraL.projectionMatrixInverse );
  36347. } else {
  36348. // Find the union of the frustum values of the cameras and scale
  36349. // the values so that the near plane's position does not change in world space,
  36350. // although must now be relative to the new union camera.
  36351. const near2 = near + zOffset;
  36352. const far2 = far + zOffset;
  36353. const left2 = left - xOffset;
  36354. const right2 = right + ( ipd - xOffset );
  36355. const top2 = topFov * far / far2 * near2;
  36356. const bottom2 = bottomFov * far / far2 * near2;
  36357. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  36358. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  36359. }
  36360. }
  36361. /**
  36362. * Updates the world matrices for the given camera based on the parent 3D object.
  36363. *
  36364. * @inner
  36365. * @param {Camera} camera - The camera to update.
  36366. * @param {Object3D} parent - The parent 3D object.
  36367. */
  36368. function updateCamera( camera, parent ) {
  36369. if ( parent === null ) {
  36370. camera.matrixWorld.copy( camera.matrix );
  36371. } else {
  36372. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  36373. }
  36374. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  36375. }
  36376. /**
  36377. * Updates the given camera with the transformation of the XR camera and parent object.
  36378. *
  36379. * @inner
  36380. * @param {Camera} camera - The camera to update.
  36381. * @param {ArrayCamera} cameraXR - The XR camera.
  36382. * @param {Object3D} parent - The parent 3D object.
  36383. */
  36384. function updateUserCamera( camera, cameraXR, parent ) {
  36385. if ( parent === null ) {
  36386. camera.matrix.copy( cameraXR.matrixWorld );
  36387. } else {
  36388. camera.matrix.copy( parent.matrixWorld );
  36389. camera.matrix.invert();
  36390. camera.matrix.multiply( cameraXR.matrixWorld );
  36391. }
  36392. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  36393. camera.updateMatrixWorld( true );
  36394. camera.projectionMatrix.copy( cameraXR.projectionMatrix );
  36395. camera.projectionMatrixInverse.copy( cameraXR.projectionMatrixInverse );
  36396. if ( camera.isPerspectiveCamera ) {
  36397. camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );
  36398. camera.zoom = 1;
  36399. }
  36400. }
  36401. function onSessionEvent( event ) {
  36402. const controllerIndex = this._controllerInputSources.indexOf( event.inputSource );
  36403. if ( controllerIndex === -1 ) {
  36404. return;
  36405. }
  36406. const controller = this._controllers[ controllerIndex ];
  36407. if ( controller !== undefined ) {
  36408. const referenceSpace = this.getReferenceSpace();
  36409. controller.update( event.inputSource, event.frame, referenceSpace );
  36410. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  36411. }
  36412. }
  36413. function onSessionEnd() {
  36414. const session = this._session;
  36415. const renderer = this._renderer;
  36416. session.removeEventListener( 'select', this._onSessionEvent );
  36417. session.removeEventListener( 'selectstart', this._onSessionEvent );
  36418. session.removeEventListener( 'selectend', this._onSessionEvent );
  36419. session.removeEventListener( 'squeeze', this._onSessionEvent );
  36420. session.removeEventListener( 'squeezestart', this._onSessionEvent );
  36421. session.removeEventListener( 'squeezeend', this._onSessionEvent );
  36422. session.removeEventListener( 'end', this._onSessionEnd );
  36423. session.removeEventListener( 'inputsourceschange', this._onInputSourcesChange );
  36424. for ( let i = 0; i < this._controllers.length; i ++ ) {
  36425. const inputSource = this._controllerInputSources[ i ];
  36426. if ( inputSource === null ) continue;
  36427. this._controllerInputSources[ i ] = null;
  36428. this._controllers[ i ].disconnect( inputSource );
  36429. }
  36430. this._currentDepthNear = null;
  36431. this._currentDepthFar = null;
  36432. // restore framebuffer/rendering state
  36433. renderer._resetXRState();
  36434. this._session = null;
  36435. this._xrRenderTarget = null;
  36436. // switch layers back to emulated
  36437. if ( this._supportsLayers === true ) {
  36438. for ( const layer of this._layers ) {
  36439. // Recreate layer render target to reset state
  36440. layer.renderTarget = new XRRenderTarget(
  36441. layer.pixelwidth,
  36442. layer.pixelheight,
  36443. {
  36444. format: RGBAFormat,
  36445. type: UnsignedByteType,
  36446. depthTexture: new DepthTexture(
  36447. layer.pixelwidth,
  36448. layer.pixelheight,
  36449. layer.stencilBuffer ? UnsignedInt248Type : UnsignedIntType,
  36450. undefined,
  36451. undefined,
  36452. undefined,
  36453. undefined,
  36454. undefined,
  36455. undefined,
  36456. layer.stencilBuffer ? DepthStencilFormat : DepthFormat
  36457. ),
  36458. stencilBuffer: layer.stencilBuffer,
  36459. resolveDepthBuffer: false,
  36460. resolveStencilBuffer: false
  36461. } );
  36462. layer.renderTarget.isXRRenderTarget = false;
  36463. layer.plane.material = layer.material;
  36464. layer.material.map = layer.renderTarget.texture;
  36465. layer.material.map.offset.y = 1;
  36466. layer.material.map.repeat.y = -1;
  36467. delete layer.xrlayer;
  36468. }
  36469. }
  36470. //
  36471. this.isPresenting = false;
  36472. this._useMultiview = false;
  36473. renderer._animation.stop();
  36474. renderer._animation.setAnimationLoop( this._currentAnimationLoop );
  36475. renderer._animation.setContext( this._currentAnimationContext );
  36476. renderer._animation.start();
  36477. renderer.setPixelRatio( this._currentPixelRatio );
  36478. renderer.setSize( this._currentSize.width, this._currentSize.height, false );
  36479. this.dispatchEvent( { type: 'sessionend' } );
  36480. }
  36481. function onInputSourcesChange( event ) {
  36482. const controllers = this._controllers;
  36483. const controllerInputSources = this._controllerInputSources;
  36484. // Notify disconnected
  36485. for ( let i = 0; i < event.removed.length; i ++ ) {
  36486. const inputSource = event.removed[ i ];
  36487. const index = controllerInputSources.indexOf( inputSource );
  36488. if ( index >= 0 ) {
  36489. controllerInputSources[ index ] = null;
  36490. controllers[ index ].disconnect( inputSource );
  36491. }
  36492. }
  36493. // Notify connected
  36494. for ( let i = 0; i < event.added.length; i ++ ) {
  36495. const inputSource = event.added[ i ];
  36496. let controllerIndex = controllerInputSources.indexOf( inputSource );
  36497. if ( controllerIndex === -1 ) {
  36498. // Assign input source a controller that currently has no input source
  36499. for ( let i = 0; i < controllers.length; i ++ ) {
  36500. if ( i >= controllerInputSources.length ) {
  36501. controllerInputSources.push( inputSource );
  36502. controllerIndex = i;
  36503. break;
  36504. } else if ( controllerInputSources[ i ] === null ) {
  36505. controllerInputSources[ i ] = inputSource;
  36506. controllerIndex = i;
  36507. break;
  36508. }
  36509. }
  36510. // If all controllers do currently receive input we ignore new ones
  36511. if ( controllerIndex === -1 ) break;
  36512. }
  36513. const controller = controllers[ controllerIndex ];
  36514. if ( controller ) {
  36515. controller.connect( inputSource );
  36516. }
  36517. }
  36518. }
  36519. // Creation method for native WebXR layers
  36520. function createXRLayer( layer ) {
  36521. if ( layer.type === 'quad' ) {
  36522. return this._glBinding.createQuadLayer( {
  36523. transform: new XRRigidTransform( layer.translation, layer.quaternion ),
  36524. width: layer.width / 2,
  36525. height: layer.height / 2,
  36526. space: this._referenceSpace,
  36527. viewPixelWidth: layer.pixelwidth,
  36528. viewPixelHeight: layer.pixelheight,
  36529. clearOnAccess: false
  36530. } );
  36531. } else {
  36532. return this._glBinding.createCylinderLayer( {
  36533. transform: new XRRigidTransform( layer.translation, layer.quaternion ),
  36534. radius: layer.radius,
  36535. centralAngle: layer.centralAngle,
  36536. aspectRatio: layer.aspectRatio,
  36537. space: this._referenceSpace,
  36538. viewPixelWidth: layer.pixelwidth,
  36539. viewPixelHeight: layer.pixelheight,
  36540. clearOnAccess: false
  36541. } );
  36542. }
  36543. }
  36544. // Animation Loop
  36545. function onAnimationFrame( time, frame ) {
  36546. if ( frame === undefined ) return;
  36547. const cameraXR = this._cameraXR;
  36548. const renderer = this._renderer;
  36549. const backend = renderer.backend;
  36550. const glBaseLayer = this._glBaseLayer;
  36551. const referenceSpace = this.getReferenceSpace();
  36552. const pose = frame.getViewerPose( referenceSpace );
  36553. this._xrFrame = frame;
  36554. if ( pose !== null ) {
  36555. const views = pose.views;
  36556. if ( this._glBaseLayer !== null ) {
  36557. backend.setXRTarget( glBaseLayer.framebuffer );
  36558. }
  36559. let cameraXRNeedsUpdate = false;
  36560. // check if it's necessary to rebuild cameraXR's camera list
  36561. if ( views.length !== cameraXR.cameras.length ) {
  36562. cameraXR.cameras.length = 0;
  36563. cameraXRNeedsUpdate = true;
  36564. }
  36565. for ( let i = 0; i < views.length; i ++ ) {
  36566. const view = views[ i ];
  36567. let viewport;
  36568. if ( this._useLayers === true ) {
  36569. const glSubImage = this._glBinding.getViewSubImage( this._glProjLayer, view );
  36570. viewport = glSubImage.viewport;
  36571. // For side-by-side projection, we only produce a single texture for both eyes.
  36572. if ( i === 0 ) {
  36573. backend.setXRRenderTargetTextures(
  36574. this._xrRenderTarget,
  36575. glSubImage.colorTexture,
  36576. ( this._glProjLayer.ignoreDepthValues && ! this._useMultiview ) ? undefined : glSubImage.depthStencilTexture
  36577. );
  36578. }
  36579. } else {
  36580. viewport = glBaseLayer.getViewport( view );
  36581. }
  36582. let camera = this._cameras[ i ];
  36583. if ( camera === undefined ) {
  36584. camera = new PerspectiveCamera();
  36585. camera.layers.enable( i );
  36586. camera.viewport = new Vector4();
  36587. this._cameras[ i ] = camera;
  36588. }
  36589. camera.matrix.fromArray( view.transform.matrix );
  36590. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  36591. camera.projectionMatrix.fromArray( view.projectionMatrix );
  36592. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  36593. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  36594. if ( i === 0 ) {
  36595. cameraXR.matrix.copy( camera.matrix );
  36596. cameraXR.matrix.decompose( cameraXR.position, cameraXR.quaternion, cameraXR.scale );
  36597. }
  36598. if ( cameraXRNeedsUpdate === true ) {
  36599. cameraXR.cameras.push( camera );
  36600. }
  36601. }
  36602. renderer.setOutputRenderTarget( this._xrRenderTarget );
  36603. }
  36604. //
  36605. for ( let i = 0; i < this._controllers.length; i ++ ) {
  36606. const inputSource = this._controllerInputSources[ i ];
  36607. const controller = this._controllers[ i ];
  36608. if ( inputSource !== null && controller !== undefined ) {
  36609. controller.update( inputSource, frame, referenceSpace );
  36610. }
  36611. }
  36612. if ( this._currentAnimationLoop ) this._currentAnimationLoop( time, frame );
  36613. if ( frame.detectedPlanes ) {
  36614. this.dispatchEvent( { type: 'planesdetected', data: frame } );
  36615. }
  36616. this._xrFrame = null;
  36617. }
  36618. const _scene = /*@__PURE__*/ new Scene();
  36619. const _drawingBufferSize$1 = /*@__PURE__*/ new Vector2();
  36620. const _screen = /*@__PURE__*/ new Vector4();
  36621. const _frustum = /*@__PURE__*/ new Frustum();
  36622. const _frustumArray = /*@__PURE__*/ new FrustumArray();
  36623. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  36624. const _vector4 = /*@__PURE__*/ new Vector4();
  36625. /**
  36626. * Base class for renderers.
  36627. */
  36628. class Renderer {
  36629. /**
  36630. * Renderer options.
  36631. *
  36632. * @typedef {Object} Renderer~Options
  36633. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  36634. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  36635. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  36636. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  36637. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  36638. * @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
  36639. * to overwrite the default.
  36640. * @property {?Function} [getFallback=null] - This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  36641. * @property {number} [colorBufferType=HalfFloatType] - Defines the type of color buffers. The default `HalfFloatType` is recommend for best
  36642. * quality. To save memory and bandwidth, `UnsignedByteType` might be used. This will reduce rendering quality though.
  36643. * @property {boolean} [multiview=false] - If set to `true`, the renderer will use multiview during WebXR rendering if supported.
  36644. */
  36645. /**
  36646. * Constructs a new renderer.
  36647. *
  36648. * @param {Backend} backend - The backend the renderer is targeting (e.g. WebGPU or WebGL 2).
  36649. * @param {Renderer~Options} [parameters] - The configuration parameter.
  36650. */
  36651. constructor( backend, parameters = {} ) {
  36652. /**
  36653. * This flag can be used for type testing.
  36654. *
  36655. * @type {boolean}
  36656. * @readonly
  36657. * @default true
  36658. */
  36659. this.isRenderer = true;
  36660. //
  36661. const {
  36662. logarithmicDepthBuffer = false,
  36663. alpha = true,
  36664. depth = true,
  36665. stencil = false,
  36666. antialias = false,
  36667. samples = 0,
  36668. getFallback = null,
  36669. colorBufferType = HalfFloatType,
  36670. multiview = false
  36671. } = parameters;
  36672. /**
  36673. * A reference to the canvas element the renderer is drawing to.
  36674. * This value of this property will automatically be created by
  36675. * the renderer.
  36676. *
  36677. * @type {HTMLCanvasElement|OffscreenCanvas}
  36678. */
  36679. this.domElement = backend.getDomElement();
  36680. /**
  36681. * A reference to the current backend.
  36682. *
  36683. * @type {Backend}
  36684. */
  36685. this.backend = backend;
  36686. /**
  36687. * The number of MSAA samples.
  36688. *
  36689. * @type {number}
  36690. * @default 0
  36691. */
  36692. this.samples = samples || ( antialias === true ) ? 4 : 0;
  36693. /**
  36694. * Whether the renderer should automatically clear the current rendering target
  36695. * before execute a `render()` call. The target can be the canvas (default framebuffer)
  36696. * or the current bound render target (custom framebuffer).
  36697. *
  36698. * @type {boolean}
  36699. * @default true
  36700. */
  36701. this.autoClear = true;
  36702. /**
  36703. * When `autoClear` is set to `true`, this property defines whether the renderer
  36704. * should clear the color buffer.
  36705. *
  36706. * @type {boolean}
  36707. * @default true
  36708. */
  36709. this.autoClearColor = true;
  36710. /**
  36711. * When `autoClear` is set to `true`, this property defines whether the renderer
  36712. * should clear the depth buffer.
  36713. *
  36714. * @type {boolean}
  36715. * @default true
  36716. */
  36717. this.autoClearDepth = true;
  36718. /**
  36719. * When `autoClear` is set to `true`, this property defines whether the renderer
  36720. * should clear the stencil buffer.
  36721. *
  36722. * @type {boolean}
  36723. * @default true
  36724. */
  36725. this.autoClearStencil = true;
  36726. /**
  36727. * Whether the default framebuffer should be transparent or opaque.
  36728. *
  36729. * @type {boolean}
  36730. * @default true
  36731. */
  36732. this.alpha = alpha;
  36733. /**
  36734. * Whether logarithmic depth buffer is enabled or not.
  36735. *
  36736. * @type {boolean}
  36737. * @default false
  36738. */
  36739. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  36740. /**
  36741. * Defines the output color space of the renderer.
  36742. *
  36743. * @type {string}
  36744. * @default SRGBColorSpace
  36745. */
  36746. this.outputColorSpace = SRGBColorSpace;
  36747. /**
  36748. * Defines the tone mapping of the renderer.
  36749. *
  36750. * @type {number}
  36751. * @default NoToneMapping
  36752. */
  36753. this.toneMapping = NoToneMapping;
  36754. /**
  36755. * Defines the tone mapping exposure.
  36756. *
  36757. * @type {number}
  36758. * @default 1
  36759. */
  36760. this.toneMappingExposure = 1.0;
  36761. /**
  36762. * Whether the renderer should sort its render lists or not.
  36763. *
  36764. * Note: Sorting is used to attempt to properly render objects that have some degree of transparency.
  36765. * By definition, sorting objects may not work in all cases. Depending on the needs of application,
  36766. * it may be necessary to turn off sorting and use other methods to deal with transparency rendering
  36767. * e.g. manually determining each object's rendering order.
  36768. *
  36769. * @type {boolean}
  36770. * @default true
  36771. */
  36772. this.sortObjects = true;
  36773. /**
  36774. * Whether the default framebuffer should have a depth buffer or not.
  36775. *
  36776. * @type {boolean}
  36777. * @default true
  36778. */
  36779. this.depth = depth;
  36780. /**
  36781. * Whether the default framebuffer should have a stencil buffer or not.
  36782. *
  36783. * @type {boolean}
  36784. * @default false
  36785. */
  36786. this.stencil = stencil;
  36787. /**
  36788. * Holds a series of statistical information about the GPU memory
  36789. * and the rendering process. Useful for debugging and monitoring.
  36790. *
  36791. * @type {Info}
  36792. */
  36793. this.info = new Info();
  36794. /**
  36795. * Stores override nodes for specific transformations or calculations.
  36796. * These nodes can be used to replace default behavior in the rendering pipeline.
  36797. *
  36798. * @type {Object}
  36799. * @property {?Node} modelViewMatrix - An override node for the model-view matrix.
  36800. * @property {?Node} modelNormalViewMatrix - An override node for the model normal view matrix.
  36801. */
  36802. this.overrideNodes = {
  36803. modelViewMatrix: null,
  36804. modelNormalViewMatrix: null
  36805. };
  36806. /**
  36807. * The node library defines how certain library objects like materials, lights
  36808. * or tone mapping functions are mapped to node types. This is required since
  36809. * although instances of classes like `MeshBasicMaterial` or `PointLight` can
  36810. * be part of the scene graph, they are internally represented as nodes for
  36811. * further processing.
  36812. *
  36813. * @type {NodeLibrary}
  36814. */
  36815. this.library = new NodeLibrary();
  36816. /**
  36817. * A map-like data structure for managing lights.
  36818. *
  36819. * @type {Lighting}
  36820. */
  36821. this.lighting = new Lighting();
  36822. // internals
  36823. /**
  36824. * This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  36825. *
  36826. * @private
  36827. * @type {?Function}
  36828. */
  36829. this._getFallback = getFallback;
  36830. /**
  36831. * The renderer's pixel ratio.
  36832. *
  36833. * @private
  36834. * @type {number}
  36835. * @default 1
  36836. */
  36837. this._pixelRatio = 1;
  36838. /**
  36839. * The width of the renderer's default framebuffer in logical pixel unit.
  36840. *
  36841. * @private
  36842. * @type {number}
  36843. */
  36844. this._width = this.domElement.width;
  36845. /**
  36846. * The height of the renderer's default framebuffer in logical pixel unit.
  36847. *
  36848. * @private
  36849. * @type {number}
  36850. */
  36851. this._height = this.domElement.height;
  36852. /**
  36853. * The viewport of the renderer in logical pixel unit.
  36854. *
  36855. * @private
  36856. * @type {Vector4}
  36857. */
  36858. this._viewport = new Vector4( 0, 0, this._width, this._height );
  36859. /**
  36860. * The scissor rectangle of the renderer in logical pixel unit.
  36861. *
  36862. * @private
  36863. * @type {Vector4}
  36864. */
  36865. this._scissor = new Vector4( 0, 0, this._width, this._height );
  36866. /**
  36867. * Whether the scissor test should be enabled or not.
  36868. *
  36869. * @private
  36870. * @type {boolean}
  36871. */
  36872. this._scissorTest = false;
  36873. /**
  36874. * A reference to a renderer module for managing shader attributes.
  36875. *
  36876. * @private
  36877. * @type {?Attributes}
  36878. * @default null
  36879. */
  36880. this._attributes = null;
  36881. /**
  36882. * A reference to a renderer module for managing geometries.
  36883. *
  36884. * @private
  36885. * @type {?Geometries}
  36886. * @default null
  36887. */
  36888. this._geometries = null;
  36889. /**
  36890. * A reference to a renderer module for managing node related logic.
  36891. *
  36892. * @private
  36893. * @type {?Nodes}
  36894. * @default null
  36895. */
  36896. this._nodes = null;
  36897. /**
  36898. * A reference to a renderer module for managing the internal animation loop.
  36899. *
  36900. * @private
  36901. * @type {?Animation}
  36902. * @default null
  36903. */
  36904. this._animation = null;
  36905. /**
  36906. * A reference to a renderer module for managing shader program bindings.
  36907. *
  36908. * @private
  36909. * @type {?Bindings}
  36910. * @default null
  36911. */
  36912. this._bindings = null;
  36913. /**
  36914. * A reference to a renderer module for managing render objects.
  36915. *
  36916. * @private
  36917. * @type {?RenderObjects}
  36918. * @default null
  36919. */
  36920. this._objects = null;
  36921. /**
  36922. * A reference to a renderer module for managing render and compute pipelines.
  36923. *
  36924. * @private
  36925. * @type {?Pipelines}
  36926. * @default null
  36927. */
  36928. this._pipelines = null;
  36929. /**
  36930. * A reference to a renderer module for managing render bundles.
  36931. *
  36932. * @private
  36933. * @type {?RenderBundles}
  36934. * @default null
  36935. */
  36936. this._bundles = null;
  36937. /**
  36938. * A reference to a renderer module for managing render lists.
  36939. *
  36940. * @private
  36941. * @type {?RenderLists}
  36942. * @default null
  36943. */
  36944. this._renderLists = null;
  36945. /**
  36946. * A reference to a renderer module for managing render contexts.
  36947. *
  36948. * @private
  36949. * @type {?RenderContexts}
  36950. * @default null
  36951. */
  36952. this._renderContexts = null;
  36953. /**
  36954. * A reference to a renderer module for managing textures.
  36955. *
  36956. * @private
  36957. * @type {?Textures}
  36958. * @default null
  36959. */
  36960. this._textures = null;
  36961. /**
  36962. * A reference to a renderer module for backgrounds.
  36963. *
  36964. * @private
  36965. * @type {?Background}
  36966. * @default null
  36967. */
  36968. this._background = null;
  36969. /**
  36970. * This fullscreen quad is used for internal render passes
  36971. * like the tone mapping and color space output pass.
  36972. *
  36973. * @private
  36974. * @type {QuadMesh}
  36975. */
  36976. this._quad = new QuadMesh( new NodeMaterial() );
  36977. this._quad.material.name = 'Renderer_output';
  36978. /**
  36979. * A reference to the current render context.
  36980. *
  36981. * @private
  36982. * @type {?RenderContext}
  36983. * @default null
  36984. */
  36985. this._currentRenderContext = null;
  36986. /**
  36987. * A custom sort function for the opaque render list.
  36988. *
  36989. * @private
  36990. * @type {?Function}
  36991. * @default null
  36992. */
  36993. this._opaqueSort = null;
  36994. /**
  36995. * A custom sort function for the transparent render list.
  36996. *
  36997. * @private
  36998. * @type {?Function}
  36999. * @default null
  37000. */
  37001. this._transparentSort = null;
  37002. /**
  37003. * The framebuffer target.
  37004. *
  37005. * @private
  37006. * @type {?RenderTarget}
  37007. * @default null
  37008. */
  37009. this._frameBufferTarget = null;
  37010. const alphaClear = this.alpha === true ? 0 : 1;
  37011. /**
  37012. * The clear color value.
  37013. *
  37014. * @private
  37015. * @type {Color4}
  37016. */
  37017. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  37018. /**
  37019. * The clear depth value.
  37020. *
  37021. * @private
  37022. * @type {number}
  37023. * @default 1
  37024. */
  37025. this._clearDepth = 1;
  37026. /**
  37027. * The clear stencil value.
  37028. *
  37029. * @private
  37030. * @type {number}
  37031. * @default 0
  37032. */
  37033. this._clearStencil = 0;
  37034. /**
  37035. * The current render target.
  37036. *
  37037. * @private
  37038. * @type {?RenderTarget}
  37039. * @default null
  37040. */
  37041. this._renderTarget = null;
  37042. /**
  37043. * The active cube face.
  37044. *
  37045. * @private
  37046. * @type {number}
  37047. * @default 0
  37048. */
  37049. this._activeCubeFace = 0;
  37050. /**
  37051. * The active mipmap level.
  37052. *
  37053. * @private
  37054. * @type {number}
  37055. * @default 0
  37056. */
  37057. this._activeMipmapLevel = 0;
  37058. /**
  37059. * The current output render target.
  37060. *
  37061. * @private
  37062. * @type {?RenderTarget}
  37063. * @default null
  37064. */
  37065. this._outputRenderTarget = null;
  37066. /**
  37067. * The MRT setting.
  37068. *
  37069. * @private
  37070. * @type {?MRTNode}
  37071. * @default null
  37072. */
  37073. this._mrt = null;
  37074. /**
  37075. * This function defines how a render object is going
  37076. * to be rendered.
  37077. *
  37078. * @private
  37079. * @type {?Function}
  37080. * @default null
  37081. */
  37082. this._renderObjectFunction = null;
  37083. /**
  37084. * Used to keep track of the current render object function.
  37085. *
  37086. * @private
  37087. * @type {?Function}
  37088. * @default null
  37089. */
  37090. this._currentRenderObjectFunction = null;
  37091. /**
  37092. * Used to keep track of the current render bundle.
  37093. *
  37094. * @private
  37095. * @type {?RenderBundle}
  37096. * @default null
  37097. */
  37098. this._currentRenderBundle = null;
  37099. /**
  37100. * Next to `_renderObjectFunction()`, this function provides another hook
  37101. * for influencing the render process of a render object. It is meant for internal
  37102. * use and only relevant for `compileAsync()` right now. Instead of using
  37103. * the default logic of `_renderObjectDirect()` which actually draws the render object,
  37104. * a different function might be used which performs no draw but just the node
  37105. * and pipeline updates.
  37106. *
  37107. * @private
  37108. * @type {?Function}
  37109. * @default null
  37110. */
  37111. this._handleObjectFunction = this._renderObjectDirect;
  37112. /**
  37113. * Indicates whether the device has been lost or not. In WebGL terms, the device
  37114. * lost is considered as a context lost. When this is set to `true`, rendering
  37115. * isn't possible anymore.
  37116. *
  37117. * @private
  37118. * @type {boolean}
  37119. * @default false
  37120. */
  37121. this._isDeviceLost = false;
  37122. /**
  37123. * A callback function that defines what should happen when a device/context lost occurs.
  37124. *
  37125. * @type {Function}
  37126. */
  37127. this.onDeviceLost = this._onDeviceLost;
  37128. /**
  37129. * Defines the type of color buffers. The default `HalfFloatType` is recommend for
  37130. * best quality. To save memory and bandwidth, `UnsignedByteType` might be used.
  37131. * This will reduce rendering quality though.
  37132. *
  37133. * @private
  37134. * @type {number}
  37135. * @default HalfFloatType
  37136. */
  37137. this._colorBufferType = colorBufferType;
  37138. /**
  37139. * Whether the renderer has been initialized or not.
  37140. *
  37141. * @private
  37142. * @type {boolean}
  37143. * @default false
  37144. */
  37145. this._initialized = false;
  37146. /**
  37147. * A reference to the promise which initializes the renderer.
  37148. *
  37149. * @private
  37150. * @type {?Promise<this>}
  37151. * @default null
  37152. */
  37153. this._initPromise = null;
  37154. /**
  37155. * An array of compilation promises which are used in `compileAsync()`.
  37156. *
  37157. * @private
  37158. * @type {?Array<Promise>}
  37159. * @default null
  37160. */
  37161. this._compilationPromises = null;
  37162. /**
  37163. * Whether the renderer should render transparent render objects or not.
  37164. *
  37165. * @type {boolean}
  37166. * @default true
  37167. */
  37168. this.transparent = true;
  37169. /**
  37170. * Whether the renderer should render opaque render objects or not.
  37171. *
  37172. * @type {boolean}
  37173. * @default true
  37174. */
  37175. this.opaque = true;
  37176. /**
  37177. * Shadow map configuration
  37178. * @typedef {Object} ShadowMapConfig
  37179. * @property {boolean} enabled - Whether to globally enable shadows or not.
  37180. * @property {number} type - The shadow map type.
  37181. */
  37182. /**
  37183. * The renderer's shadow configuration.
  37184. *
  37185. * @type {ShadowMapConfig}
  37186. */
  37187. this.shadowMap = {
  37188. enabled: false,
  37189. type: PCFShadowMap
  37190. };
  37191. /**
  37192. * XR configuration.
  37193. * @typedef {Object} XRConfig
  37194. * @property {boolean} enabled - Whether to globally enable XR or not.
  37195. */
  37196. /**
  37197. * The renderer's XR manager.
  37198. *
  37199. * @type {XRManager}
  37200. */
  37201. this.xr = new XRManager( this, multiview );
  37202. /**
  37203. * Debug configuration.
  37204. * @typedef {Object} DebugConfig
  37205. * @property {boolean} checkShaderErrors - Whether shader errors should be checked or not.
  37206. * @property {?Function} onShaderError - A callback function that is executed when a shader error happens. Only supported with WebGL 2 right now.
  37207. * @property {Function} getShaderAsync - Allows the get the raw shader code for the given scene, camera and 3D object.
  37208. */
  37209. /**
  37210. * The renderer's debug configuration.
  37211. *
  37212. * @type {DebugConfig}
  37213. */
  37214. this.debug = {
  37215. checkShaderErrors: true,
  37216. onShaderError: null,
  37217. getShaderAsync: async ( scene, camera, object ) => {
  37218. await this.compileAsync( scene, camera );
  37219. const renderList = this._renderLists.get( scene, camera );
  37220. const renderContext = this._renderContexts.get( scene, camera, this._renderTarget );
  37221. const material = scene.overrideMaterial || object.material;
  37222. const renderObject = this._objects.get( object, material, scene, camera, renderList.lightsNode, renderContext, renderContext.clippingContext );
  37223. const { fragmentShader, vertexShader } = renderObject.getNodeBuilderState();
  37224. return { fragmentShader, vertexShader };
  37225. }
  37226. };
  37227. }
  37228. /**
  37229. * Initializes the renderer so it is ready for usage.
  37230. *
  37231. * @async
  37232. * @return {Promise<this>} A Promise that resolves when the renderer has been initialized.
  37233. */
  37234. async init() {
  37235. if ( this._initialized ) {
  37236. throw new Error( 'Renderer: Backend has already been initialized.' );
  37237. }
  37238. if ( this._initPromise !== null ) {
  37239. return this._initPromise;
  37240. }
  37241. this._initPromise = new Promise( async ( resolve, reject ) => {
  37242. let backend = this.backend;
  37243. try {
  37244. await backend.init( this );
  37245. } catch ( error ) {
  37246. if ( this._getFallback !== null ) {
  37247. // try the fallback
  37248. try {
  37249. this.backend = backend = this._getFallback( error );
  37250. await backend.init( this );
  37251. } catch ( error ) {
  37252. reject( error );
  37253. return;
  37254. }
  37255. } else {
  37256. reject( error );
  37257. return;
  37258. }
  37259. }
  37260. this._nodes = new Nodes( this, backend );
  37261. this._animation = new Animation( this._nodes, this.info );
  37262. this._attributes = new Attributes( backend );
  37263. this._background = new Background( this, this._nodes );
  37264. this._geometries = new Geometries( this._attributes, this.info );
  37265. this._textures = new Textures( this, backend, this.info );
  37266. this._pipelines = new Pipelines( backend, this._nodes );
  37267. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  37268. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  37269. this._renderLists = new RenderLists( this.lighting );
  37270. this._bundles = new RenderBundles();
  37271. this._renderContexts = new RenderContexts();
  37272. //
  37273. this._animation.start();
  37274. this._initialized = true;
  37275. resolve( this );
  37276. } );
  37277. return this._initPromise;
  37278. }
  37279. /**
  37280. * The coordinate system of the renderer. The value of this property
  37281. * depends on the selected backend. Either `THREE.WebGLCoordinateSystem` or
  37282. * `THREE.WebGPUCoordinateSystem`.
  37283. *
  37284. * @readonly
  37285. * @type {number}
  37286. */
  37287. get coordinateSystem() {
  37288. return this.backend.coordinateSystem;
  37289. }
  37290. /**
  37291. * Compiles all materials in the given scene. This can be useful to avoid a
  37292. * phenomenon which is called "shader compilation stutter", which occurs when
  37293. * rendering an object with a new shader for the first time.
  37294. *
  37295. * If you want to add a 3D object to an existing scene, use the third optional
  37296. * parameter for applying the target scene. Note that the (target) scene's lighting
  37297. * and environment must be configured before calling this method.
  37298. *
  37299. * @async
  37300. * @param {Object3D} scene - The scene or 3D object to precompile.
  37301. * @param {Camera} camera - The camera that is used to render the scene.
  37302. * @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.
  37303. * @return {Promise<Array|undefined>} A Promise that resolves when the compile has been finished.
  37304. */
  37305. async compileAsync( scene, camera, targetScene = null ) {
  37306. if ( this._isDeviceLost === true ) return;
  37307. if ( this._initialized === false ) await this.init();
  37308. // preserve render tree
  37309. const nodeFrame = this._nodes.nodeFrame;
  37310. const previousRenderId = nodeFrame.renderId;
  37311. const previousRenderContext = this._currentRenderContext;
  37312. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  37313. const previousCompilationPromises = this._compilationPromises;
  37314. //
  37315. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  37316. if ( targetScene === null ) targetScene = scene;
  37317. const renderTarget = this._renderTarget;
  37318. const renderContext = this._renderContexts.get( targetScene, camera, renderTarget );
  37319. const activeMipmapLevel = this._activeMipmapLevel;
  37320. const compilationPromises = [];
  37321. this._currentRenderContext = renderContext;
  37322. this._currentRenderObjectFunction = this.renderObject;
  37323. this._handleObjectFunction = this._createObjectPipeline;
  37324. this._compilationPromises = compilationPromises;
  37325. nodeFrame.renderId ++;
  37326. //
  37327. nodeFrame.update();
  37328. //
  37329. renderContext.depth = this.depth;
  37330. renderContext.stencil = this.stencil;
  37331. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  37332. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  37333. //
  37334. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  37335. //
  37336. const renderList = this._renderLists.get( scene, camera );
  37337. renderList.begin();
  37338. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  37339. // include lights from target scene
  37340. if ( targetScene !== scene ) {
  37341. targetScene.traverseVisible( function ( object ) {
  37342. if ( object.isLight && object.layers.test( camera.layers ) ) {
  37343. renderList.pushLight( object );
  37344. }
  37345. } );
  37346. }
  37347. renderList.finish();
  37348. //
  37349. if ( renderTarget !== null ) {
  37350. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  37351. const renderTargetData = this._textures.get( renderTarget );
  37352. renderContext.textures = renderTargetData.textures;
  37353. renderContext.depthTexture = renderTargetData.depthTexture;
  37354. } else {
  37355. renderContext.textures = null;
  37356. renderContext.depthTexture = null;
  37357. }
  37358. //
  37359. this._background.update( sceneRef, renderList, renderContext );
  37360. // process render lists
  37361. const opaqueObjects = renderList.opaque;
  37362. const transparentObjects = renderList.transparent;
  37363. const transparentDoublePassObjects = renderList.transparentDoublePass;
  37364. const lightsNode = renderList.lightsNode;
  37365. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  37366. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  37367. // restore render tree
  37368. nodeFrame.renderId = previousRenderId;
  37369. this._currentRenderContext = previousRenderContext;
  37370. this._currentRenderObjectFunction = previousRenderObjectFunction;
  37371. this._compilationPromises = previousCompilationPromises;
  37372. this._handleObjectFunction = this._renderObjectDirect;
  37373. // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete
  37374. await Promise.all( compilationPromises );
  37375. }
  37376. /**
  37377. * Renders the scene in an async fashion.
  37378. *
  37379. * @async
  37380. * @param {Object3D} scene - The scene or 3D object to render.
  37381. * @param {Camera} camera - The camera.
  37382. * @return {Promise} A Promise that resolves when the render has been finished.
  37383. */
  37384. async renderAsync( scene, camera ) {
  37385. if ( this._initialized === false ) await this.init();
  37386. this._renderScene( scene, camera );
  37387. }
  37388. /**
  37389. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  37390. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  37391. *
  37392. * @async
  37393. * @return {Promise} A Promise that resolves when synchronization has been finished.
  37394. */
  37395. async waitForGPU() {
  37396. await this.backend.waitForGPU();
  37397. }
  37398. /**
  37399. * Enables or disables high precision for model-view and normal-view matrices.
  37400. * When enabled, will use CPU 64-bit precision for higher precision instead of GPU 32-bit for higher performance.
  37401. *
  37402. * NOTE: 64-bit precision is not compatible with `InstancedMesh` and `SkinnedMesh`.
  37403. *
  37404. * @param {boolean} value - Whether to enable or disable high precision.
  37405. * @type {boolean}
  37406. */
  37407. set highPrecision( value ) {
  37408. if ( value === true ) {
  37409. this.overrideNodes.modelViewMatrix = highpModelViewMatrix;
  37410. this.overrideNodes.modelNormalViewMatrix = highpModelNormalViewMatrix;
  37411. } else if ( this.highPrecision ) {
  37412. this.overrideNodes.modelViewMatrix = null;
  37413. this.overrideNodes.modelNormalViewMatrix = null;
  37414. }
  37415. }
  37416. /**
  37417. * Returns whether high precision is enabled or not.
  37418. *
  37419. * @return {boolean} Whether high precision is enabled or not.
  37420. * @type {boolean}
  37421. */
  37422. get highPrecision() {
  37423. return this.overrideNodes.modelViewMatrix === highpModelViewMatrix && this.overrideNodes.modelNormalViewMatrix === highpModelNormalViewMatrix;
  37424. }
  37425. /**
  37426. * Sets the given MRT configuration.
  37427. *
  37428. * @param {MRTNode} mrt - The MRT node to set.
  37429. * @return {Renderer} A reference to this renderer.
  37430. */
  37431. setMRT( mrt ) {
  37432. this._mrt = mrt;
  37433. return this;
  37434. }
  37435. /**
  37436. * Returns the MRT configuration.
  37437. *
  37438. * @return {MRTNode} The MRT configuration.
  37439. */
  37440. getMRT() {
  37441. return this._mrt;
  37442. }
  37443. /**
  37444. * Returns the color buffer type.
  37445. *
  37446. * @return {number} The color buffer type.
  37447. */
  37448. getColorBufferType() {
  37449. return this._colorBufferType;
  37450. }
  37451. /**
  37452. * Default implementation of the device lost callback.
  37453. *
  37454. * @private
  37455. * @param {Object} info - Information about the context lost.
  37456. */
  37457. _onDeviceLost( info ) {
  37458. let errorMessage = `THREE.WebGPURenderer: ${info.api} Device Lost:\n\nMessage: ${info.message}`;
  37459. if ( info.reason ) {
  37460. errorMessage += `\nReason: ${info.reason}`;
  37461. }
  37462. console.error( errorMessage );
  37463. this._isDeviceLost = true;
  37464. }
  37465. /**
  37466. * Renders the given render bundle.
  37467. *
  37468. * @private
  37469. * @param {Object} bundle - Render bundle data.
  37470. * @param {Scene} sceneRef - The scene the render bundle belongs to.
  37471. * @param {LightsNode} lightsNode - The lights node.
  37472. */
  37473. _renderBundle( bundle, sceneRef, lightsNode ) {
  37474. const { bundleGroup, camera, renderList } = bundle;
  37475. const renderContext = this._currentRenderContext;
  37476. //
  37477. const renderBundle = this._bundles.get( bundleGroup, camera );
  37478. const renderBundleData = this.backend.get( renderBundle );
  37479. if ( renderBundleData.renderContexts === undefined ) renderBundleData.renderContexts = new Set();
  37480. //
  37481. const needsUpdate = bundleGroup.version !== renderBundleData.version;
  37482. const renderBundleNeedsUpdate = renderBundleData.renderContexts.has( renderContext ) === false || needsUpdate;
  37483. renderBundleData.renderContexts.add( renderContext );
  37484. if ( renderBundleNeedsUpdate ) {
  37485. this.backend.beginBundle( renderContext );
  37486. if ( renderBundleData.renderObjects === undefined || needsUpdate ) {
  37487. renderBundleData.renderObjects = [];
  37488. }
  37489. this._currentRenderBundle = renderBundle;
  37490. const {
  37491. transparentDoublePass: transparentDoublePassObjects,
  37492. transparent: transparentObjects,
  37493. opaque: opaqueObjects
  37494. } = renderList;
  37495. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  37496. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  37497. this._currentRenderBundle = null;
  37498. //
  37499. this.backend.finishBundle( renderContext, renderBundle );
  37500. renderBundleData.version = bundleGroup.version;
  37501. } else {
  37502. const { renderObjects } = renderBundleData;
  37503. for ( let i = 0, l = renderObjects.length; i < l; i ++ ) {
  37504. const renderObject = renderObjects[ i ];
  37505. if ( this._nodes.needsRefresh( renderObject ) ) {
  37506. this._nodes.updateBefore( renderObject );
  37507. this._nodes.updateForRender( renderObject );
  37508. this._bindings.updateForRender( renderObject );
  37509. this._nodes.updateAfter( renderObject );
  37510. }
  37511. }
  37512. }
  37513. this.backend.addBundle( renderContext, renderBundle );
  37514. }
  37515. /**
  37516. * Renders the scene or 3D object with the given camera. This method can only be called
  37517. * if the renderer has been initialized.
  37518. *
  37519. * The target of the method is the default framebuffer (meaning the canvas)
  37520. * or alternatively a render target when specified via `setRenderTarget()`.
  37521. *
  37522. * @param {Object3D} scene - The scene or 3D object to render.
  37523. * @param {Camera} camera - The camera to render the scene with.
  37524. * @return {?Promise} A Promise that resolve when the scene has been rendered.
  37525. * Only returned when the renderer has not been initialized.
  37526. */
  37527. render( scene, camera ) {
  37528. if ( this._initialized === false ) {
  37529. console.warn( 'THREE.Renderer: .render() called before the backend is initialized. Try using .renderAsync() instead.' );
  37530. return this.renderAsync( scene, camera );
  37531. }
  37532. this._renderScene( scene, camera );
  37533. }
  37534. /**
  37535. * Returns an internal render target which is used when computing the output tone mapping
  37536. * and color space conversion. Unlike in `WebGLRenderer`, this is done in a separate render
  37537. * pass and not inline to achieve more correct results.
  37538. *
  37539. * @private
  37540. * @return {?RenderTarget} The render target. The method returns `null` if no output conversion should be applied.
  37541. */
  37542. _getFrameBufferTarget() {
  37543. const { currentToneMapping, currentColorSpace } = this;
  37544. const useToneMapping = currentToneMapping !== NoToneMapping;
  37545. const useColorSpace = currentColorSpace !== LinearSRGBColorSpace;
  37546. if ( useToneMapping === false && useColorSpace === false ) return null;
  37547. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize$1 );
  37548. const { depth, stencil } = this;
  37549. let frameBufferTarget = this._frameBufferTarget;
  37550. if ( frameBufferTarget === null ) {
  37551. frameBufferTarget = new RenderTarget( width, height, {
  37552. depthBuffer: depth,
  37553. stencilBuffer: stencil,
  37554. type: this._colorBufferType,
  37555. format: RGBAFormat,
  37556. colorSpace: LinearSRGBColorSpace,
  37557. generateMipmaps: false,
  37558. minFilter: LinearFilter,
  37559. magFilter: LinearFilter,
  37560. samples: this.samples
  37561. } );
  37562. frameBufferTarget.isPostProcessingRenderTarget = true;
  37563. this._frameBufferTarget = frameBufferTarget;
  37564. }
  37565. const outputRenderTarget = this.getOutputRenderTarget();
  37566. frameBufferTarget.depthBuffer = depth;
  37567. frameBufferTarget.stencilBuffer = stencil;
  37568. if ( outputRenderTarget !== null ) {
  37569. frameBufferTarget.setSize( outputRenderTarget.width, outputRenderTarget.height, outputRenderTarget.depth );
  37570. } else {
  37571. frameBufferTarget.setSize( width, height, 1 );
  37572. }
  37573. frameBufferTarget.viewport.copy( this._viewport );
  37574. frameBufferTarget.scissor.copy( this._scissor );
  37575. frameBufferTarget.viewport.multiplyScalar( this._pixelRatio );
  37576. frameBufferTarget.scissor.multiplyScalar( this._pixelRatio );
  37577. frameBufferTarget.scissorTest = this._scissorTest;
  37578. frameBufferTarget.multiview = outputRenderTarget !== null ? outputRenderTarget.multiview : false;
  37579. frameBufferTarget.resolveDepthBuffer = outputRenderTarget !== null ? outputRenderTarget.resolveDepthBuffer : true;
  37580. frameBufferTarget.autoAllocateDepthBuffer = outputRenderTarget !== null ? outputRenderTarget.autoAllocateDepthBuffer : false;
  37581. return frameBufferTarget;
  37582. }
  37583. /**
  37584. * Renders the scene or 3D object with the given camera.
  37585. *
  37586. * @private
  37587. * @param {Object3D} scene - The scene or 3D object to render.
  37588. * @param {Camera} camera - The camera to render the scene with.
  37589. * @param {boolean} [useFrameBufferTarget=true] - Whether to use a framebuffer target or not.
  37590. * @return {RenderContext} The current render context.
  37591. */
  37592. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  37593. if ( this._isDeviceLost === true ) return;
  37594. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  37595. // preserve render tree
  37596. const nodeFrame = this._nodes.nodeFrame;
  37597. const previousRenderId = nodeFrame.renderId;
  37598. const previousRenderContext = this._currentRenderContext;
  37599. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  37600. //
  37601. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  37602. const outputRenderTarget = this._renderTarget || this._outputRenderTarget;
  37603. const activeCubeFace = this._activeCubeFace;
  37604. const activeMipmapLevel = this._activeMipmapLevel;
  37605. //
  37606. let renderTarget;
  37607. if ( frameBufferTarget !== null ) {
  37608. renderTarget = frameBufferTarget;
  37609. this.setRenderTarget( renderTarget );
  37610. } else {
  37611. renderTarget = outputRenderTarget;
  37612. }
  37613. //
  37614. const renderContext = this._renderContexts.get( scene, camera, renderTarget );
  37615. this._currentRenderContext = renderContext;
  37616. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  37617. //
  37618. this.info.calls ++;
  37619. this.info.render.calls ++;
  37620. this.info.render.frameCalls ++;
  37621. nodeFrame.renderId = this.info.calls;
  37622. //
  37623. const coordinateSystem = this.coordinateSystem;
  37624. const xr = this.xr;
  37625. if ( camera.coordinateSystem !== coordinateSystem && xr.isPresenting === false ) {
  37626. camera.coordinateSystem = coordinateSystem;
  37627. camera.updateProjectionMatrix();
  37628. if ( camera.isArrayCamera ) {
  37629. for ( const subCamera of camera.cameras ) {
  37630. subCamera.coordinateSystem = coordinateSystem;
  37631. subCamera.updateProjectionMatrix();
  37632. }
  37633. }
  37634. }
  37635. //
  37636. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  37637. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  37638. if ( xr.enabled === true && xr.isPresenting === true ) {
  37639. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  37640. camera = xr.getCamera(); // use XR camera for rendering
  37641. }
  37642. //
  37643. let viewport = this._viewport;
  37644. let scissor = this._scissor;
  37645. let pixelRatio = this._pixelRatio;
  37646. if ( renderTarget !== null ) {
  37647. viewport = renderTarget.viewport;
  37648. scissor = renderTarget.scissor;
  37649. pixelRatio = 1;
  37650. }
  37651. this.getDrawingBufferSize( _drawingBufferSize$1 );
  37652. _screen.set( 0, 0, _drawingBufferSize$1.width, _drawingBufferSize$1.height );
  37653. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  37654. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  37655. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  37656. renderContext.viewportValue.width >>= activeMipmapLevel;
  37657. renderContext.viewportValue.height >>= activeMipmapLevel;
  37658. renderContext.viewportValue.minDepth = minDepth;
  37659. renderContext.viewportValue.maxDepth = maxDepth;
  37660. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  37661. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  37662. renderContext.scissor = this._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  37663. renderContext.scissorValue.width >>= activeMipmapLevel;
  37664. renderContext.scissorValue.height >>= activeMipmapLevel;
  37665. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  37666. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  37667. //
  37668. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  37669. //
  37670. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  37671. if ( ! camera.isArrayCamera ) {
  37672. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  37673. frustum.setFromProjectionMatrix( _projScreenMatrix, coordinateSystem );
  37674. }
  37675. const renderList = this._renderLists.get( scene, camera );
  37676. renderList.begin();
  37677. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  37678. renderList.finish();
  37679. if ( this.sortObjects === true ) {
  37680. renderList.sort( this._opaqueSort, this._transparentSort );
  37681. }
  37682. //
  37683. if ( renderTarget !== null ) {
  37684. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  37685. const renderTargetData = this._textures.get( renderTarget );
  37686. renderContext.textures = renderTargetData.textures;
  37687. renderContext.depthTexture = renderTargetData.depthTexture;
  37688. renderContext.width = renderTargetData.width;
  37689. renderContext.height = renderTargetData.height;
  37690. renderContext.renderTarget = renderTarget;
  37691. renderContext.depth = renderTarget.depthBuffer;
  37692. renderContext.stencil = renderTarget.stencilBuffer;
  37693. } else {
  37694. renderContext.textures = null;
  37695. renderContext.depthTexture = null;
  37696. renderContext.width = this.domElement.width;
  37697. renderContext.height = this.domElement.height;
  37698. renderContext.depth = this.depth;
  37699. renderContext.stencil = this.stencil;
  37700. }
  37701. renderContext.width >>= activeMipmapLevel;
  37702. renderContext.height >>= activeMipmapLevel;
  37703. renderContext.activeCubeFace = activeCubeFace;
  37704. renderContext.activeMipmapLevel = activeMipmapLevel;
  37705. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  37706. //
  37707. this._background.update( sceneRef, renderList, renderContext );
  37708. //
  37709. renderContext.camera = camera;
  37710. this.backend.beginRender( renderContext );
  37711. // process render lists
  37712. const {
  37713. bundles,
  37714. lightsNode,
  37715. transparentDoublePass: transparentDoublePassObjects,
  37716. transparent: transparentObjects,
  37717. opaque: opaqueObjects
  37718. } = renderList;
  37719. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  37720. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  37721. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  37722. // finish render pass
  37723. this.backend.finishRender( renderContext );
  37724. // restore render tree
  37725. nodeFrame.renderId = previousRenderId;
  37726. this._currentRenderContext = previousRenderContext;
  37727. this._currentRenderObjectFunction = previousRenderObjectFunction;
  37728. //
  37729. if ( frameBufferTarget !== null ) {
  37730. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  37731. this._renderOutput( renderTarget );
  37732. }
  37733. //
  37734. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  37735. //
  37736. return renderContext;
  37737. }
  37738. _setXRLayerSize( width, height ) {
  37739. this._width = width;
  37740. this._height = height;
  37741. this.setViewport( 0, 0, width, height );
  37742. }
  37743. /**
  37744. * The output pass performs tone mapping and color space conversion.
  37745. *
  37746. * @private
  37747. * @param {RenderTarget} renderTarget - The current render target.
  37748. */
  37749. _renderOutput( renderTarget ) {
  37750. const quad = this._quad;
  37751. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  37752. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  37753. quad.material.needsUpdate = true;
  37754. }
  37755. // a clear operation clears the intermediate renderTarget texture, but should not update the screen canvas.
  37756. const currentAutoClear = this.autoClear;
  37757. const currentXR = this.xr.enabled;
  37758. this.autoClear = false;
  37759. this.xr.enabled = false;
  37760. this._renderScene( quad, quad.camera, false );
  37761. this.autoClear = currentAutoClear;
  37762. this.xr.enabled = currentXR;
  37763. }
  37764. /**
  37765. * Returns the maximum available anisotropy for texture filtering.
  37766. *
  37767. * @return {number} The maximum available anisotropy.
  37768. */
  37769. getMaxAnisotropy() {
  37770. return this.backend.getMaxAnisotropy();
  37771. }
  37772. /**
  37773. * Returns the active cube face.
  37774. *
  37775. * @return {number} The active cube face.
  37776. */
  37777. getActiveCubeFace() {
  37778. return this._activeCubeFace;
  37779. }
  37780. /**
  37781. * Returns the active mipmap level.
  37782. *
  37783. * @return {number} The active mipmap level.
  37784. */
  37785. getActiveMipmapLevel() {
  37786. return this._activeMipmapLevel;
  37787. }
  37788. /**
  37789. * Applications are advised to always define the animation loop
  37790. * with this method and not manually with `requestAnimationFrame()`
  37791. * for best compatibility.
  37792. *
  37793. * @async
  37794. * @param {?Function} callback - The application's animation loop.
  37795. * @return {Promise} A Promise that resolves when the set has been executed.
  37796. */
  37797. async setAnimationLoop( callback ) {
  37798. if ( this._initialized === false ) await this.init();
  37799. this._animation.setAnimationLoop( callback );
  37800. }
  37801. /**
  37802. * Can be used to transfer buffer data from a storage buffer attribute
  37803. * from the GPU to the CPU in context of compute shaders.
  37804. *
  37805. * @async
  37806. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  37807. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  37808. */
  37809. async getArrayBufferAsync( attribute ) {
  37810. return await this.backend.getArrayBufferAsync( attribute );
  37811. }
  37812. /**
  37813. * Returns the rendering context.
  37814. *
  37815. * @return {GPUCanvasContext|WebGL2RenderingContext} The rendering context.
  37816. */
  37817. getContext() {
  37818. return this.backend.getContext();
  37819. }
  37820. /**
  37821. * Returns the pixel ratio.
  37822. *
  37823. * @return {number} The pixel ratio.
  37824. */
  37825. getPixelRatio() {
  37826. return this._pixelRatio;
  37827. }
  37828. /**
  37829. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  37830. *
  37831. * @param {Vector2} target - The method writes the result in this target object.
  37832. * @return {Vector2} The drawing buffer size.
  37833. */
  37834. getDrawingBufferSize( target ) {
  37835. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  37836. }
  37837. /**
  37838. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  37839. *
  37840. * @param {Vector2} target - The method writes the result in this target object.
  37841. * @return {Vector2} The renderer's size in logical pixels.
  37842. */
  37843. getSize( target ) {
  37844. return target.set( this._width, this._height );
  37845. }
  37846. /**
  37847. * Sets the given pixel ratio and resizes the canvas if necessary.
  37848. *
  37849. * @param {number} [value=1] - The pixel ratio.
  37850. */
  37851. setPixelRatio( value = 1 ) {
  37852. if ( this._pixelRatio === value ) return;
  37853. this._pixelRatio = value;
  37854. this.setSize( this._width, this._height, false );
  37855. }
  37856. /**
  37857. * This method allows to define the drawing buffer size by specifying
  37858. * width, height and pixel ratio all at once. The size of the drawing
  37859. * buffer is computed with this formula:
  37860. * ```js
  37861. * size.x = width * pixelRatio;
  37862. * size.y = height * pixelRatio;
  37863. * ```
  37864. *
  37865. * @param {number} width - The width in logical pixels.
  37866. * @param {number} height - The height in logical pixels.
  37867. * @param {number} pixelRatio - The pixel ratio.
  37868. */
  37869. setDrawingBufferSize( width, height, pixelRatio ) {
  37870. // Renderer can't be resized while presenting in XR.
  37871. if ( this.xr && this.xr.isPresenting ) return;
  37872. this._width = width;
  37873. this._height = height;
  37874. this._pixelRatio = pixelRatio;
  37875. this.domElement.width = Math.floor( width * pixelRatio );
  37876. this.domElement.height = Math.floor( height * pixelRatio );
  37877. this.setViewport( 0, 0, width, height );
  37878. if ( this._initialized ) this.backend.updateSize();
  37879. }
  37880. /**
  37881. * Sets the size of the renderer.
  37882. *
  37883. * @param {number} width - The width in logical pixels.
  37884. * @param {number} height - The height in logical pixels.
  37885. * @param {boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  37886. */
  37887. setSize( width, height, updateStyle = true ) {
  37888. // Renderer can't be resized while presenting in XR.
  37889. if ( this.xr && this.xr.isPresenting ) return;
  37890. this._width = width;
  37891. this._height = height;
  37892. this.domElement.width = Math.floor( width * this._pixelRatio );
  37893. this.domElement.height = Math.floor( height * this._pixelRatio );
  37894. if ( updateStyle === true ) {
  37895. this.domElement.style.width = width + 'px';
  37896. this.domElement.style.height = height + 'px';
  37897. }
  37898. this.setViewport( 0, 0, width, height );
  37899. if ( this._initialized ) this.backend.updateSize();
  37900. }
  37901. /**
  37902. * Defines a manual sort function for the opaque render list.
  37903. * Pass `null` to use the default sort.
  37904. *
  37905. * @param {Function} method - The sort function.
  37906. */
  37907. setOpaqueSort( method ) {
  37908. this._opaqueSort = method;
  37909. }
  37910. /**
  37911. * Defines a manual sort function for the transparent render list.
  37912. * Pass `null` to use the default sort.
  37913. *
  37914. * @param {Function} method - The sort function.
  37915. */
  37916. setTransparentSort( method ) {
  37917. this._transparentSort = method;
  37918. }
  37919. /**
  37920. * Returns the scissor rectangle.
  37921. *
  37922. * @param {Vector4} target - The method writes the result in this target object.
  37923. * @return {Vector4} The scissor rectangle.
  37924. */
  37925. getScissor( target ) {
  37926. const scissor = this._scissor;
  37927. target.x = scissor.x;
  37928. target.y = scissor.y;
  37929. target.width = scissor.width;
  37930. target.height = scissor.height;
  37931. return target;
  37932. }
  37933. /**
  37934. * Defines the scissor rectangle.
  37935. *
  37936. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  37937. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  37938. * @param {number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  37939. * @param {number} width - The width of the scissor box in logical pixel unit.
  37940. * @param {number} height - The height of the scissor box in logical pixel unit.
  37941. */
  37942. setScissor( x, y, width, height ) {
  37943. const scissor = this._scissor;
  37944. if ( x.isVector4 ) {
  37945. scissor.copy( x );
  37946. } else {
  37947. scissor.set( x, y, width, height );
  37948. }
  37949. }
  37950. /**
  37951. * Returns the scissor test value.
  37952. *
  37953. * @return {boolean} Whether the scissor test should be enabled or not.
  37954. */
  37955. getScissorTest() {
  37956. return this._scissorTest;
  37957. }
  37958. /**
  37959. * Defines the scissor test.
  37960. *
  37961. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  37962. */
  37963. setScissorTest( boolean ) {
  37964. this._scissorTest = boolean;
  37965. this.backend.setScissorTest( boolean );
  37966. }
  37967. /**
  37968. * Returns the viewport definition.
  37969. *
  37970. * @param {Vector4} target - The method writes the result in this target object.
  37971. * @return {Vector4} The viewport definition.
  37972. */
  37973. getViewport( target ) {
  37974. return target.copy( this._viewport );
  37975. }
  37976. /**
  37977. * Defines the viewport.
  37978. *
  37979. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  37980. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  37981. * @param {number} width - The width of the viewport in logical pixel unit.
  37982. * @param {number} height - The height of the viewport in logical pixel unit.
  37983. * @param {number} minDepth - The minimum depth value of the viewport. WebGPU only.
  37984. * @param {number} maxDepth - The maximum depth value of the viewport. WebGPU only.
  37985. */
  37986. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  37987. const viewport = this._viewport;
  37988. if ( x.isVector4 ) {
  37989. viewport.copy( x );
  37990. } else {
  37991. viewport.set( x, y, width, height );
  37992. }
  37993. viewport.minDepth = minDepth;
  37994. viewport.maxDepth = maxDepth;
  37995. }
  37996. /**
  37997. * Returns the clear color.
  37998. *
  37999. * @param {Color} target - The method writes the result in this target object.
  38000. * @return {Color} The clear color.
  38001. */
  38002. getClearColor( target ) {
  38003. return target.copy( this._clearColor );
  38004. }
  38005. /**
  38006. * Defines the clear color and optionally the clear alpha.
  38007. *
  38008. * @param {Color} color - The clear color.
  38009. * @param {number} [alpha=1] - The clear alpha.
  38010. */
  38011. setClearColor( color, alpha = 1 ) {
  38012. this._clearColor.set( color );
  38013. this._clearColor.a = alpha;
  38014. }
  38015. /**
  38016. * Returns the clear alpha.
  38017. *
  38018. * @return {number} The clear alpha.
  38019. */
  38020. getClearAlpha() {
  38021. return this._clearColor.a;
  38022. }
  38023. /**
  38024. * Defines the clear alpha.
  38025. *
  38026. * @param {number} alpha - The clear alpha.
  38027. */
  38028. setClearAlpha( alpha ) {
  38029. this._clearColor.a = alpha;
  38030. }
  38031. /**
  38032. * Returns the clear depth.
  38033. *
  38034. * @return {number} The clear depth.
  38035. */
  38036. getClearDepth() {
  38037. return this._clearDepth;
  38038. }
  38039. /**
  38040. * Defines the clear depth.
  38041. *
  38042. * @param {number} depth - The clear depth.
  38043. */
  38044. setClearDepth( depth ) {
  38045. this._clearDepth = depth;
  38046. }
  38047. /**
  38048. * Returns the clear stencil.
  38049. *
  38050. * @return {number} The clear stencil.
  38051. */
  38052. getClearStencil() {
  38053. return this._clearStencil;
  38054. }
  38055. /**
  38056. * Defines the clear stencil.
  38057. *
  38058. * @param {number} stencil - The clear stencil.
  38059. */
  38060. setClearStencil( stencil ) {
  38061. this._clearStencil = stencil;
  38062. }
  38063. /**
  38064. * This method performs an occlusion query for the given 3D object.
  38065. * It returns `true` if the given 3D object is fully occluded by other
  38066. * 3D objects in the scene.
  38067. *
  38068. * @param {Object3D} object - The 3D object to test.
  38069. * @return {boolean} Whether the 3D object is fully occluded or not.
  38070. */
  38071. isOccluded( object ) {
  38072. const renderContext = this._currentRenderContext;
  38073. return renderContext && this.backend.isOccluded( renderContext, object );
  38074. }
  38075. /**
  38076. * Performs a manual clear operation. This method ignores `autoClear` properties.
  38077. *
  38078. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  38079. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  38080. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  38081. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  38082. * Only returned when the renderer has not been initialized.
  38083. */
  38084. clear( color = true, depth = true, stencil = true ) {
  38085. if ( this._initialized === false ) {
  38086. console.warn( 'THREE.Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead.' );
  38087. return this.clearAsync( color, depth, stencil );
  38088. }
  38089. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  38090. let renderContext = null;
  38091. if ( renderTarget !== null ) {
  38092. this._textures.updateRenderTarget( renderTarget );
  38093. const renderTargetData = this._textures.get( renderTarget );
  38094. renderContext = this._renderContexts.getForClear( renderTarget );
  38095. renderContext.textures = renderTargetData.textures;
  38096. renderContext.depthTexture = renderTargetData.depthTexture;
  38097. renderContext.width = renderTargetData.width;
  38098. renderContext.height = renderTargetData.height;
  38099. renderContext.renderTarget = renderTarget;
  38100. renderContext.depth = renderTarget.depthBuffer;
  38101. renderContext.stencil = renderTarget.stencilBuffer;
  38102. // #30329
  38103. renderContext.clearColorValue = this.backend.getClearColor();
  38104. renderContext.activeCubeFace = this.getActiveCubeFace();
  38105. renderContext.activeMipmapLevel = this.getActiveMipmapLevel();
  38106. }
  38107. this.backend.clear( color, depth, stencil, renderContext );
  38108. if ( renderTarget !== null && this._renderTarget === null ) {
  38109. this._renderOutput( renderTarget );
  38110. }
  38111. }
  38112. /**
  38113. * Performs a manual clear operation of the color buffer. This method ignores `autoClear` properties.
  38114. *
  38115. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  38116. * Only returned when the renderer has not been initialized.
  38117. */
  38118. clearColor() {
  38119. return this.clear( true, false, false );
  38120. }
  38121. /**
  38122. * Performs a manual clear operation of the depth buffer. This method ignores `autoClear` properties.
  38123. *
  38124. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  38125. * Only returned when the renderer has not been initialized.
  38126. */
  38127. clearDepth() {
  38128. return this.clear( false, true, false );
  38129. }
  38130. /**
  38131. * Performs a manual clear operation of the stencil buffer. This method ignores `autoClear` properties.
  38132. *
  38133. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  38134. * Only returned when the renderer has not been initialized.
  38135. */
  38136. clearStencil() {
  38137. return this.clear( false, false, true );
  38138. }
  38139. /**
  38140. * Async version of {@link Renderer#clear}.
  38141. *
  38142. * @async
  38143. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  38144. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  38145. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  38146. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  38147. */
  38148. async clearAsync( color = true, depth = true, stencil = true ) {
  38149. if ( this._initialized === false ) await this.init();
  38150. this.clear( color, depth, stencil );
  38151. }
  38152. /**
  38153. * Async version of {@link Renderer#clearColor}.
  38154. *
  38155. * @async
  38156. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  38157. */
  38158. async clearColorAsync() {
  38159. this.clearAsync( true, false, false );
  38160. }
  38161. /**
  38162. * Async version of {@link Renderer#clearDepth}.
  38163. *
  38164. * @async
  38165. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  38166. */
  38167. async clearDepthAsync() {
  38168. this.clearAsync( false, true, false );
  38169. }
  38170. /**
  38171. * Async version of {@link Renderer#clearStencil}.
  38172. *
  38173. * @async
  38174. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  38175. */
  38176. async clearStencilAsync() {
  38177. this.clearAsync( false, false, true );
  38178. }
  38179. /**
  38180. * The current output tone mapping of the renderer. When a render target is set,
  38181. * the output tone mapping is always `NoToneMapping`.
  38182. *
  38183. * @type {number}
  38184. */
  38185. get currentToneMapping() {
  38186. return this.isOutputTarget ? this.toneMapping : NoToneMapping;
  38187. }
  38188. /**
  38189. * The current output color space of the renderer. When a render target is set,
  38190. * the output color space is always `LinearSRGBColorSpace`.
  38191. *
  38192. * @type {string}
  38193. */
  38194. get currentColorSpace() {
  38195. return this.isOutputTarget ? this.outputColorSpace : LinearSRGBColorSpace;
  38196. }
  38197. /**
  38198. * Returns `true` if the rendering settings are set to screen output.
  38199. *
  38200. * @returns {boolean} True if the current render target is the same of output render target or `null`, otherwise false.
  38201. */
  38202. get isOutputTarget() {
  38203. return this._renderTarget === this._outputRenderTarget || this._renderTarget === null;
  38204. }
  38205. /**
  38206. * Frees all internal resources of the renderer. Call this method if the renderer
  38207. * is no longer in use by your app.
  38208. */
  38209. dispose() {
  38210. this.info.dispose();
  38211. this.backend.dispose();
  38212. this._animation.dispose();
  38213. this._objects.dispose();
  38214. this._pipelines.dispose();
  38215. this._nodes.dispose();
  38216. this._bindings.dispose();
  38217. this._renderLists.dispose();
  38218. this._renderContexts.dispose();
  38219. this._textures.dispose();
  38220. if ( this._frameBufferTarget !== null ) this._frameBufferTarget.dispose();
  38221. Object.values( this.backend.timestampQueryPool ).forEach( queryPool => {
  38222. if ( queryPool !== null ) queryPool.dispose();
  38223. } );
  38224. this.setRenderTarget( null );
  38225. this.setAnimationLoop( null );
  38226. }
  38227. /**
  38228. * Sets the given render target. Calling this method means the renderer does not
  38229. * target the default framebuffer (meaning the canvas) anymore but a custom framebuffer.
  38230. * Use `null` as the first argument to reset the state.
  38231. *
  38232. * @param {?RenderTarget} renderTarget - The render target to set.
  38233. * @param {number} [activeCubeFace=0] - The active cube face.
  38234. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  38235. */
  38236. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  38237. this._renderTarget = renderTarget;
  38238. this._activeCubeFace = activeCubeFace;
  38239. this._activeMipmapLevel = activeMipmapLevel;
  38240. }
  38241. /**
  38242. * Returns the current render target.
  38243. *
  38244. * @return {?RenderTarget} The render target. Returns `null` if no render target is set.
  38245. */
  38246. getRenderTarget() {
  38247. return this._renderTarget;
  38248. }
  38249. /**
  38250. * Sets the output render target for the renderer.
  38251. *
  38252. * @param {Object} renderTarget - The render target to set as the output target.
  38253. */
  38254. setOutputRenderTarget( renderTarget ) {
  38255. this._outputRenderTarget = renderTarget;
  38256. }
  38257. /**
  38258. * Returns the current output target.
  38259. *
  38260. * @return {?RenderTarget} The current output render target. Returns `null` if no output target is set.
  38261. */
  38262. getOutputRenderTarget() {
  38263. return this._outputRenderTarget;
  38264. }
  38265. /**
  38266. * Resets the renderer to the initial state before WebXR started.
  38267. *
  38268. */
  38269. _resetXRState() {
  38270. this.backend.setXRTarget( null );
  38271. this.setOutputRenderTarget( null );
  38272. this.setRenderTarget( null );
  38273. this._frameBufferTarget.dispose();
  38274. this._frameBufferTarget = null;
  38275. }
  38276. /**
  38277. * Callback for {@link Renderer#setRenderObjectFunction}.
  38278. *
  38279. * @callback renderObjectFunction
  38280. * @param {Object3D} object - The 3D object.
  38281. * @param {Scene} scene - The scene the 3D object belongs to.
  38282. * @param {Camera} camera - The camera the object should be rendered with.
  38283. * @param {BufferGeometry} geometry - The object's geometry.
  38284. * @param {Material} material - The object's material.
  38285. * @param {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  38286. * @param {LightsNode} lightsNode - The current lights node.
  38287. * @param {ClippingContext} clippingContext - The clipping context.
  38288. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  38289. */
  38290. /**
  38291. * Sets the given render object function. Calling this method overwrites the default implementation
  38292. * which is {@link Renderer#renderObject}. Defining a custom function can be useful
  38293. * if you want to modify the way objects are rendered. For example you can define things like "every
  38294. * object that has material of a certain type should perform a pre-pass with a special overwrite material".
  38295. * The custom function must always call `renderObject()` in its implementation.
  38296. *
  38297. * Use `null` as the first argument to reset the state.
  38298. *
  38299. * @param {?renderObjectFunction} renderObjectFunction - The render object function.
  38300. */
  38301. setRenderObjectFunction( renderObjectFunction ) {
  38302. this._renderObjectFunction = renderObjectFunction;
  38303. }
  38304. /**
  38305. * Returns the current render object function.
  38306. *
  38307. * @return {?Function} The current render object function. Returns `null` if no function is set.
  38308. */
  38309. getRenderObjectFunction() {
  38310. return this._renderObjectFunction;
  38311. }
  38312. /**
  38313. * Execute a single or an array of compute nodes. This method can only be called
  38314. * if the renderer has been initialized.
  38315. *
  38316. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  38317. * @return {Promise|undefined} A Promise that resolve when the compute has finished. Only returned when the renderer has not been initialized.
  38318. */
  38319. compute( computeNodes ) {
  38320. if ( this._isDeviceLost === true ) return;
  38321. if ( this._initialized === false ) {
  38322. console.warn( 'THREE.Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead.' );
  38323. return this.computeAsync( computeNodes );
  38324. }
  38325. //
  38326. const nodeFrame = this._nodes.nodeFrame;
  38327. const previousRenderId = nodeFrame.renderId;
  38328. //
  38329. this.info.calls ++;
  38330. this.info.compute.calls ++;
  38331. this.info.compute.frameCalls ++;
  38332. nodeFrame.renderId = this.info.calls;
  38333. //
  38334. const backend = this.backend;
  38335. const pipelines = this._pipelines;
  38336. const bindings = this._bindings;
  38337. const nodes = this._nodes;
  38338. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  38339. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  38340. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  38341. }
  38342. backend.beginCompute( computeNodes );
  38343. for ( const computeNode of computeList ) {
  38344. // onInit
  38345. if ( pipelines.has( computeNode ) === false ) {
  38346. const dispose = () => {
  38347. computeNode.removeEventListener( 'dispose', dispose );
  38348. pipelines.delete( computeNode );
  38349. bindings.delete( computeNode );
  38350. nodes.delete( computeNode );
  38351. };
  38352. computeNode.addEventListener( 'dispose', dispose );
  38353. //
  38354. const onInitFn = computeNode.onInitFunction;
  38355. if ( onInitFn !== null ) {
  38356. onInitFn.call( computeNode, { renderer: this } );
  38357. }
  38358. }
  38359. nodes.updateForCompute( computeNode );
  38360. bindings.updateForCompute( computeNode );
  38361. const computeBindings = bindings.getForCompute( computeNode );
  38362. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  38363. backend.compute( computeNodes, computeNode, computeBindings, computePipeline );
  38364. }
  38365. backend.finishCompute( computeNodes );
  38366. //
  38367. nodeFrame.renderId = previousRenderId;
  38368. }
  38369. /**
  38370. * Execute a single or an array of compute nodes.
  38371. *
  38372. * @async
  38373. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  38374. * @return {Promise} A Promise that resolve when the compute has finished.
  38375. */
  38376. async computeAsync( computeNodes ) {
  38377. if ( this._initialized === false ) await this.init();
  38378. this.compute( computeNodes );
  38379. }
  38380. /**
  38381. * Checks if the given feature is supported by the selected backend.
  38382. *
  38383. * @async
  38384. * @param {string} name - The feature's name.
  38385. * @return {Promise<boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  38386. */
  38387. async hasFeatureAsync( name ) {
  38388. if ( this._initialized === false ) await this.init();
  38389. return this.backend.hasFeature( name );
  38390. }
  38391. async resolveTimestampsAsync( type = 'render' ) {
  38392. if ( this._initialized === false ) await this.init();
  38393. return this.backend.resolveTimestampsAsync( type );
  38394. }
  38395. /**
  38396. * Checks if the given feature is supported by the selected backend. If the
  38397. * renderer has not been initialized, this method always returns `false`.
  38398. *
  38399. * @param {string} name - The feature's name.
  38400. * @return {boolean} Whether the feature is supported or not.
  38401. */
  38402. hasFeature( name ) {
  38403. if ( this._initialized === false ) {
  38404. console.warn( 'THREE.Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead.' );
  38405. return false;
  38406. }
  38407. return this.backend.hasFeature( name );
  38408. }
  38409. /**
  38410. * Returns `true` when the renderer has been initialized.
  38411. *
  38412. * @return {boolean} Whether the renderer has been initialized or not.
  38413. */
  38414. hasInitialized() {
  38415. return this._initialized;
  38416. }
  38417. /**
  38418. * Initializes the given textures. Useful for preloading a texture rather than waiting until first render
  38419. * (which can cause noticeable lags due to decode and GPU upload overhead).
  38420. *
  38421. * @async
  38422. * @param {Texture} texture - The texture.
  38423. * @return {Promise} A Promise that resolves when the texture has been initialized.
  38424. */
  38425. async initTextureAsync( texture ) {
  38426. if ( this._initialized === false ) await this.init();
  38427. this._textures.updateTexture( texture );
  38428. }
  38429. /**
  38430. * Initializes the given texture. Useful for preloading a texture rather than waiting until first render
  38431. * (which can cause noticeable lags due to decode and GPU upload overhead).
  38432. *
  38433. * This method can only be used if the renderer has been initialized.
  38434. *
  38435. * @param {Texture} texture - The texture.
  38436. */
  38437. initTexture( texture ) {
  38438. if ( this._initialized === false ) {
  38439. console.warn( 'THREE.Renderer: .initTexture() called before the backend is initialized. Try using .initTextureAsync() instead.' );
  38440. }
  38441. this._textures.updateTexture( texture );
  38442. }
  38443. /**
  38444. * Copies the current bound framebuffer into the given texture.
  38445. *
  38446. * @param {FramebufferTexture} framebufferTexture - The texture.
  38447. * @param {?Vector2|Vector4} [rectangle=null] - A two or four dimensional vector that defines the rectangular portion of the framebuffer that should be copied.
  38448. */
  38449. copyFramebufferToTexture( framebufferTexture, rectangle = null ) {
  38450. if ( rectangle !== null ) {
  38451. if ( rectangle.isVector2 ) {
  38452. rectangle = _vector4.set( rectangle.x, rectangle.y, framebufferTexture.image.width, framebufferTexture.image.height ).floor();
  38453. } else if ( rectangle.isVector4 ) {
  38454. rectangle = _vector4.copy( rectangle ).floor();
  38455. } else {
  38456. console.error( 'THREE.Renderer.copyFramebufferToTexture: Invalid rectangle.' );
  38457. return;
  38458. }
  38459. } else {
  38460. rectangle = _vector4.set( 0, 0, framebufferTexture.image.width, framebufferTexture.image.height );
  38461. }
  38462. //
  38463. let renderContext = this._currentRenderContext;
  38464. let renderTarget;
  38465. if ( renderContext !== null ) {
  38466. renderTarget = renderContext.renderTarget;
  38467. } else {
  38468. renderTarget = this._renderTarget || this._getFrameBufferTarget();
  38469. if ( renderTarget !== null ) {
  38470. this._textures.updateRenderTarget( renderTarget );
  38471. renderContext = this._textures.get( renderTarget );
  38472. }
  38473. }
  38474. //
  38475. this._textures.updateTexture( framebufferTexture, { renderTarget } );
  38476. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext, rectangle );
  38477. }
  38478. /**
  38479. * Copies data of the given source texture into a destination texture.
  38480. *
  38481. * @param {Texture} srcTexture - The source texture.
  38482. * @param {Texture} dstTexture - The destination texture.
  38483. * @param {Box2|Box3} [srcRegion=null] - A bounding box which describes the source region. Can be two or three-dimensional.
  38484. * @param {Vector2|Vector3} [dstPosition=null] - A vector that represents the origin of the destination region. Can be two or three-dimensional.
  38485. * @param {number} [srcLevel=0] - The source mip level to copy from.
  38486. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  38487. */
  38488. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  38489. this._textures.updateTexture( srcTexture );
  38490. this._textures.updateTexture( dstTexture );
  38491. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, srcLevel, dstLevel );
  38492. }
  38493. /**
  38494. * Reads pixel data from the given render target.
  38495. *
  38496. * @async
  38497. * @param {RenderTarget} renderTarget - The render target to read from.
  38498. * @param {number} x - The `x` coordinate of the copy region's origin.
  38499. * @param {number} y - The `y` coordinate of the copy region's origin.
  38500. * @param {number} width - The width of the copy region.
  38501. * @param {number} height - The height of the copy region.
  38502. * @param {number} [textureIndex=0] - The texture index of a MRT render target.
  38503. * @param {number} [faceIndex=0] - The active cube face index.
  38504. * @return {Promise<TypedArray>} A Promise that resolves when the read has been finished. The resolve provides the read data as a typed array.
  38505. */
  38506. async readRenderTargetPixelsAsync( renderTarget, x, y, width, height, textureIndex = 0, faceIndex = 0 ) {
  38507. return this.backend.copyTextureToBuffer( renderTarget.textures[ textureIndex ], x, y, width, height, faceIndex );
  38508. }
  38509. /**
  38510. * Analyzes the given 3D object's hierarchy and builds render lists from the
  38511. * processed hierarchy.
  38512. *
  38513. * @param {Object3D} object - The 3D object to process (usually a scene).
  38514. * @param {Camera} camera - The camera the object is rendered with.
  38515. * @param {number} groupOrder - The group order is derived from the `renderOrder` of groups and is used to group 3D objects within groups.
  38516. * @param {RenderList} renderList - The current render list.
  38517. * @param {ClippingContext} clippingContext - The current clipping context.
  38518. */
  38519. _projectObject( object, camera, groupOrder, renderList, clippingContext ) {
  38520. if ( object.visible === false ) return;
  38521. const visible = object.layers.test( camera.layers );
  38522. if ( visible ) {
  38523. if ( object.isGroup ) {
  38524. groupOrder = object.renderOrder;
  38525. if ( object.isClippingGroup && object.enabled ) clippingContext = clippingContext.getGroupContext( object );
  38526. } else if ( object.isLOD ) {
  38527. if ( object.autoUpdate === true ) object.update( camera );
  38528. } else if ( object.isLight ) {
  38529. renderList.pushLight( object );
  38530. } else if ( object.isSprite ) {
  38531. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  38532. if ( ! object.frustumCulled || frustum.intersectsSprite( object, camera ) ) {
  38533. if ( this.sortObjects === true ) {
  38534. _vector4.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  38535. }
  38536. const { geometry, material } = object;
  38537. if ( material.visible ) {
  38538. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  38539. }
  38540. }
  38541. } else if ( object.isLineLoop ) {
  38542. console.error( 'THREE.Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  38543. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  38544. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  38545. if ( ! object.frustumCulled || frustum.intersectsObject( object, camera ) ) {
  38546. const { geometry, material } = object;
  38547. if ( this.sortObjects === true ) {
  38548. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  38549. _vector4
  38550. .copy( geometry.boundingSphere.center )
  38551. .applyMatrix4( object.matrixWorld )
  38552. .applyMatrix4( _projScreenMatrix );
  38553. }
  38554. if ( Array.isArray( material ) ) {
  38555. const groups = geometry.groups;
  38556. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  38557. const group = groups[ i ];
  38558. const groupMaterial = material[ group.materialIndex ];
  38559. if ( groupMaterial && groupMaterial.visible ) {
  38560. renderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group, clippingContext );
  38561. }
  38562. }
  38563. } else if ( material.visible ) {
  38564. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  38565. }
  38566. }
  38567. }
  38568. }
  38569. if ( object.isBundleGroup === true && this.backend.beginBundle !== undefined ) {
  38570. const baseRenderList = renderList;
  38571. // replace render list
  38572. renderList = this._renderLists.get( object, camera );
  38573. renderList.begin();
  38574. baseRenderList.pushBundle( {
  38575. bundleGroup: object,
  38576. camera,
  38577. renderList,
  38578. } );
  38579. renderList.finish();
  38580. }
  38581. const children = object.children;
  38582. for ( let i = 0, l = children.length; i < l; i ++ ) {
  38583. this._projectObject( children[ i ], camera, groupOrder, renderList, clippingContext );
  38584. }
  38585. }
  38586. /**
  38587. * Renders the given render bundles.
  38588. *
  38589. * @private
  38590. * @param {Array<Object>} bundles - Array with render bundle data.
  38591. * @param {Scene} sceneRef - The scene the render bundles belong to.
  38592. * @param {LightsNode} lightsNode - The current lights node.
  38593. */
  38594. _renderBundles( bundles, sceneRef, lightsNode ) {
  38595. for ( const bundle of bundles ) {
  38596. this._renderBundle( bundle, sceneRef, lightsNode );
  38597. }
  38598. }
  38599. /**
  38600. * Renders the transparent objects from the given render lists.
  38601. *
  38602. * @private
  38603. * @param {Array<Object>} renderList - The transparent render list.
  38604. * @param {Array<Object>} doublePassList - The list of transparent objects which require a double pass (e.g. because of transmission).
  38605. * @param {Camera} camera - The camera the render list should be rendered with.
  38606. * @param {Scene} scene - The scene the render list belongs to.
  38607. * @param {LightsNode} lightsNode - The current lights node.
  38608. */
  38609. _renderTransparents( renderList, doublePassList, camera, scene, lightsNode ) {
  38610. if ( doublePassList.length > 0 ) {
  38611. // render back side
  38612. for ( const { material } of doublePassList ) {
  38613. material.side = BackSide;
  38614. }
  38615. this._renderObjects( doublePassList, camera, scene, lightsNode, 'backSide' );
  38616. // render front side
  38617. for ( const { material } of doublePassList ) {
  38618. material.side = FrontSide;
  38619. }
  38620. this._renderObjects( renderList, camera, scene, lightsNode );
  38621. // restore
  38622. for ( const { material } of doublePassList ) {
  38623. material.side = DoubleSide;
  38624. }
  38625. } else {
  38626. this._renderObjects( renderList, camera, scene, lightsNode );
  38627. }
  38628. }
  38629. /**
  38630. * Renders the objects from the given render list.
  38631. *
  38632. * @private
  38633. * @param {Array<Object>} renderList - The render list.
  38634. * @param {Camera} camera - The camera the render list should be rendered with.
  38635. * @param {Scene} scene - The scene the render list belongs to.
  38636. * @param {LightsNode} lightsNode - The current lights node.
  38637. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  38638. */
  38639. _renderObjects( renderList, camera, scene, lightsNode, passId = null ) {
  38640. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  38641. const { object, geometry, material, group, clippingContext } = renderList[ i ];
  38642. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode, clippingContext, passId );
  38643. }
  38644. }
  38645. /**
  38646. * This method represents the default render object function that manages the render lifecycle
  38647. * of the object.
  38648. *
  38649. * @param {Object3D} object - The 3D object.
  38650. * @param {Scene} scene - The scene the 3D object belongs to.
  38651. * @param {Camera} camera - The camera the object should be rendered with.
  38652. * @param {BufferGeometry} geometry - The object's geometry.
  38653. * @param {Material} material - The object's material.
  38654. * @param {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  38655. * @param {LightsNode} lightsNode - The current lights node.
  38656. * @param {?ClippingContext} clippingContext - The clipping context.
  38657. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  38658. */
  38659. renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext = null, passId = null ) {
  38660. let overridePositionNode;
  38661. let overrideColorNode;
  38662. let overrideDepthNode;
  38663. //
  38664. object.onBeforeRender( this, scene, camera, geometry, material, group );
  38665. //
  38666. if ( material.allowOverride === true && scene.overrideMaterial !== null ) {
  38667. const overrideMaterial = scene.overrideMaterial;
  38668. if ( material.positionNode && material.positionNode.isNode ) {
  38669. overridePositionNode = overrideMaterial.positionNode;
  38670. overrideMaterial.positionNode = material.positionNode;
  38671. }
  38672. overrideMaterial.alphaTest = material.alphaTest;
  38673. overrideMaterial.alphaMap = material.alphaMap;
  38674. overrideMaterial.transparent = material.transparent || material.transmission > 0;
  38675. if ( overrideMaterial.isShadowPassMaterial ) {
  38676. overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide;
  38677. if ( material.depthNode && material.depthNode.isNode ) {
  38678. overrideDepthNode = overrideMaterial.depthNode;
  38679. overrideMaterial.depthNode = material.depthNode;
  38680. }
  38681. if ( material.castShadowNode && material.castShadowNode.isNode ) {
  38682. overrideColorNode = overrideMaterial.colorNode;
  38683. overrideMaterial.colorNode = material.castShadowNode;
  38684. }
  38685. if ( material.castShadowPositionNode && material.castShadowPositionNode.isNode ) {
  38686. overridePositionNode = overrideMaterial.positionNode;
  38687. overrideMaterial.positionNode = material.castShadowPositionNode;
  38688. }
  38689. }
  38690. material = overrideMaterial;
  38691. }
  38692. //
  38693. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  38694. material.side = BackSide;
  38695. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, 'backSide' ); // create backSide pass id
  38696. material.side = FrontSide;
  38697. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId ); // use default pass id
  38698. material.side = DoubleSide;
  38699. } else {
  38700. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId );
  38701. }
  38702. //
  38703. if ( overridePositionNode !== undefined ) {
  38704. scene.overrideMaterial.positionNode = overridePositionNode;
  38705. }
  38706. if ( overrideDepthNode !== undefined ) {
  38707. scene.overrideMaterial.depthNode = overrideDepthNode;
  38708. }
  38709. if ( overrideColorNode !== undefined ) {
  38710. scene.overrideMaterial.colorNode = overrideColorNode;
  38711. }
  38712. //
  38713. object.onAfterRender( this, scene, camera, geometry, material, group );
  38714. }
  38715. /**
  38716. * This method represents the default `_handleObjectFunction` implementation which creates
  38717. * a render object from the given data and performs the draw command with the selected backend.
  38718. *
  38719. * @private
  38720. * @param {Object3D} object - The 3D object.
  38721. * @param {Material} material - The object's material.
  38722. * @param {Scene} scene - The scene the 3D object belongs to.
  38723. * @param {Camera} camera - The camera the object should be rendered with.
  38724. * @param {LightsNode} lightsNode - The current lights node.
  38725. * @param {?{start: number, count: number}} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  38726. * @param {ClippingContext} clippingContext - The clipping context.
  38727. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  38728. */
  38729. _renderObjectDirect( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  38730. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  38731. renderObject.drawRange = object.geometry.drawRange;
  38732. renderObject.group = group;
  38733. //
  38734. const needsRefresh = this._nodes.needsRefresh( renderObject );
  38735. if ( needsRefresh ) {
  38736. this._nodes.updateBefore( renderObject );
  38737. this._geometries.updateForRender( renderObject );
  38738. this._nodes.updateForRender( renderObject );
  38739. this._bindings.updateForRender( renderObject );
  38740. }
  38741. this._pipelines.updateForRender( renderObject );
  38742. //
  38743. if ( this._currentRenderBundle !== null ) {
  38744. const renderBundleData = this.backend.get( this._currentRenderBundle );
  38745. renderBundleData.renderObjects.push( renderObject );
  38746. renderObject.bundle = this._currentRenderBundle.bundleGroup;
  38747. }
  38748. this.backend.draw( renderObject, this.info );
  38749. if ( needsRefresh ) this._nodes.updateAfter( renderObject );
  38750. }
  38751. /**
  38752. * A different implementation for `_handleObjectFunction` which only makes sure the object is ready for rendering.
  38753. * Used in `compileAsync()`.
  38754. *
  38755. * @private
  38756. * @param {Object3D} object - The 3D object.
  38757. * @param {Material} material - The object's material.
  38758. * @param {Scene} scene - The scene the 3D object belongs to.
  38759. * @param {Camera} camera - The camera the object should be rendered with.
  38760. * @param {LightsNode} lightsNode - The current lights node.
  38761. * @param {?{start: number, count: number}} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  38762. * @param {ClippingContext} clippingContext - The clipping context.
  38763. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  38764. */
  38765. _createObjectPipeline( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  38766. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  38767. renderObject.drawRange = object.geometry.drawRange;
  38768. renderObject.group = group;
  38769. //
  38770. this._nodes.updateBefore( renderObject );
  38771. this._geometries.updateForRender( renderObject );
  38772. this._nodes.updateForRender( renderObject );
  38773. this._bindings.updateForRender( renderObject );
  38774. this._pipelines.getForRender( renderObject, this._compilationPromises );
  38775. this._nodes.updateAfter( renderObject );
  38776. }
  38777. /**
  38778. * Alias for `compileAsync()`.
  38779. *
  38780. * @method
  38781. * @param {Object3D} scene - The scene or 3D object to precompile.
  38782. * @param {Camera} camera - The camera that is used to render the scene.
  38783. * @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.
  38784. * @return {function(Object3D, Camera, ?Scene): Promise|undefined} A Promise that resolves when the compile has been finished.
  38785. */
  38786. get compile() {
  38787. return this.compileAsync;
  38788. }
  38789. }
  38790. /**
  38791. * A binding represents the connection between a resource (like a texture, sampler
  38792. * or uniform buffer) and the resource definition in a shader stage.
  38793. *
  38794. * This module is an abstract base class for all concrete bindings types.
  38795. *
  38796. * @abstract
  38797. * @private
  38798. */
  38799. class Binding {
  38800. /**
  38801. * Constructs a new binding.
  38802. *
  38803. * @param {string} [name=''] - The binding's name.
  38804. */
  38805. constructor( name = '' ) {
  38806. /**
  38807. * The binding's name.
  38808. *
  38809. * @type {string}
  38810. */
  38811. this.name = name;
  38812. /**
  38813. * A bitmask that defines in what shader stages the
  38814. * binding's resource is accessible.
  38815. *
  38816. * @type {number}
  38817. */
  38818. this.visibility = 0;
  38819. }
  38820. /**
  38821. * Makes sure binding's resource is visible for the given shader stage.
  38822. *
  38823. * @param {number} visibility - The shader stage.
  38824. */
  38825. setVisibility( visibility ) {
  38826. this.visibility |= visibility;
  38827. }
  38828. /**
  38829. * Clones the binding.
  38830. *
  38831. * @return {Binding} The cloned binding.
  38832. */
  38833. clone() {
  38834. return Object.assign( new this.constructor(), this );
  38835. }
  38836. }
  38837. /**
  38838. * This function is usually called with the length in bytes of an array buffer.
  38839. * It returns an padded value which ensure chunk size alignment according to STD140 layout.
  38840. *
  38841. * @function
  38842. * @param {number} floatLength - The buffer length.
  38843. * @return {number} The padded length.
  38844. */
  38845. function getFloatLength( floatLength ) {
  38846. // ensure chunk size alignment (STD140 layout)
  38847. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  38848. }
  38849. /**
  38850. * Represents a buffer binding type.
  38851. *
  38852. * @private
  38853. * @abstract
  38854. * @augments Binding
  38855. */
  38856. class Buffer extends Binding {
  38857. /**
  38858. * Constructs a new buffer.
  38859. *
  38860. * @param {string} name - The buffer's name.
  38861. * @param {TypedArray} [buffer=null] - The buffer.
  38862. */
  38863. constructor( name, buffer = null ) {
  38864. super( name );
  38865. /**
  38866. * This flag can be used for type testing.
  38867. *
  38868. * @type {boolean}
  38869. * @readonly
  38870. * @default true
  38871. */
  38872. this.isBuffer = true;
  38873. /**
  38874. * The bytes per element.
  38875. *
  38876. * @type {number}
  38877. */
  38878. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  38879. /**
  38880. * A reference to the internal buffer.
  38881. *
  38882. * @private
  38883. * @type {TypedArray}
  38884. */
  38885. this._buffer = buffer;
  38886. }
  38887. /**
  38888. * The buffer's byte length.
  38889. *
  38890. * @type {number}
  38891. * @readonly
  38892. */
  38893. get byteLength() {
  38894. return getFloatLength( this._buffer.byteLength );
  38895. }
  38896. /**
  38897. * A reference to the internal buffer.
  38898. *
  38899. * @type {Float32Array}
  38900. * @readonly
  38901. */
  38902. get buffer() {
  38903. return this._buffer;
  38904. }
  38905. /**
  38906. * Updates the binding.
  38907. *
  38908. * @return {boolean} Whether the buffer has been updated and must be
  38909. * uploaded to the GPU.
  38910. */
  38911. update() {
  38912. return true;
  38913. }
  38914. }
  38915. /**
  38916. * Represents a uniform buffer binding type.
  38917. *
  38918. * @private
  38919. * @augments Buffer
  38920. */
  38921. class UniformBuffer extends Buffer {
  38922. /**
  38923. * Constructs a new uniform buffer.
  38924. *
  38925. * @param {string} name - The buffer's name.
  38926. * @param {TypedArray} [buffer=null] - The buffer.
  38927. */
  38928. constructor( name, buffer = null ) {
  38929. super( name, buffer );
  38930. /**
  38931. * This flag can be used for type testing.
  38932. *
  38933. * @type {boolean}
  38934. * @readonly
  38935. * @default true
  38936. */
  38937. this.isUniformBuffer = true;
  38938. }
  38939. }
  38940. let _id$4 = 0;
  38941. /**
  38942. * A special form of uniform buffer binding type.
  38943. * It's buffer value is managed by a node object.
  38944. *
  38945. * @private
  38946. * @augments UniformBuffer
  38947. */
  38948. class NodeUniformBuffer extends UniformBuffer {
  38949. /**
  38950. * Constructs a new node-based uniform buffer.
  38951. *
  38952. * @param {BufferNode} nodeUniform - The uniform buffer node.
  38953. * @param {UniformGroupNode} groupNode - The uniform group node.
  38954. */
  38955. constructor( nodeUniform, groupNode ) {
  38956. super( 'UniformBuffer_' + _id$4 ++, nodeUniform ? nodeUniform.value : null );
  38957. /**
  38958. * The uniform buffer node.
  38959. *
  38960. * @type {BufferNode}
  38961. */
  38962. this.nodeUniform = nodeUniform;
  38963. /**
  38964. * The uniform group node.
  38965. *
  38966. * @type {UniformGroupNode}
  38967. */
  38968. this.groupNode = groupNode;
  38969. }
  38970. /**
  38971. * The uniform buffer.
  38972. *
  38973. * @type {Float32Array}
  38974. */
  38975. get buffer() {
  38976. return this.nodeUniform.value;
  38977. }
  38978. }
  38979. /**
  38980. * This class represents a uniform buffer binding but with
  38981. * an API that allows to maintain individual uniform objects.
  38982. *
  38983. * @private
  38984. * @augments UniformBuffer
  38985. */
  38986. class UniformsGroup extends UniformBuffer {
  38987. /**
  38988. * Constructs a new uniforms group.
  38989. *
  38990. * @param {string} name - The group's name.
  38991. */
  38992. constructor( name ) {
  38993. super( name );
  38994. /**
  38995. * This flag can be used for type testing.
  38996. *
  38997. * @type {boolean}
  38998. * @readonly
  38999. * @default true
  39000. */
  39001. this.isUniformsGroup = true;
  39002. /**
  39003. * An array with the raw uniform values.
  39004. *
  39005. * @private
  39006. * @type {?Array<number>}
  39007. * @default null
  39008. */
  39009. this._values = null;
  39010. /**
  39011. * An array of uniform objects.
  39012. *
  39013. * The order of uniforms in this array must match the order of uniforms in the shader.
  39014. *
  39015. * @type {Array<Uniform>}
  39016. */
  39017. this.uniforms = [];
  39018. }
  39019. /**
  39020. * Adds a uniform to this group.
  39021. *
  39022. * @param {Uniform} uniform - The uniform to add.
  39023. * @return {UniformsGroup} A reference to this group.
  39024. */
  39025. addUniform( uniform ) {
  39026. this.uniforms.push( uniform );
  39027. return this;
  39028. }
  39029. /**
  39030. * Removes a uniform from this group.
  39031. *
  39032. * @param {Uniform} uniform - The uniform to remove.
  39033. * @return {UniformsGroup} A reference to this group.
  39034. */
  39035. removeUniform( uniform ) {
  39036. const index = this.uniforms.indexOf( uniform );
  39037. if ( index !== -1 ) {
  39038. this.uniforms.splice( index, 1 );
  39039. }
  39040. return this;
  39041. }
  39042. /**
  39043. * An array with the raw uniform values.
  39044. *
  39045. * @type {Array<number>}
  39046. */
  39047. get values() {
  39048. if ( this._values === null ) {
  39049. this._values = Array.from( this.buffer );
  39050. }
  39051. return this._values;
  39052. }
  39053. /**
  39054. * A Float32 array buffer with the uniform values.
  39055. *
  39056. * @type {Float32Array}
  39057. */
  39058. get buffer() {
  39059. let buffer = this._buffer;
  39060. if ( buffer === null ) {
  39061. const byteLength = this.byteLength;
  39062. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  39063. this._buffer = buffer;
  39064. }
  39065. return buffer;
  39066. }
  39067. /**
  39068. * The byte length of the buffer with correct buffer alignment.
  39069. *
  39070. * @type {number}
  39071. */
  39072. get byteLength() {
  39073. const bytesPerElement = this.bytesPerElement;
  39074. let offset = 0; // global buffer offset in bytes
  39075. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  39076. const uniform = this.uniforms[ i ];
  39077. const boundary = uniform.boundary;
  39078. const itemSize = uniform.itemSize * bytesPerElement; // size of the uniform in bytes
  39079. const chunkOffset = offset % GPU_CHUNK_BYTES; // offset in the current chunk
  39080. const chunkPadding = chunkOffset % boundary; // required padding to match boundary
  39081. const chunkStart = chunkOffset + chunkPadding; // start position in the current chunk for the data
  39082. offset += chunkPadding;
  39083. // Check for chunk overflow
  39084. if ( chunkStart !== 0 && ( GPU_CHUNK_BYTES - chunkStart ) < itemSize ) {
  39085. // Add padding to the end of the chunk
  39086. offset += ( GPU_CHUNK_BYTES - chunkStart );
  39087. }
  39088. uniform.offset = offset / bytesPerElement;
  39089. offset += itemSize;
  39090. }
  39091. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  39092. }
  39093. /**
  39094. * Updates this group by updating each uniform object of
  39095. * the internal uniform list. The uniform objects check if their
  39096. * values has actually changed so this method only returns
  39097. * `true` if there is a real value change.
  39098. *
  39099. * @return {boolean} Whether the uniforms have been updated and
  39100. * must be uploaded to the GPU.
  39101. */
  39102. update() {
  39103. let updated = false;
  39104. for ( const uniform of this.uniforms ) {
  39105. if ( this.updateByType( uniform ) === true ) {
  39106. updated = true;
  39107. }
  39108. }
  39109. return updated;
  39110. }
  39111. /**
  39112. * Updates a given uniform by calling an update method matching
  39113. * the uniforms type.
  39114. *
  39115. * @param {Uniform} uniform - The uniform to update.
  39116. * @return {boolean} Whether the uniform has been updated or not.
  39117. */
  39118. updateByType( uniform ) {
  39119. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  39120. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  39121. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  39122. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  39123. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  39124. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  39125. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  39126. console.error( 'THREE.WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  39127. }
  39128. /**
  39129. * Updates a given Number uniform.
  39130. *
  39131. * @param {NumberUniform} uniform - The Number uniform.
  39132. * @return {boolean} Whether the uniform has been updated or not.
  39133. */
  39134. updateNumber( uniform ) {
  39135. let updated = false;
  39136. const a = this.values;
  39137. const v = uniform.getValue();
  39138. const offset = uniform.offset;
  39139. const type = uniform.getType();
  39140. if ( a[ offset ] !== v ) {
  39141. const b = this._getBufferForType( type );
  39142. b[ offset ] = a[ offset ] = v;
  39143. updated = true;
  39144. }
  39145. return updated;
  39146. }
  39147. /**
  39148. * Updates a given Vector2 uniform.
  39149. *
  39150. * @param {Vector2Uniform} uniform - The Vector2 uniform.
  39151. * @return {boolean} Whether the uniform has been updated or not.
  39152. */
  39153. updateVector2( uniform ) {
  39154. let updated = false;
  39155. const a = this.values;
  39156. const v = uniform.getValue();
  39157. const offset = uniform.offset;
  39158. const type = uniform.getType();
  39159. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  39160. const b = this._getBufferForType( type );
  39161. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  39162. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  39163. updated = true;
  39164. }
  39165. return updated;
  39166. }
  39167. /**
  39168. * Updates a given Vector3 uniform.
  39169. *
  39170. * @param {Vector3Uniform} uniform - The Vector3 uniform.
  39171. * @return {boolean} Whether the uniform has been updated or not.
  39172. */
  39173. updateVector3( uniform ) {
  39174. let updated = false;
  39175. const a = this.values;
  39176. const v = uniform.getValue();
  39177. const offset = uniform.offset;
  39178. const type = uniform.getType();
  39179. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  39180. const b = this._getBufferForType( type );
  39181. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  39182. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  39183. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  39184. updated = true;
  39185. }
  39186. return updated;
  39187. }
  39188. /**
  39189. * Updates a given Vector4 uniform.
  39190. *
  39191. * @param {Vector4Uniform} uniform - The Vector4 uniform.
  39192. * @return {boolean} Whether the uniform has been updated or not.
  39193. */
  39194. updateVector4( uniform ) {
  39195. let updated = false;
  39196. const a = this.values;
  39197. const v = uniform.getValue();
  39198. const offset = uniform.offset;
  39199. const type = uniform.getType();
  39200. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 4 ] !== v.w ) {
  39201. const b = this._getBufferForType( type );
  39202. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  39203. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  39204. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  39205. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  39206. updated = true;
  39207. }
  39208. return updated;
  39209. }
  39210. /**
  39211. * Updates a given Color uniform.
  39212. *
  39213. * @param {ColorUniform} uniform - The Color uniform.
  39214. * @return {boolean} Whether the uniform has been updated or not.
  39215. */
  39216. updateColor( uniform ) {
  39217. let updated = false;
  39218. const a = this.values;
  39219. const c = uniform.getValue();
  39220. const offset = uniform.offset;
  39221. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  39222. const b = this.buffer;
  39223. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  39224. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  39225. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  39226. updated = true;
  39227. }
  39228. return updated;
  39229. }
  39230. /**
  39231. * Updates a given Matrix3 uniform.
  39232. *
  39233. * @param {Matrix3Uniform} uniform - The Matrix3 uniform.
  39234. * @return {boolean} Whether the uniform has been updated or not.
  39235. */
  39236. updateMatrix3( uniform ) {
  39237. let updated = false;
  39238. const a = this.values;
  39239. const e = uniform.getValue().elements;
  39240. const offset = uniform.offset;
  39241. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  39242. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  39243. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  39244. const b = this.buffer;
  39245. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  39246. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  39247. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  39248. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  39249. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  39250. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  39251. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  39252. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  39253. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  39254. updated = true;
  39255. }
  39256. return updated;
  39257. }
  39258. /**
  39259. * Updates a given Matrix4 uniform.
  39260. *
  39261. * @param {Matrix4Uniform} uniform - The Matrix4 uniform.
  39262. * @return {boolean} Whether the uniform has been updated or not.
  39263. */
  39264. updateMatrix4( uniform ) {
  39265. let updated = false;
  39266. const a = this.values;
  39267. const e = uniform.getValue().elements;
  39268. const offset = uniform.offset;
  39269. if ( arraysEqual( a, e, offset ) === false ) {
  39270. const b = this.buffer;
  39271. b.set( e, offset );
  39272. setArray( a, e, offset );
  39273. updated = true;
  39274. }
  39275. return updated;
  39276. }
  39277. /**
  39278. * Returns a typed array that matches the given data type.
  39279. *
  39280. * @param {string} type - The data type.
  39281. * @return {TypedArray} The typed array.
  39282. */
  39283. _getBufferForType( type ) {
  39284. if ( type === 'int' || type === 'ivec2' || type === 'ivec3' || type === 'ivec4' ) return new Int32Array( this.buffer.buffer );
  39285. if ( type === 'uint' || type === 'uvec2' || type === 'uvec3' || type === 'uvec4' ) return new Uint32Array( this.buffer.buffer );
  39286. return this.buffer;
  39287. }
  39288. }
  39289. /**
  39290. * Sets the values of the second array to the first array.
  39291. *
  39292. * @private
  39293. * @param {TypedArray} a - The first array.
  39294. * @param {TypedArray} b - The second array.
  39295. * @param {number} offset - An index offset for the first array.
  39296. */
  39297. function setArray( a, b, offset ) {
  39298. for ( let i = 0, l = b.length; i < l; i ++ ) {
  39299. a[ offset + i ] = b[ i ];
  39300. }
  39301. }
  39302. /**
  39303. * Returns `true` if the given arrays are equal.
  39304. *
  39305. * @private
  39306. * @param {TypedArray} a - The first array.
  39307. * @param {TypedArray} b - The second array.
  39308. * @param {number} offset - An index offset for the first array.
  39309. * @return {boolean} Whether the given arrays are equal or not.
  39310. */
  39311. function arraysEqual( a, b, offset ) {
  39312. for ( let i = 0, l = b.length; i < l; i ++ ) {
  39313. if ( a[ offset + i ] !== b[ i ] ) return false;
  39314. }
  39315. return true;
  39316. }
  39317. let _id$3 = 0;
  39318. /**
  39319. * A special form of uniforms group that represents
  39320. * the individual uniforms as node-based uniforms.
  39321. *
  39322. * @private
  39323. * @augments UniformsGroup
  39324. */
  39325. class NodeUniformsGroup extends UniformsGroup {
  39326. /**
  39327. * Constructs a new node-based uniforms group.
  39328. *
  39329. * @param {string} name - The group's name.
  39330. * @param {UniformGroupNode} groupNode - The uniform group node.
  39331. */
  39332. constructor( name, groupNode ) {
  39333. super( name );
  39334. /**
  39335. * The group's ID.
  39336. *
  39337. * @type {number}
  39338. */
  39339. this.id = _id$3 ++;
  39340. /**
  39341. * The uniform group node.
  39342. *
  39343. * @type {UniformGroupNode}
  39344. */
  39345. this.groupNode = groupNode;
  39346. /**
  39347. * This flag can be used for type testing.
  39348. *
  39349. * @type {boolean}
  39350. * @readonly
  39351. * @default true
  39352. */
  39353. this.isNodeUniformsGroup = true;
  39354. }
  39355. }
  39356. let _id$2 = 0;
  39357. /**
  39358. * Represents a sampled texture binding type.
  39359. *
  39360. * @private
  39361. * @augments Binding
  39362. */
  39363. class SampledTexture extends Binding {
  39364. /**
  39365. * Constructs a new sampled texture.
  39366. *
  39367. * @param {string} name - The sampled texture's name.
  39368. * @param {?Texture} texture - The texture this binding is referring to.
  39369. */
  39370. constructor( name, texture ) {
  39371. super( name );
  39372. /**
  39373. * This identifier.
  39374. *
  39375. * @type {number}
  39376. */
  39377. this.id = _id$2 ++;
  39378. /**
  39379. * The texture this binding is referring to.
  39380. *
  39381. * @type {?Texture}
  39382. */
  39383. this.texture = texture;
  39384. /**
  39385. * The binding's version.
  39386. *
  39387. * @type {number}
  39388. */
  39389. this.version = texture ? texture.version : 0;
  39390. /**
  39391. * Whether the texture is a storage texture or not.
  39392. *
  39393. * @type {boolean}
  39394. * @default false
  39395. */
  39396. this.store = false;
  39397. /**
  39398. * The binding's generation which is an additional version
  39399. * qualifier.
  39400. *
  39401. * @type {?number}
  39402. * @default null
  39403. */
  39404. this.generation = null;
  39405. /**
  39406. * This flag can be used for type testing.
  39407. *
  39408. * @type {boolean}
  39409. * @readonly
  39410. * @default true
  39411. */
  39412. this.isSampledTexture = true;
  39413. }
  39414. /**
  39415. * Returns `true` whether this binding requires an update for the
  39416. * given generation.
  39417. *
  39418. * @param {number} generation - The generation.
  39419. * @return {boolean} Whether an update is required or not.
  39420. */
  39421. needsBindingsUpdate( generation ) {
  39422. const { texture } = this;
  39423. if ( generation !== this.generation ) {
  39424. this.generation = generation;
  39425. return true;
  39426. }
  39427. return texture.isVideoTexture;
  39428. }
  39429. /**
  39430. * Updates the binding.
  39431. *
  39432. * @return {boolean} Whether the texture has been updated and must be
  39433. * uploaded to the GPU.
  39434. */
  39435. update() {
  39436. const { texture, version } = this;
  39437. if ( version !== texture.version ) {
  39438. this.version = texture.version;
  39439. return true;
  39440. }
  39441. return false;
  39442. }
  39443. }
  39444. /**
  39445. * A special form of sampled texture binding type.
  39446. * It's texture value is managed by a node object.
  39447. *
  39448. * @private
  39449. * @augments SampledTexture
  39450. */
  39451. class NodeSampledTexture extends SampledTexture {
  39452. /**
  39453. * Constructs a new node-based sampled texture.
  39454. *
  39455. * @param {string} name - The textures's name.
  39456. * @param {TextureNode} textureNode - The texture node.
  39457. * @param {UniformGroupNode} groupNode - The uniform group node.
  39458. * @param {?string} [access=null] - The access type.
  39459. */
  39460. constructor( name, textureNode, groupNode, access = null ) {
  39461. super( name, textureNode ? textureNode.value : null );
  39462. /**
  39463. * The texture node.
  39464. *
  39465. * @type {TextureNode}
  39466. */
  39467. this.textureNode = textureNode;
  39468. /**
  39469. * The uniform group node.
  39470. *
  39471. * @type {UniformGroupNode}
  39472. */
  39473. this.groupNode = groupNode;
  39474. /**
  39475. * The access type.
  39476. *
  39477. * @type {?string}
  39478. * @default null
  39479. */
  39480. this.access = access;
  39481. }
  39482. /**
  39483. * Overwrites the default to additionally check if the node value has changed.
  39484. *
  39485. * @param {number} generation - The generation.
  39486. * @return {boolean} Whether an update is required or not.
  39487. */
  39488. needsBindingsUpdate( generation ) {
  39489. return this.textureNode.value !== this.texture || super.needsBindingsUpdate( generation );
  39490. }
  39491. /**
  39492. * Updates the binding.
  39493. *
  39494. * @return {boolean} Whether the texture has been updated and must be
  39495. * uploaded to the GPU.
  39496. */
  39497. update() {
  39498. const { textureNode } = this;
  39499. if ( this.texture !== textureNode.value ) {
  39500. this.texture = textureNode.value;
  39501. return true;
  39502. }
  39503. return super.update();
  39504. }
  39505. }
  39506. /**
  39507. * A special form of sampled cube texture binding type.
  39508. * It's texture value is managed by a node object.
  39509. *
  39510. * @private
  39511. * @augments NodeSampledTexture
  39512. */
  39513. class NodeSampledCubeTexture extends NodeSampledTexture {
  39514. /**
  39515. * Constructs a new node-based sampled cube texture.
  39516. *
  39517. * @param {string} name - The textures's name.
  39518. * @param {TextureNode} textureNode - The texture node.
  39519. * @param {UniformGroupNode} groupNode - The uniform group node.
  39520. * @param {?string} [access=null] - The access type.
  39521. */
  39522. constructor( name, textureNode, groupNode, access = null ) {
  39523. super( name, textureNode, groupNode, access );
  39524. /**
  39525. * This flag can be used for type testing.
  39526. *
  39527. * @type {boolean}
  39528. * @readonly
  39529. * @default true
  39530. */
  39531. this.isSampledCubeTexture = true;
  39532. }
  39533. }
  39534. /**
  39535. * A special form of sampled 3D texture binding type.
  39536. * It's texture value is managed by a node object.
  39537. *
  39538. * @private
  39539. * @augments NodeSampledTexture
  39540. */
  39541. class NodeSampledTexture3D extends NodeSampledTexture {
  39542. /**
  39543. * Constructs a new node-based sampled 3D texture.
  39544. *
  39545. * @param {string} name - The textures's name.
  39546. * @param {TextureNode} textureNode - The texture node.
  39547. * @param {UniformGroupNode} groupNode - The uniform group node.
  39548. * @param {?string} [access=null] - The access type.
  39549. */
  39550. constructor( name, textureNode, groupNode, access = null ) {
  39551. super( name, textureNode, groupNode, access );
  39552. /**
  39553. * This flag can be used for type testing.
  39554. *
  39555. * @type {boolean}
  39556. * @readonly
  39557. * @default true
  39558. */
  39559. this.isSampledTexture3D = true;
  39560. }
  39561. }
  39562. const glslMethods = {
  39563. textureDimensions: 'textureSize',
  39564. equals: 'equal'
  39565. };
  39566. const precisionLib = {
  39567. low: 'lowp',
  39568. medium: 'mediump',
  39569. high: 'highp'
  39570. };
  39571. const supports$1 = {
  39572. swizzleAssign: true,
  39573. storageBuffer: false
  39574. };
  39575. const interpolationTypeMap = {
  39576. perspective: 'smooth',
  39577. linear: 'noperspective'
  39578. };
  39579. const interpolationModeMap = {
  39580. 'centroid': 'centroid',
  39581. 'flat first': 'flat',
  39582. 'flat either': 'flat'
  39583. };
  39584. const defaultPrecisions = `
  39585. precision highp float;
  39586. precision highp int;
  39587. precision highp sampler2D;
  39588. precision highp sampler3D;
  39589. precision highp samplerCube;
  39590. precision highp sampler2DArray;
  39591. precision highp usampler2D;
  39592. precision highp usampler3D;
  39593. precision highp usamplerCube;
  39594. precision highp usampler2DArray;
  39595. precision highp isampler2D;
  39596. precision highp isampler3D;
  39597. precision highp isamplerCube;
  39598. precision highp isampler2DArray;
  39599. precision lowp sampler2DShadow;
  39600. precision lowp sampler2DArrayShadow;
  39601. precision lowp samplerCubeShadow;
  39602. `;
  39603. /**
  39604. * A node builder targeting GLSL.
  39605. *
  39606. * This module generates GLSL shader code from node materials and also
  39607. * generates the respective bindings and vertex buffer definitions. These
  39608. * data are later used by the renderer to create render and compute pipelines
  39609. * for render objects.
  39610. *
  39611. * @augments NodeBuilder
  39612. */
  39613. class GLSLNodeBuilder extends NodeBuilder {
  39614. /**
  39615. * Constructs a new GLSL node builder renderer.
  39616. *
  39617. * @param {Object3D} object - The 3D object.
  39618. * @param {Renderer} renderer - The renderer.
  39619. */
  39620. constructor( object, renderer ) {
  39621. super( object, renderer, new GLSLNodeParser() );
  39622. /**
  39623. * A dictionary holds for each shader stage ('vertex', 'fragment', 'compute')
  39624. * another dictionary which manages UBOs per group ('render','frame','object').
  39625. *
  39626. * @type {Object<string,Object<string,NodeUniformsGroup>>}
  39627. */
  39628. this.uniformGroups = {};
  39629. /**
  39630. * An array that holds objects defining the varying and attribute data in
  39631. * context of Transform Feedback.
  39632. *
  39633. * @type {Array<Object<string,AttributeNode|string>>}
  39634. */
  39635. this.transforms = [];
  39636. /**
  39637. * A dictionary that holds for each shader stage a Map of used extensions.
  39638. *
  39639. * @type {Object<string,Map<string,Object>>}
  39640. */
  39641. this.extensions = {};
  39642. /**
  39643. * A dictionary that holds for each shader stage an Array of used builtins.
  39644. *
  39645. * @type {Object<string,Array<string>>}
  39646. */
  39647. this.builtins = { vertex: [], fragment: [], compute: [] };
  39648. }
  39649. /**
  39650. * Checks if the given texture requires a manual conversion to the working color space.
  39651. *
  39652. * @param {Texture} texture - The texture to check.
  39653. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  39654. */
  39655. needsToWorkingColorSpace( texture ) {
  39656. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  39657. }
  39658. /**
  39659. * Returns the native shader method name for a given generic name.
  39660. *
  39661. * @param {string} method - The method name to resolve.
  39662. * @return {string} The resolved GLSL method name.
  39663. */
  39664. getMethod( method ) {
  39665. return glslMethods[ method ] || method;
  39666. }
  39667. /**
  39668. * Returns the output struct name. Not relevant for GLSL.
  39669. *
  39670. * @return {string}
  39671. */
  39672. getOutputStructName() {
  39673. return '';
  39674. }
  39675. /**
  39676. * Builds the given shader node.
  39677. *
  39678. * @param {ShaderNodeInternal} shaderNode - The shader node.
  39679. * @return {string} The GLSL function code.
  39680. */
  39681. buildFunctionCode( shaderNode ) {
  39682. const layout = shaderNode.layout;
  39683. const flowData = this.flowShaderNode( shaderNode );
  39684. const parameters = [];
  39685. for ( const input of layout.inputs ) {
  39686. parameters.push( this.getType( input.type ) + ' ' + input.name );
  39687. }
  39688. //
  39689. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  39690. ${ flowData.vars }
  39691. ${ flowData.code }
  39692. return ${ flowData.result };
  39693. }`;
  39694. //
  39695. return code;
  39696. }
  39697. /**
  39698. * Setups the Pixel Buffer Object (PBO) for the given storage
  39699. * buffer node.
  39700. *
  39701. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  39702. */
  39703. setupPBO( storageBufferNode ) {
  39704. const attribute = storageBufferNode.value;
  39705. if ( attribute.pbo === undefined ) {
  39706. const originalArray = attribute.array;
  39707. const numElements = attribute.count * attribute.itemSize;
  39708. const { itemSize } = attribute;
  39709. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  39710. let format = isInteger ? RedIntegerFormat : RedFormat;
  39711. if ( itemSize === 2 ) {
  39712. format = isInteger ? RGIntegerFormat : RGFormat;
  39713. } else if ( itemSize === 3 ) {
  39714. format = isInteger ? RGBIntegerFormat : RGBFormat;
  39715. } else if ( itemSize === 4 ) {
  39716. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  39717. }
  39718. const typeMap = {
  39719. Float32Array: FloatType,
  39720. Uint8Array: UnsignedByteType,
  39721. Uint16Array: UnsignedShortType,
  39722. Uint32Array: UnsignedIntType,
  39723. Int8Array: ByteType,
  39724. Int16Array: ShortType,
  39725. Int32Array: IntType,
  39726. Uint8ClampedArray: UnsignedByteType,
  39727. };
  39728. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  39729. let height = Math.ceil( ( numElements / itemSize ) / width );
  39730. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  39731. const newSize = width * height * itemSize;
  39732. const newArray = new originalArray.constructor( newSize );
  39733. newArray.set( originalArray, 0 );
  39734. attribute.array = newArray;
  39735. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  39736. pboTexture.needsUpdate = true;
  39737. pboTexture.isPBOTexture = true;
  39738. const pbo = new TextureNode( pboTexture, null, null );
  39739. pbo.setPrecision( 'high' );
  39740. attribute.pboNode = pbo;
  39741. attribute.pbo = pbo.value;
  39742. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  39743. }
  39744. }
  39745. /**
  39746. * Returns a GLSL snippet that represents the property name of the given node.
  39747. *
  39748. * @param {Node} node - The node.
  39749. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  39750. * @return {string} The property name.
  39751. */
  39752. getPropertyName( node, shaderStage = this.shaderStage ) {
  39753. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  39754. return shaderStage.charAt( 0 ) + '_' + node.name;
  39755. }
  39756. return super.getPropertyName( node, shaderStage );
  39757. }
  39758. /**
  39759. * Setups the Pixel Buffer Object (PBO) for the given storage
  39760. * buffer node.
  39761. *
  39762. * @param {StorageArrayElementNode} storageArrayElementNode - The storage array element node.
  39763. * @return {string} The property name.
  39764. */
  39765. generatePBO( storageArrayElementNode ) {
  39766. const { node, indexNode } = storageArrayElementNode;
  39767. const attribute = node.value;
  39768. if ( this.renderer.backend.has( attribute ) ) {
  39769. const attributeData = this.renderer.backend.get( attribute );
  39770. attributeData.pbo = attribute.pbo;
  39771. }
  39772. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  39773. const textureName = this.getPropertyName( nodeUniform );
  39774. this.increaseUsage( indexNode ); // force cache generate to be used as index in x,y
  39775. const indexSnippet = indexNode.build( this, 'uint' );
  39776. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  39777. let propertyName = elementNodeData.propertyName;
  39778. if ( propertyName === undefined ) {
  39779. // property element
  39780. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  39781. propertyName = this.getPropertyName( nodeVar );
  39782. // property size
  39783. const bufferNodeData = this.getDataFromNode( node );
  39784. let propertySizeName = bufferNodeData.propertySizeName;
  39785. if ( propertySizeName === undefined ) {
  39786. propertySizeName = propertyName + 'Size';
  39787. this.getVarFromNode( node, propertySizeName, 'uint' );
  39788. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )`, storageArrayElementNode );
  39789. bufferNodeData.propertySizeName = propertySizeName;
  39790. }
  39791. //
  39792. const { itemSize } = attribute;
  39793. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  39794. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  39795. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, null, '0' );
  39796. //
  39797. let prefix = 'vec4';
  39798. if ( attribute.pbo.type === UnsignedIntType ) {
  39799. prefix = 'uvec4';
  39800. } else if ( attribute.pbo.type === IntType ) {
  39801. prefix = 'ivec4';
  39802. }
  39803. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}`, storageArrayElementNode );
  39804. elementNodeData.propertyName = propertyName;
  39805. }
  39806. return propertyName;
  39807. }
  39808. /**
  39809. * Generates the GLSL snippet that reads a single texel from a texture without sampling or filtering.
  39810. *
  39811. * @param {Texture} texture - The texture.
  39812. * @param {string} textureProperty - The name of the texture uniform in the shader.
  39813. * @param {string} uvIndexSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  39814. * @param {?string} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  39815. * @param {string} [levelSnippet='0u'] - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  39816. * @return {string} The GLSL snippet.
  39817. */
  39818. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0' ) {
  39819. if ( depthSnippet ) {
  39820. return `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  39821. } else {
  39822. return `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  39823. }
  39824. }
  39825. /**
  39826. * Generates the GLSL snippet for sampling/loading the given texture.
  39827. *
  39828. * @param {Texture} texture - The texture.
  39829. * @param {string} textureProperty - The name of the texture uniform in the shader.
  39830. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  39831. * @param {?string} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  39832. * @return {string} The GLSL snippet.
  39833. */
  39834. generateTexture( texture, textureProperty, uvSnippet, depthSnippet ) {
  39835. if ( texture.isDepthTexture ) {
  39836. if ( depthSnippet ) uvSnippet = `vec4( ${ uvSnippet }, ${ depthSnippet } )`;
  39837. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  39838. } else {
  39839. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  39840. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  39841. }
  39842. }
  39843. /**
  39844. * Generates the GLSL snippet when sampling textures with explicit mip level.
  39845. *
  39846. * @param {Texture} texture - The texture.
  39847. * @param {string} textureProperty - The name of the texture uniform in the shader.
  39848. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  39849. * @param {string} levelSnippet - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  39850. * @return {string} The GLSL snippet.
  39851. */
  39852. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet ) {
  39853. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  39854. }
  39855. /**
  39856. * Generates the GLSL snippet when sampling textures with a bias to the mip level.
  39857. *
  39858. * @param {Texture} texture - The texture.
  39859. * @param {string} textureProperty - The name of the texture uniform in the shader.
  39860. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  39861. * @param {string} biasSnippet - A GLSL snippet that represents the bias to apply to the mip level before sampling.
  39862. * @return {string} The GLSL snippet.
  39863. */
  39864. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet ) {
  39865. return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
  39866. }
  39867. /**
  39868. * Generates the GLSL snippet for sampling/loading the given texture using explicit gradients.
  39869. *
  39870. * @param {Texture} texture - The texture.
  39871. * @param {string} textureProperty - The name of the texture uniform in the shader.
  39872. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  39873. * @param {Array<string>} gradSnippet - An array holding both gradient GLSL snippets.
  39874. * @return {string} The GLSL snippet.
  39875. */
  39876. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet ) {
  39877. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  39878. }
  39879. /**
  39880. * Generates the GLSL snippet for sampling a depth texture and comparing the sampled depth values
  39881. * against a reference value.
  39882. *
  39883. * @param {Texture} texture - The texture.
  39884. * @param {string} textureProperty - The name of the texture uniform in the shader.
  39885. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  39886. * @param {string} compareSnippet - A GLSL snippet that represents the reference value.
  39887. * @param {?string} depthSnippet - A GLSL snippet that represents 0-based texture array index to sample.
  39888. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  39889. * @return {string} The GLSL snippet.
  39890. */
  39891. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  39892. if ( shaderStage === 'fragment' ) {
  39893. if ( depthSnippet ) {
  39894. return `texture( ${ textureProperty }, vec4( ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } ) )`;
  39895. }
  39896. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  39897. } else {
  39898. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  39899. }
  39900. }
  39901. /**
  39902. * Returns the variables of the given shader stage as a GLSL string.
  39903. *
  39904. * @param {string} shaderStage - The shader stage.
  39905. * @return {string} The GLSL snippet that defines the variables.
  39906. */
  39907. getVars( shaderStage ) {
  39908. const snippets = [];
  39909. const vars = this.vars[ shaderStage ];
  39910. if ( vars !== undefined ) {
  39911. for ( const variable of vars ) {
  39912. snippets.push( `${ this.getVar( variable.type, variable.name, variable.count ) };` );
  39913. }
  39914. }
  39915. return snippets.join( '\n\t' );
  39916. }
  39917. /**
  39918. * Returns the uniforms of the given shader stage as a GLSL string.
  39919. *
  39920. * @param {string} shaderStage - The shader stage.
  39921. * @return {string} The GLSL snippet that defines the uniforms.
  39922. */
  39923. getUniforms( shaderStage ) {
  39924. const uniforms = this.uniforms[ shaderStage ];
  39925. const bindingSnippets = [];
  39926. const uniformGroups = {};
  39927. for ( const uniform of uniforms ) {
  39928. let snippet = null;
  39929. let group = false;
  39930. if ( uniform.type === 'texture' || uniform.type === 'texture3D' ) {
  39931. const texture = uniform.node.value;
  39932. let typePrefix = '';
  39933. if ( texture.isDataTexture === true || texture.isData3DTexture === true ) {
  39934. if ( texture.type === UnsignedIntType ) {
  39935. typePrefix = 'u';
  39936. } else if ( texture.type === IntType ) {
  39937. typePrefix = 'i';
  39938. }
  39939. }
  39940. if ( uniform.type === 'texture3D' && texture.isArrayTexture === false ) {
  39941. snippet = `${typePrefix}sampler3D ${ uniform.name };`;
  39942. } else if ( texture.compareFunction ) {
  39943. if ( texture.isArrayTexture === true ) {
  39944. snippet = `sampler2DArrayShadow ${ uniform.name };`;
  39945. } else {
  39946. snippet = `sampler2DShadow ${ uniform.name };`;
  39947. }
  39948. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  39949. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  39950. } else {
  39951. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  39952. }
  39953. } else if ( uniform.type === 'cubeTexture' ) {
  39954. snippet = `samplerCube ${ uniform.name };`;
  39955. } else if ( uniform.type === 'buffer' ) {
  39956. const bufferNode = uniform.node;
  39957. const bufferType = this.getType( bufferNode.bufferType );
  39958. const bufferCount = bufferNode.bufferCount;
  39959. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  39960. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  39961. } else {
  39962. const vectorType = this.getVectorType( uniform.type );
  39963. snippet = `${ vectorType } ${ this.getPropertyName( uniform, shaderStage ) };`;
  39964. group = true;
  39965. }
  39966. const precision = uniform.node.precision;
  39967. if ( precision !== null ) {
  39968. snippet = precisionLib[ precision ] + ' ' + snippet;
  39969. }
  39970. if ( group ) {
  39971. snippet = '\t' + snippet;
  39972. const groupName = uniform.groupNode.name;
  39973. const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
  39974. groupSnippets.push( snippet );
  39975. } else {
  39976. snippet = 'uniform ' + snippet;
  39977. bindingSnippets.push( snippet );
  39978. }
  39979. }
  39980. let output = '';
  39981. for ( const name in uniformGroups ) {
  39982. const groupSnippets = uniformGroups[ name ];
  39983. output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
  39984. }
  39985. output += bindingSnippets.join( '\n' );
  39986. return output;
  39987. }
  39988. /**
  39989. * Returns the type for a given buffer attribute.
  39990. *
  39991. * @param {BufferAttribute} attribute - The buffer attribute.
  39992. * @return {string} The type.
  39993. */
  39994. getTypeFromAttribute( attribute ) {
  39995. let nodeType = super.getTypeFromAttribute( attribute );
  39996. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  39997. let dataAttribute = attribute;
  39998. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  39999. const array = dataAttribute.array;
  40000. if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
  40001. nodeType = nodeType.slice( 1 );
  40002. }
  40003. }
  40004. return nodeType;
  40005. }
  40006. /**
  40007. * Returns the shader attributes of the given shader stage as a GLSL string.
  40008. *
  40009. * @param {string} shaderStage - The shader stage.
  40010. * @return {string} The GLSL snippet that defines the shader attributes.
  40011. */
  40012. getAttributes( shaderStage ) {
  40013. let snippet = '';
  40014. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  40015. const attributes = this.getAttributesArray();
  40016. let location = 0;
  40017. for ( const attribute of attributes ) {
  40018. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  40019. }
  40020. }
  40021. return snippet;
  40022. }
  40023. /**
  40024. * Returns the members of the given struct type node as a GLSL string.
  40025. *
  40026. * @param {StructTypeNode} struct - The struct type node.
  40027. * @return {string} The GLSL snippet that defines the struct members.
  40028. */
  40029. getStructMembers( struct ) {
  40030. const snippets = [];
  40031. for ( const member of struct.members ) {
  40032. snippets.push( `\t${ member.type } ${ member.name };` );
  40033. }
  40034. return snippets.join( '\n' );
  40035. }
  40036. /**
  40037. * Returns the structs of the given shader stage as a GLSL string.
  40038. *
  40039. * @param {string} shaderStage - The shader stage.
  40040. * @return {string} The GLSL snippet that defines the structs.
  40041. */
  40042. getStructs( shaderStage ) {
  40043. const snippets = [];
  40044. const structs = this.structs[ shaderStage ];
  40045. const outputSnippet = [];
  40046. for ( const struct of structs ) {
  40047. if ( struct.output ) {
  40048. for ( const member of struct.members ) {
  40049. outputSnippet.push( `layout( location = ${ member.index } ) out ${ member.type } ${ member.name };` );
  40050. }
  40051. } else {
  40052. let snippet = 'struct ' + struct.name + ' {\n';
  40053. snippet += this.getStructMembers( struct );
  40054. snippet += '\n};\n';
  40055. snippets.push( snippet );
  40056. }
  40057. }
  40058. if ( outputSnippet.length === 0 ) {
  40059. outputSnippet.push( 'layout( location = 0 ) out vec4 fragColor;' );
  40060. }
  40061. return '\n' + outputSnippet.join( '\n' ) + '\n\n' + snippets.join( '\n' );
  40062. }
  40063. /**
  40064. * Returns the varyings of the given shader stage as a GLSL string.
  40065. *
  40066. * @param {string} shaderStage - The shader stage.
  40067. * @return {string} The GLSL snippet that defines the varyings.
  40068. */
  40069. getVaryings( shaderStage ) {
  40070. let snippet = '';
  40071. const varyings = this.varyings;
  40072. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  40073. for ( const varying of varyings ) {
  40074. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  40075. const type = this.getType( varying.type );
  40076. if ( varying.needsInterpolation ) {
  40077. if ( varying.interpolationType ) {
  40078. const interpolationType = interpolationTypeMap[ varying.interpolationType ] || varying.interpolationType;
  40079. const sampling = interpolationModeMap[ varying.interpolationSampling ] || '';
  40080. snippet += `${ interpolationType } ${ sampling } out ${ type } ${ varying.name };\n`;
  40081. } else {
  40082. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  40083. snippet += `${ flat }out ${ type } ${ varying.name };\n`;
  40084. }
  40085. } else {
  40086. snippet += `${type} ${varying.name};\n`; // generate variable (no varying required)
  40087. }
  40088. }
  40089. } else if ( shaderStage === 'fragment' ) {
  40090. for ( const varying of varyings ) {
  40091. if ( varying.needsInterpolation ) {
  40092. const type = this.getType( varying.type );
  40093. if ( varying.interpolationType ) {
  40094. const interpolationType = interpolationTypeMap[ varying.interpolationType ] || varying.interpolationType;
  40095. const sampling = interpolationModeMap[ varying.interpolationSampling ] || '';
  40096. snippet += `${ interpolationType } ${ sampling } in ${ type } ${ varying.name };\n`;
  40097. } else {
  40098. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  40099. snippet += `${ flat }in ${ type } ${ varying.name };\n`;
  40100. }
  40101. }
  40102. }
  40103. }
  40104. for ( const builtin of this.builtins[ shaderStage ] ) {
  40105. snippet += `${builtin};\n`;
  40106. }
  40107. return snippet;
  40108. }
  40109. /**
  40110. * Returns the vertex index builtin.
  40111. *
  40112. * @return {string} The vertex index.
  40113. */
  40114. getVertexIndex() {
  40115. return 'uint( gl_VertexID )';
  40116. }
  40117. /**
  40118. * Returns the instance index builtin.
  40119. *
  40120. * @return {string} The instance index.
  40121. */
  40122. getInstanceIndex() {
  40123. return 'uint( gl_InstanceID )';
  40124. }
  40125. /**
  40126. * Returns the invocation local index builtin.
  40127. *
  40128. * @return {string} The invocation local index.
  40129. */
  40130. getInvocationLocalIndex() {
  40131. const workgroupSize = this.object.workgroupSize;
  40132. const size = workgroupSize.reduce( ( acc, curr ) => acc * curr, 1 );
  40133. return `uint( gl_InstanceID ) % ${size}u`;
  40134. }
  40135. /**
  40136. * Returns the draw index builtin.
  40137. *
  40138. * @return {?string} The drawIndex shader string. Returns `null` if `WEBGL_multi_draw` isn't supported by the device.
  40139. */
  40140. getDrawIndex() {
  40141. const extensions = this.renderer.backend.extensions;
  40142. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  40143. return 'uint( gl_DrawID )';
  40144. }
  40145. return null;
  40146. }
  40147. /**
  40148. * Returns the front facing builtin.
  40149. *
  40150. * @return {string} The front facing builtin.
  40151. */
  40152. getFrontFacing() {
  40153. return 'gl_FrontFacing';
  40154. }
  40155. /**
  40156. * Returns the frag coord builtin.
  40157. *
  40158. * @return {string} The frag coord builtin.
  40159. */
  40160. getFragCoord() {
  40161. return 'gl_FragCoord.xy';
  40162. }
  40163. /**
  40164. * Returns the frag depth builtin.
  40165. *
  40166. * @return {string} The frag depth builtin.
  40167. */
  40168. getFragDepth() {
  40169. return 'gl_FragDepth';
  40170. }
  40171. /**
  40172. * Enables the given extension.
  40173. *
  40174. * @param {string} name - The extension name.
  40175. * @param {string} behavior - The extension behavior.
  40176. * @param {string} [shaderStage=this.shaderStage] - The shader stage.
  40177. */
  40178. enableExtension( name, behavior, shaderStage = this.shaderStage ) {
  40179. const map = this.extensions[ shaderStage ] || ( this.extensions[ shaderStage ] = new Map() );
  40180. if ( map.has( name ) === false ) {
  40181. map.set( name, {
  40182. name,
  40183. behavior
  40184. } );
  40185. }
  40186. }
  40187. /**
  40188. * Returns the enabled extensions of the given shader stage as a GLSL string.
  40189. *
  40190. * @param {string} shaderStage - The shader stage.
  40191. * @return {string} The GLSL snippet that defines the enabled extensions.
  40192. */
  40193. getExtensions( shaderStage ) {
  40194. const snippets = [];
  40195. if ( shaderStage === 'vertex' ) {
  40196. const ext = this.renderer.backend.extensions;
  40197. const isBatchedMesh = this.object.isBatchedMesh;
  40198. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  40199. this.enableExtension( 'GL_ANGLE_multi_draw', 'require', shaderStage );
  40200. }
  40201. }
  40202. const extensions = this.extensions[ shaderStage ];
  40203. if ( extensions !== undefined ) {
  40204. for ( const { name, behavior } of extensions.values() ) {
  40205. snippets.push( `#extension ${name} : ${behavior}` );
  40206. }
  40207. }
  40208. return snippets.join( '\n' );
  40209. }
  40210. /**
  40211. * Returns the clip distances builtin.
  40212. *
  40213. * @return {string} The clip distances builtin.
  40214. */
  40215. getClipDistance() {
  40216. return 'gl_ClipDistance';
  40217. }
  40218. /**
  40219. * Whether the requested feature is available or not.
  40220. *
  40221. * @param {string} name - The requested feature.
  40222. * @return {boolean} Whether the requested feature is supported or not.
  40223. */
  40224. isAvailable( name ) {
  40225. let result = supports$1[ name ];
  40226. if ( result === undefined ) {
  40227. let extensionName;
  40228. result = false;
  40229. switch ( name ) {
  40230. case 'float32Filterable':
  40231. extensionName = 'OES_texture_float_linear';
  40232. break;
  40233. case 'clipDistance':
  40234. extensionName = 'WEBGL_clip_cull_distance';
  40235. break;
  40236. }
  40237. if ( extensionName !== undefined ) {
  40238. const extensions = this.renderer.backend.extensions;
  40239. if ( extensions.has( extensionName ) ) {
  40240. extensions.get( extensionName );
  40241. result = true;
  40242. }
  40243. }
  40244. supports$1[ name ] = result;
  40245. }
  40246. return result;
  40247. }
  40248. /**
  40249. * Whether to flip texture data along its vertical axis or not.
  40250. *
  40251. * @return {boolean} Returns always `true` in context of GLSL.
  40252. */
  40253. isFlipY() {
  40254. return true;
  40255. }
  40256. /**
  40257. * Enables hardware clipping.
  40258. *
  40259. * @param {string} planeCount - The clipping plane count.
  40260. */
  40261. enableHardwareClipping( planeCount ) {
  40262. this.enableExtension( 'GL_ANGLE_clip_cull_distance', 'require' );
  40263. this.builtins[ 'vertex' ].push( `out float gl_ClipDistance[ ${ planeCount } ]` );
  40264. }
  40265. /**
  40266. * Enables multiview.
  40267. */
  40268. enableMultiview() {
  40269. this.enableExtension( 'GL_OVR_multiview2', 'require', 'fragment' );
  40270. this.enableExtension( 'GL_OVR_multiview2', 'require', 'vertex' );
  40271. this.builtins[ 'vertex' ].push( 'layout(num_views = 2) in' );
  40272. }
  40273. /**
  40274. * Registers a transform in context of Transform Feedback.
  40275. *
  40276. * @param {string} varyingName - The varying name.
  40277. * @param {AttributeNode} attributeNode - The attribute node.
  40278. */
  40279. registerTransform( varyingName, attributeNode ) {
  40280. this.transforms.push( { varyingName, attributeNode } );
  40281. }
  40282. /**
  40283. * Returns the transforms of the given shader stage as a GLSL string.
  40284. *
  40285. * @param {string} shaderStage - The shader stage.
  40286. * @return {string} The GLSL snippet that defines the transforms.
  40287. */
  40288. getTransforms( /* shaderStage */ ) {
  40289. const transforms = this.transforms;
  40290. let snippet = '';
  40291. for ( let i = 0; i < transforms.length; i ++ ) {
  40292. const transform = transforms[ i ];
  40293. const attributeName = this.getPropertyName( transform.attributeNode );
  40294. if ( attributeName ) snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  40295. }
  40296. return snippet;
  40297. }
  40298. /**
  40299. * Returns a GLSL struct based on the given name and variables.
  40300. *
  40301. * @private
  40302. * @param {string} name - The struct name.
  40303. * @param {string} vars - The struct variables.
  40304. * @return {string} The GLSL snippet representing a struct.
  40305. */
  40306. _getGLSLUniformStruct( name, vars ) {
  40307. return `
  40308. layout( std140 ) uniform ${name} {
  40309. ${vars}
  40310. };`;
  40311. }
  40312. /**
  40313. * Returns a GLSL vertex shader based on the given shader data.
  40314. *
  40315. * @private
  40316. * @param {Object} shaderData - The shader data.
  40317. * @return {string} The vertex shader.
  40318. */
  40319. _getGLSLVertexCode( shaderData ) {
  40320. return `#version 300 es
  40321. ${ this.getSignature() }
  40322. // extensions
  40323. ${shaderData.extensions}
  40324. // precision
  40325. ${ defaultPrecisions }
  40326. // uniforms
  40327. ${shaderData.uniforms}
  40328. // varyings
  40329. ${shaderData.varyings}
  40330. // attributes
  40331. ${shaderData.attributes}
  40332. // codes
  40333. ${shaderData.codes}
  40334. void main() {
  40335. // vars
  40336. ${shaderData.vars}
  40337. // transforms
  40338. ${shaderData.transforms}
  40339. // flow
  40340. ${shaderData.flow}
  40341. gl_PointSize = 1.0;
  40342. }
  40343. `;
  40344. }
  40345. /**
  40346. * Returns a GLSL fragment shader based on the given shader data.
  40347. *
  40348. * @private
  40349. * @param {Object} shaderData - The shader data.
  40350. * @return {string} The vertex shader.
  40351. */
  40352. _getGLSLFragmentCode( shaderData ) {
  40353. return `#version 300 es
  40354. ${ this.getSignature() }
  40355. // extensions
  40356. ${shaderData.extensions}
  40357. // precision
  40358. ${ defaultPrecisions }
  40359. // uniforms
  40360. ${shaderData.uniforms}
  40361. // varyings
  40362. ${shaderData.varyings}
  40363. // codes
  40364. ${shaderData.codes}
  40365. // structs
  40366. ${shaderData.structs}
  40367. void main() {
  40368. // vars
  40369. ${shaderData.vars}
  40370. // flow
  40371. ${shaderData.flow}
  40372. }
  40373. `;
  40374. }
  40375. /**
  40376. * Controls the code build of the shader stages.
  40377. */
  40378. buildCode() {
  40379. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  40380. this.sortBindingGroups();
  40381. for ( const shaderStage in shadersData ) {
  40382. let flow = '// code\n\n';
  40383. flow += this.flowCode[ shaderStage ];
  40384. const flowNodes = this.flowNodes[ shaderStage ];
  40385. const mainNode = flowNodes[ flowNodes.length - 1 ];
  40386. for ( const node of flowNodes ) {
  40387. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  40388. const slotName = node.name;
  40389. if ( slotName ) {
  40390. if ( flow.length > 0 ) flow += '\n';
  40391. flow += `\t// flow -> ${ slotName }\n\t`;
  40392. }
  40393. flow += `${ flowSlotData.code }\n\t`;
  40394. if ( node === mainNode && shaderStage !== 'compute' ) {
  40395. flow += '// result\n\t';
  40396. if ( shaderStage === 'vertex' ) {
  40397. flow += 'gl_Position = ';
  40398. flow += `${ flowSlotData.result };`;
  40399. } else if ( shaderStage === 'fragment' ) {
  40400. if ( ! node.outputNode.isOutputStructNode ) {
  40401. flow += 'fragColor = ';
  40402. flow += `${ flowSlotData.result };`;
  40403. }
  40404. }
  40405. }
  40406. }
  40407. const stageData = shadersData[ shaderStage ];
  40408. stageData.extensions = this.getExtensions( shaderStage );
  40409. stageData.uniforms = this.getUniforms( shaderStage );
  40410. stageData.attributes = this.getAttributes( shaderStage );
  40411. stageData.varyings = this.getVaryings( shaderStage );
  40412. stageData.vars = this.getVars( shaderStage );
  40413. stageData.structs = this.getStructs( shaderStage );
  40414. stageData.codes = this.getCodes( shaderStage );
  40415. stageData.transforms = this.getTransforms( shaderStage );
  40416. stageData.flow = flow;
  40417. }
  40418. if ( this.material !== null ) {
  40419. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  40420. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  40421. } else {
  40422. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  40423. }
  40424. }
  40425. /**
  40426. * This method is one of the more important ones since it's responsible
  40427. * for generating a matching binding instance for the given uniform node.
  40428. *
  40429. * These bindings are later used in the renderer to create bind groups
  40430. * and layouts.
  40431. *
  40432. * @param {UniformNode} node - The uniform node.
  40433. * @param {string} type - The node data type.
  40434. * @param {string} shaderStage - The shader stage.
  40435. * @param {?string} [name=null] - An optional uniform name.
  40436. * @return {NodeUniform} The node uniform object.
  40437. */
  40438. getUniformFromNode( node, type, shaderStage, name = null ) {
  40439. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  40440. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  40441. let uniformGPU = nodeData.uniformGPU;
  40442. if ( uniformGPU === undefined ) {
  40443. const group = node.groupNode;
  40444. const groupName = group.name;
  40445. const bindings = this.getBindGroupArray( groupName, shaderStage );
  40446. if ( type === 'texture' ) {
  40447. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  40448. bindings.push( uniformGPU );
  40449. } else if ( type === 'cubeTexture' ) {
  40450. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  40451. bindings.push( uniformGPU );
  40452. } else if ( type === 'texture3D' ) {
  40453. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  40454. bindings.push( uniformGPU );
  40455. } else if ( type === 'buffer' ) {
  40456. node.name = `NodeBuffer_${ node.id }`;
  40457. uniformNode.name = `buffer${ node.id }`;
  40458. const buffer = new NodeUniformBuffer( node, group );
  40459. buffer.name = node.name;
  40460. bindings.push( buffer );
  40461. uniformGPU = buffer;
  40462. } else {
  40463. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  40464. let uniformsGroup = uniformsStage[ groupName ];
  40465. if ( uniformsGroup === undefined ) {
  40466. uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
  40467. //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  40468. uniformsStage[ groupName ] = uniformsGroup;
  40469. bindings.push( uniformsGroup );
  40470. }
  40471. uniformGPU = this.getNodeUniform( uniformNode, type );
  40472. uniformsGroup.addUniform( uniformGPU );
  40473. }
  40474. nodeData.uniformGPU = uniformGPU;
  40475. }
  40476. return uniformNode;
  40477. }
  40478. }
  40479. let _vector2 = null;
  40480. let _color4 = null;
  40481. /**
  40482. * Most of the rendering related logic is implemented in the
  40483. * {@link Renderer} module and related management components.
  40484. * Sometimes it is required though to execute commands which are
  40485. * specific to the current 3D backend (which is WebGPU or WebGL 2).
  40486. * This abstract base class defines an interface that encapsulates
  40487. * all backend-related logic. Derived classes for each backend must
  40488. * implement the interface.
  40489. *
  40490. * @abstract
  40491. * @private
  40492. */
  40493. class Backend {
  40494. /**
  40495. * Constructs a new backend.
  40496. *
  40497. * @param {Object} parameters - An object holding parameters for the backend.
  40498. */
  40499. constructor( parameters = {} ) {
  40500. /**
  40501. * The parameters of the backend.
  40502. *
  40503. * @type {Object}
  40504. */
  40505. this.parameters = Object.assign( {}, parameters );
  40506. /**
  40507. * This weak map holds backend-specific data of objects
  40508. * like textures, attributes or render targets.
  40509. *
  40510. * @type {WeakMap}
  40511. */
  40512. this.data = new WeakMap();
  40513. /**
  40514. * A reference to the renderer.
  40515. *
  40516. * @type {?Renderer}
  40517. * @default null
  40518. */
  40519. this.renderer = null;
  40520. /**
  40521. * A reference to the canvas element the renderer is drawing to.
  40522. *
  40523. * @type {?(HTMLCanvasElement|OffscreenCanvas)}
  40524. * @default null
  40525. */
  40526. this.domElement = null;
  40527. /**
  40528. * A reference to the timestamp query pool.
  40529. *
  40530. * @type {{render: ?TimestampQueryPool, compute: ?TimestampQueryPool}}
  40531. */
  40532. this.timestampQueryPool = {
  40533. 'render': null,
  40534. 'compute': null
  40535. };
  40536. /**
  40537. * Whether to track timestamps with a Timestamp Query API or not.
  40538. *
  40539. * @type {boolean}
  40540. * @default false
  40541. */
  40542. this.trackTimestamp = ( parameters.trackTimestamp === true );
  40543. }
  40544. /**
  40545. * Initializes the backend so it is ready for usage. Concrete backends
  40546. * are supposed to implement their rendering context creation and related
  40547. * operations in this method.
  40548. *
  40549. * @async
  40550. * @param {Renderer} renderer - The renderer.
  40551. * @return {Promise} A Promise that resolves when the backend has been initialized.
  40552. */
  40553. async init( renderer ) {
  40554. this.renderer = renderer;
  40555. }
  40556. /**
  40557. * The coordinate system of the backend.
  40558. *
  40559. * @abstract
  40560. * @type {number}
  40561. * @readonly
  40562. */
  40563. get coordinateSystem() {}
  40564. // render context
  40565. /**
  40566. * This method is executed at the beginning of a render call and
  40567. * can be used by the backend to prepare the state for upcoming
  40568. * draw calls.
  40569. *
  40570. * @abstract
  40571. * @param {RenderContext} renderContext - The render context.
  40572. */
  40573. beginRender( /*renderContext*/ ) {}
  40574. /**
  40575. * This method is executed at the end of a render call and
  40576. * can be used by the backend to finalize work after draw
  40577. * calls.
  40578. *
  40579. * @abstract
  40580. * @param {RenderContext} renderContext - The render context.
  40581. */
  40582. finishRender( /*renderContext*/ ) {}
  40583. /**
  40584. * This method is executed at the beginning of a compute call and
  40585. * can be used by the backend to prepare the state for upcoming
  40586. * compute tasks.
  40587. *
  40588. * @abstract
  40589. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  40590. */
  40591. beginCompute( /*computeGroup*/ ) {}
  40592. /**
  40593. * This method is executed at the end of a compute call and
  40594. * can be used by the backend to finalize work after compute
  40595. * tasks.
  40596. *
  40597. * @abstract
  40598. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  40599. */
  40600. finishCompute( /*computeGroup*/ ) {}
  40601. // render object
  40602. /**
  40603. * Executes a draw command for the given render object.
  40604. *
  40605. * @abstract
  40606. * @param {RenderObject} renderObject - The render object to draw.
  40607. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  40608. */
  40609. draw( /*renderObject, info*/ ) { }
  40610. // compute node
  40611. /**
  40612. * Executes a compute command for the given compute node.
  40613. *
  40614. * @abstract
  40615. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  40616. * @param {Node} computeNode - The compute node.
  40617. * @param {Array<BindGroup>} bindings - The bindings.
  40618. * @param {ComputePipeline} computePipeline - The compute pipeline.
  40619. */
  40620. compute( /*computeGroup, computeNode, computeBindings, computePipeline*/ ) { }
  40621. // program
  40622. /**
  40623. * Creates a shader program from the given programmable stage.
  40624. *
  40625. * @abstract
  40626. * @param {ProgrammableStage} program - The programmable stage.
  40627. */
  40628. createProgram( /*program*/ ) { }
  40629. /**
  40630. * Destroys the shader program of the given programmable stage.
  40631. *
  40632. * @abstract
  40633. * @param {ProgrammableStage} program - The programmable stage.
  40634. */
  40635. destroyProgram( /*program*/ ) { }
  40636. // bindings
  40637. /**
  40638. * Creates bindings from the given bind group definition.
  40639. *
  40640. * @abstract
  40641. * @param {BindGroup} bindGroup - The bind group.
  40642. * @param {Array<BindGroup>} bindings - Array of bind groups.
  40643. * @param {number} cacheIndex - The cache index.
  40644. * @param {number} version - The version.
  40645. */
  40646. createBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  40647. /**
  40648. * Updates the given bind group definition.
  40649. *
  40650. * @abstract
  40651. * @param {BindGroup} bindGroup - The bind group.
  40652. * @param {Array<BindGroup>} bindings - Array of bind groups.
  40653. * @param {number} cacheIndex - The cache index.
  40654. * @param {number} version - The version.
  40655. */
  40656. updateBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  40657. /**
  40658. * Updates a buffer binding.
  40659. *
  40660. * @abstract
  40661. * @param {Buffer} binding - The buffer binding to update.
  40662. */
  40663. updateBinding( /*binding*/ ) { }
  40664. // pipeline
  40665. /**
  40666. * Creates a render pipeline for the given render object.
  40667. *
  40668. * @abstract
  40669. * @param {RenderObject} renderObject - The render object.
  40670. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  40671. */
  40672. createRenderPipeline( /*renderObject, promises*/ ) { }
  40673. /**
  40674. * Creates a compute pipeline for the given compute node.
  40675. *
  40676. * @abstract
  40677. * @param {ComputePipeline} computePipeline - The compute pipeline.
  40678. * @param {Array<BindGroup>} bindings - The bindings.
  40679. */
  40680. createComputePipeline( /*computePipeline, bindings*/ ) { }
  40681. // cache key
  40682. /**
  40683. * Returns `true` if the render pipeline requires an update.
  40684. *
  40685. * @abstract
  40686. * @param {RenderObject} renderObject - The render object.
  40687. * @return {boolean} Whether the render pipeline requires an update or not.
  40688. */
  40689. needsRenderUpdate( /*renderObject*/ ) { }
  40690. /**
  40691. * Returns a cache key that is used to identify render pipelines.
  40692. *
  40693. * @abstract
  40694. * @param {RenderObject} renderObject - The render object.
  40695. * @return {string} The cache key.
  40696. */
  40697. getRenderCacheKey( /*renderObject*/ ) { }
  40698. // node builder
  40699. /**
  40700. * Returns a node builder for the given render object.
  40701. *
  40702. * @abstract
  40703. * @param {RenderObject} renderObject - The render object.
  40704. * @param {Renderer} renderer - The renderer.
  40705. * @return {NodeBuilder} The node builder.
  40706. */
  40707. createNodeBuilder( /*renderObject, renderer*/ ) { }
  40708. // textures
  40709. /**
  40710. * Creates a GPU sampler for the given texture.
  40711. *
  40712. * @abstract
  40713. * @param {Texture} texture - The texture to create the sampler for.
  40714. */
  40715. createSampler( /*texture*/ ) { }
  40716. /**
  40717. * Destroys the GPU sampler for the given texture.
  40718. *
  40719. * @abstract
  40720. * @param {Texture} texture - The texture to destroy the sampler for.
  40721. */
  40722. destroySampler( /*texture*/ ) {}
  40723. /**
  40724. * Creates a default texture for the given texture that can be used
  40725. * as a placeholder until the actual texture is ready for usage.
  40726. *
  40727. * @abstract
  40728. * @param {Texture} texture - The texture to create a default texture for.
  40729. */
  40730. createDefaultTexture( /*texture*/ ) { }
  40731. /**
  40732. * Defines a texture on the GPU for the given texture object.
  40733. *
  40734. * @abstract
  40735. * @param {Texture} texture - The texture.
  40736. * @param {Object} [options={}] - Optional configuration parameter.
  40737. */
  40738. createTexture( /*texture, options={}*/ ) { }
  40739. /**
  40740. * Uploads the updated texture data to the GPU.
  40741. *
  40742. * @abstract
  40743. * @param {Texture} texture - The texture.
  40744. * @param {Object} [options={}] - Optional configuration parameter.
  40745. */
  40746. updateTexture( /*texture, options = {}*/ ) { }
  40747. /**
  40748. * Generates mipmaps for the given texture.
  40749. *
  40750. * @abstract
  40751. * @param {Texture} texture - The texture.
  40752. */
  40753. generateMipmaps( /*texture*/ ) { }
  40754. /**
  40755. * Destroys the GPU data for the given texture object.
  40756. *
  40757. * @abstract
  40758. * @param {Texture} texture - The texture.
  40759. */
  40760. destroyTexture( /*texture*/ ) { }
  40761. /**
  40762. * Returns texture data as a typed array.
  40763. *
  40764. * @abstract
  40765. * @async
  40766. * @param {Texture} texture - The texture to copy.
  40767. * @param {number} x - The x coordinate of the copy origin.
  40768. * @param {number} y - The y coordinate of the copy origin.
  40769. * @param {number} width - The width of the copy.
  40770. * @param {number} height - The height of the copy.
  40771. * @param {number} faceIndex - The face index.
  40772. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  40773. */
  40774. async copyTextureToBuffer( /*texture, x, y, width, height, faceIndex*/ ) {}
  40775. /**
  40776. * Copies data of the given source texture to the given destination texture.
  40777. *
  40778. * @abstract
  40779. * @param {Texture} srcTexture - The source texture.
  40780. * @param {Texture} dstTexture - The destination texture.
  40781. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  40782. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  40783. * @param {number} [srcLevel=0] - The source mip level to copy from.
  40784. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  40785. */
  40786. copyTextureToTexture( /*srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0*/ ) {}
  40787. /**
  40788. * Copies the current bound framebuffer to the given texture.
  40789. *
  40790. * @abstract
  40791. * @param {Texture} texture - The destination texture.
  40792. * @param {RenderContext} renderContext - The render context.
  40793. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  40794. */
  40795. copyFramebufferToTexture( /*texture, renderContext, rectangle*/ ) {}
  40796. // attributes
  40797. /**
  40798. * Creates the GPU buffer of a shader attribute.
  40799. *
  40800. * @abstract
  40801. * @param {BufferAttribute} attribute - The buffer attribute.
  40802. */
  40803. createAttribute( /*attribute*/ ) { }
  40804. /**
  40805. * Creates the GPU buffer of an indexed shader attribute.
  40806. *
  40807. * @abstract
  40808. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  40809. */
  40810. createIndexAttribute( /*attribute*/ ) { }
  40811. /**
  40812. * Creates the GPU buffer of a storage attribute.
  40813. *
  40814. * @abstract
  40815. * @param {BufferAttribute} attribute - The buffer attribute.
  40816. */
  40817. createStorageAttribute( /*attribute*/ ) { }
  40818. /**
  40819. * Updates the GPU buffer of a shader attribute.
  40820. *
  40821. * @abstract
  40822. * @param {BufferAttribute} attribute - The buffer attribute to update.
  40823. */
  40824. updateAttribute( /*attribute*/ ) { }
  40825. /**
  40826. * Destroys the GPU buffer of a shader attribute.
  40827. *
  40828. * @abstract
  40829. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  40830. */
  40831. destroyAttribute( /*attribute*/ ) { }
  40832. // canvas
  40833. /**
  40834. * Returns the backend's rendering context.
  40835. *
  40836. * @abstract
  40837. * @return {Object} The rendering context.
  40838. */
  40839. getContext() { }
  40840. /**
  40841. * Backends can use this method if they have to run
  40842. * logic when the renderer gets resized.
  40843. *
  40844. * @abstract
  40845. */
  40846. updateSize() { }
  40847. /**
  40848. * Updates the viewport with the values from the given render context.
  40849. *
  40850. * @abstract
  40851. * @param {RenderContext} renderContext - The render context.
  40852. */
  40853. updateViewport( /*renderContext*/ ) {}
  40854. // utils
  40855. /**
  40856. * Returns `true` if the given 3D object is fully occluded by other
  40857. * 3D objects in the scene. Backends must implement this method by using
  40858. * a Occlusion Query API.
  40859. *
  40860. * @abstract
  40861. * @param {RenderContext} renderContext - The render context.
  40862. * @param {Object3D} object - The 3D object to test.
  40863. * @return {boolean} Whether the 3D object is fully occluded or not.
  40864. */
  40865. isOccluded( /*renderContext, object*/ ) {}
  40866. /**
  40867. * Resolves the time stamp for the given render context and type.
  40868. *
  40869. * @async
  40870. * @abstract
  40871. * @param {string} [type='render'] - The type of the time stamp.
  40872. * @return {Promise<number>} A Promise that resolves with the time stamp.
  40873. */
  40874. async resolveTimestampsAsync( type = 'render' ) {
  40875. if ( ! this.trackTimestamp ) {
  40876. warnOnce( 'WebGPURenderer: Timestamp tracking is disabled.' );
  40877. return;
  40878. }
  40879. const queryPool = this.timestampQueryPool[ type ];
  40880. if ( ! queryPool ) {
  40881. warnOnce( `WebGPURenderer: No timestamp query pool for type '${type}' found.` );
  40882. return;
  40883. }
  40884. const duration = await queryPool.resolveQueriesAsync();
  40885. this.renderer.info[ type ].timestamp = duration;
  40886. return duration;
  40887. }
  40888. /**
  40889. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  40890. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  40891. *
  40892. * @async
  40893. * @abstract
  40894. * @return {Promise} A Promise that resolves when synchronization has been finished.
  40895. */
  40896. async waitForGPU() {}
  40897. /**
  40898. * This method performs a readback operation by moving buffer data from
  40899. * a storage buffer attribute from the GPU to the CPU.
  40900. *
  40901. * @async
  40902. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  40903. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  40904. */
  40905. async getArrayBufferAsync( /* attribute */ ) {}
  40906. /**
  40907. * Checks if the given feature is supported by the backend.
  40908. *
  40909. * @async
  40910. * @abstract
  40911. * @param {string} name - The feature's name.
  40912. * @return {Promise<boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  40913. */
  40914. async hasFeatureAsync( /*name*/ ) { }
  40915. /**
  40916. * Checks if the given feature is supported by the backend.
  40917. *
  40918. * @abstract
  40919. * @param {string} name - The feature's name.
  40920. * @return {boolean} Whether the feature is supported or not.
  40921. */
  40922. hasFeature( /*name*/ ) {}
  40923. /**
  40924. * Returns the maximum anisotropy texture filtering value.
  40925. *
  40926. * @abstract
  40927. * @return {number} The maximum anisotropy texture filtering value.
  40928. */
  40929. getMaxAnisotropy() {}
  40930. /**
  40931. * Returns the drawing buffer size.
  40932. *
  40933. * @return {Vector2} The drawing buffer size.
  40934. */
  40935. getDrawingBufferSize() {
  40936. _vector2 = _vector2 || new Vector2();
  40937. return this.renderer.getDrawingBufferSize( _vector2 );
  40938. }
  40939. /**
  40940. * Defines the scissor test.
  40941. *
  40942. * @abstract
  40943. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  40944. */
  40945. setScissorTest( /*boolean*/ ) { }
  40946. /**
  40947. * Returns the clear color and alpha into a single
  40948. * color object.
  40949. *
  40950. * @return {Color4} The clear color.
  40951. */
  40952. getClearColor() {
  40953. const renderer = this.renderer;
  40954. _color4 = _color4 || new Color4();
  40955. renderer.getClearColor( _color4 );
  40956. _color4.getRGB( _color4 );
  40957. return _color4;
  40958. }
  40959. /**
  40960. * Returns the DOM element. If no DOM element exists, the backend
  40961. * creates a new one.
  40962. *
  40963. * @return {HTMLCanvasElement} The DOM element.
  40964. */
  40965. getDomElement() {
  40966. let domElement = this.domElement;
  40967. if ( domElement === null ) {
  40968. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  40969. // OffscreenCanvas does not have setAttribute, see #22811
  40970. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  40971. this.domElement = domElement;
  40972. }
  40973. return domElement;
  40974. }
  40975. /**
  40976. * Sets a dictionary for the given object into the
  40977. * internal data structure.
  40978. *
  40979. * @param {Object} object - The object.
  40980. * @param {Object} value - The dictionary to set.
  40981. */
  40982. set( object, value ) {
  40983. this.data.set( object, value );
  40984. }
  40985. /**
  40986. * Returns the dictionary for the given object.
  40987. *
  40988. * @param {Object} object - The object.
  40989. * @return {Object} The object's dictionary.
  40990. */
  40991. get( object ) {
  40992. let map = this.data.get( object );
  40993. if ( map === undefined ) {
  40994. map = {};
  40995. this.data.set( object, map );
  40996. }
  40997. return map;
  40998. }
  40999. /**
  41000. * Checks if the given object has a dictionary
  41001. * with data defined.
  41002. *
  41003. * @param {Object} object - The object.
  41004. * @return {boolean} Whether a dictionary for the given object as been defined or not.
  41005. */
  41006. has( object ) {
  41007. return this.data.has( object );
  41008. }
  41009. /**
  41010. * Deletes an object from the internal data structure.
  41011. *
  41012. * @param {Object} object - The object to delete.
  41013. */
  41014. delete( object ) {
  41015. this.data.delete( object );
  41016. }
  41017. /**
  41018. * Frees internal resources.
  41019. *
  41020. * @abstract
  41021. */
  41022. dispose() { }
  41023. }
  41024. let _id$1 = 0;
  41025. /**
  41026. * This module is internally used in context of compute shaders.
  41027. * This type of shader is not natively supported in WebGL 2 and
  41028. * thus implemented via Transform Feedback. `DualAttributeData`
  41029. * manages the related data.
  41030. *
  41031. * @private
  41032. */
  41033. class DualAttributeData {
  41034. constructor( attributeData, dualBuffer ) {
  41035. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  41036. this.type = attributeData.type;
  41037. this.bufferType = attributeData.bufferType;
  41038. this.pbo = attributeData.pbo;
  41039. this.byteLength = attributeData.byteLength;
  41040. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  41041. this.version = attributeData.version;
  41042. this.isInteger = attributeData.isInteger;
  41043. this.activeBufferIndex = 0;
  41044. this.baseId = attributeData.id;
  41045. }
  41046. get id() {
  41047. return `${ this.baseId }|${ this.activeBufferIndex }`;
  41048. }
  41049. get bufferGPU() {
  41050. return this.buffers[ this.activeBufferIndex ];
  41051. }
  41052. get transformBuffer() {
  41053. return this.buffers[ this.activeBufferIndex ^ 1 ];
  41054. }
  41055. switchBuffers() {
  41056. this.activeBufferIndex ^= 1;
  41057. }
  41058. }
  41059. /**
  41060. * A WebGL 2 backend utility module for managing shader attributes.
  41061. *
  41062. * @private
  41063. */
  41064. class WebGLAttributeUtils {
  41065. /**
  41066. * Constructs a new utility object.
  41067. *
  41068. * @param {WebGLBackend} backend - The WebGL 2 backend.
  41069. */
  41070. constructor( backend ) {
  41071. /**
  41072. * A reference to the WebGL 2 backend.
  41073. *
  41074. * @type {WebGLBackend}
  41075. */
  41076. this.backend = backend;
  41077. }
  41078. /**
  41079. * Creates the GPU buffer for the given buffer attribute.
  41080. *
  41081. * @param {BufferAttribute} attribute - The buffer attribute.
  41082. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  41083. */
  41084. createAttribute( attribute, bufferType ) {
  41085. const backend = this.backend;
  41086. const { gl } = backend;
  41087. const array = attribute.array;
  41088. const usage = attribute.usage || gl.STATIC_DRAW;
  41089. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  41090. const bufferData = backend.get( bufferAttribute );
  41091. let bufferGPU = bufferData.bufferGPU;
  41092. if ( bufferGPU === undefined ) {
  41093. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  41094. bufferData.bufferGPU = bufferGPU;
  41095. bufferData.bufferType = bufferType;
  41096. bufferData.version = bufferAttribute.version;
  41097. }
  41098. //attribute.onUploadCallback();
  41099. let type;
  41100. if ( array instanceof Float32Array ) {
  41101. type = gl.FLOAT;
  41102. } else if ( array instanceof Uint16Array ) {
  41103. if ( attribute.isFloat16BufferAttribute ) {
  41104. type = gl.HALF_FLOAT;
  41105. } else {
  41106. type = gl.UNSIGNED_SHORT;
  41107. }
  41108. } else if ( array instanceof Int16Array ) {
  41109. type = gl.SHORT;
  41110. } else if ( array instanceof Uint32Array ) {
  41111. type = gl.UNSIGNED_INT;
  41112. } else if ( array instanceof Int32Array ) {
  41113. type = gl.INT;
  41114. } else if ( array instanceof Int8Array ) {
  41115. type = gl.BYTE;
  41116. } else if ( array instanceof Uint8Array ) {
  41117. type = gl.UNSIGNED_BYTE;
  41118. } else if ( array instanceof Uint8ClampedArray ) {
  41119. type = gl.UNSIGNED_BYTE;
  41120. } else {
  41121. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  41122. }
  41123. let attributeData = {
  41124. bufferGPU,
  41125. bufferType,
  41126. type,
  41127. byteLength: array.byteLength,
  41128. bytesPerElement: array.BYTES_PER_ELEMENT,
  41129. version: attribute.version,
  41130. pbo: attribute.pbo,
  41131. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType,
  41132. id: _id$1 ++
  41133. };
  41134. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  41135. // create buffer for transform feedback use
  41136. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  41137. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  41138. }
  41139. backend.set( attribute, attributeData );
  41140. }
  41141. /**
  41142. * Updates the GPU buffer of the given buffer attribute.
  41143. *
  41144. * @param {BufferAttribute} attribute - The buffer attribute.
  41145. */
  41146. updateAttribute( attribute ) {
  41147. const backend = this.backend;
  41148. const { gl } = backend;
  41149. const array = attribute.array;
  41150. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  41151. const bufferData = backend.get( bufferAttribute );
  41152. const bufferType = bufferData.bufferType;
  41153. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  41154. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  41155. if ( updateRanges.length === 0 ) {
  41156. // Not using update ranges
  41157. gl.bufferSubData( bufferType, 0, array );
  41158. } else {
  41159. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  41160. const range = updateRanges[ i ];
  41161. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  41162. array, range.start, range.count );
  41163. }
  41164. bufferAttribute.clearUpdateRanges();
  41165. }
  41166. gl.bindBuffer( bufferType, null );
  41167. bufferData.version = bufferAttribute.version;
  41168. }
  41169. /**
  41170. * Destroys the GPU buffer of the given buffer attribute.
  41171. *
  41172. * @param {BufferAttribute} attribute - The buffer attribute.
  41173. */
  41174. destroyAttribute( attribute ) {
  41175. const backend = this.backend;
  41176. const { gl } = backend;
  41177. if ( attribute.isInterleavedBufferAttribute ) {
  41178. backend.delete( attribute.data );
  41179. }
  41180. const attributeData = backend.get( attribute );
  41181. gl.deleteBuffer( attributeData.bufferGPU );
  41182. backend.delete( attribute );
  41183. }
  41184. /**
  41185. * This method performs a readback operation by moving buffer data from
  41186. * a storage buffer attribute from the GPU to the CPU.
  41187. *
  41188. * @async
  41189. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  41190. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  41191. */
  41192. async getArrayBufferAsync( attribute ) {
  41193. const backend = this.backend;
  41194. const { gl } = backend;
  41195. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  41196. const { bufferGPU } = backend.get( bufferAttribute );
  41197. const array = attribute.array;
  41198. const byteLength = array.byteLength;
  41199. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  41200. const writeBuffer = gl.createBuffer();
  41201. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  41202. gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ );
  41203. gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength );
  41204. await backend.utils._clientWaitAsync();
  41205. const dstBuffer = new attribute.array.constructor( array.length );
  41206. // Ensure the buffer is bound before reading
  41207. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  41208. gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer );
  41209. gl.deleteBuffer( writeBuffer );
  41210. gl.bindBuffer( gl.COPY_READ_BUFFER, null );
  41211. gl.bindBuffer( gl.COPY_WRITE_BUFFER, null );
  41212. return dstBuffer.buffer;
  41213. }
  41214. /**
  41215. * Creates a WebGL buffer with the given data.
  41216. *
  41217. * @private
  41218. * @param {WebGL2RenderingContext} gl - The rendering context.
  41219. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  41220. * @param {TypedArray} array - The array of the buffer attribute.
  41221. * @param {GLenum} usage - The usage.
  41222. * @return {WebGLBuffer} The WebGL buffer.
  41223. */
  41224. _createBuffer( gl, bufferType, array, usage ) {
  41225. const bufferGPU = gl.createBuffer();
  41226. gl.bindBuffer( bufferType, bufferGPU );
  41227. gl.bufferData( bufferType, array, usage );
  41228. gl.bindBuffer( bufferType, null );
  41229. return bufferGPU;
  41230. }
  41231. }
  41232. let equationToGL, factorToGL;
  41233. /**
  41234. * A WebGL 2 backend utility module for managing the WebGL state.
  41235. *
  41236. * The major goal of this module is to reduce the number of state changes
  41237. * by caching the WEbGL state with a series of variables. In this way, the
  41238. * renderer only executes state change commands when necessary which
  41239. * improves the overall performance.
  41240. *
  41241. * @private
  41242. */
  41243. class WebGLState {
  41244. /**
  41245. * Constructs a new utility object.
  41246. *
  41247. * @param {WebGLBackend} backend - The WebGL 2 backend.
  41248. */
  41249. constructor( backend ) {
  41250. /**
  41251. * A reference to the WebGL 2 backend.
  41252. *
  41253. * @type {WebGLBackend}
  41254. */
  41255. this.backend = backend;
  41256. /**
  41257. * A reference to the rendering context.
  41258. *
  41259. * @type {WebGL2RenderingContext}
  41260. */
  41261. this.gl = this.backend.gl;
  41262. // Below properties are intended to cache
  41263. // the WebGL state and are not explicitly
  41264. // documented for convenience reasons.
  41265. this.enabled = {};
  41266. this.currentFlipSided = null;
  41267. this.currentCullFace = null;
  41268. this.currentProgram = null;
  41269. this.currentBlendingEnabled = false;
  41270. this.currentBlending = null;
  41271. this.currentBlendSrc = null;
  41272. this.currentBlendDst = null;
  41273. this.currentBlendSrcAlpha = null;
  41274. this.currentBlendDstAlpha = null;
  41275. this.currentPremultipledAlpha = null;
  41276. this.currentPolygonOffsetFactor = null;
  41277. this.currentPolygonOffsetUnits = null;
  41278. this.currentColorMask = null;
  41279. this.currentDepthFunc = null;
  41280. this.currentDepthMask = null;
  41281. this.currentStencilFunc = null;
  41282. this.currentStencilRef = null;
  41283. this.currentStencilFuncMask = null;
  41284. this.currentStencilFail = null;
  41285. this.currentStencilZFail = null;
  41286. this.currentStencilZPass = null;
  41287. this.currentStencilMask = null;
  41288. this.currentLineWidth = null;
  41289. this.currentClippingPlanes = 0;
  41290. this.currentVAO = null;
  41291. this.currentIndex = null;
  41292. this.currentBoundFramebuffers = {};
  41293. this.currentDrawbuffers = new WeakMap();
  41294. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  41295. this.currentTextureSlot = null;
  41296. this.currentBoundTextures = {};
  41297. this.currentBoundBufferBases = {};
  41298. this._init();
  41299. }
  41300. /**
  41301. * Inits the state of the utility.
  41302. *
  41303. * @private
  41304. */
  41305. _init() {
  41306. const gl = this.gl;
  41307. // Store only WebGL constants here.
  41308. equationToGL = {
  41309. [ AddEquation ]: gl.FUNC_ADD,
  41310. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  41311. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  41312. };
  41313. factorToGL = {
  41314. [ ZeroFactor ]: gl.ZERO,
  41315. [ OneFactor ]: gl.ONE,
  41316. [ SrcColorFactor ]: gl.SRC_COLOR,
  41317. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  41318. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  41319. [ DstColorFactor ]: gl.DST_COLOR,
  41320. [ DstAlphaFactor ]: gl.DST_ALPHA,
  41321. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  41322. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  41323. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  41324. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  41325. };
  41326. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  41327. const viewportParam = gl.getParameter( gl.VIEWPORT );
  41328. this.currentScissor = new Vector4().fromArray( scissorParam );
  41329. this.currentViewport = new Vector4().fromArray( viewportParam );
  41330. this._tempVec4 = new Vector4();
  41331. }
  41332. /**
  41333. * Enables the given WebGL capability.
  41334. *
  41335. * This method caches the capability state so
  41336. * `gl.enable()` is only called when necessary.
  41337. *
  41338. * @param {GLenum} id - The capability to enable.
  41339. */
  41340. enable( id ) {
  41341. const { enabled } = this;
  41342. if ( enabled[ id ] !== true ) {
  41343. this.gl.enable( id );
  41344. enabled[ id ] = true;
  41345. }
  41346. }
  41347. /**
  41348. * Disables the given WebGL capability.
  41349. *
  41350. * This method caches the capability state so
  41351. * `gl.disable()` is only called when necessary.
  41352. *
  41353. * @param {GLenum} id - The capability to enable.
  41354. */
  41355. disable( id ) {
  41356. const { enabled } = this;
  41357. if ( enabled[ id ] !== false ) {
  41358. this.gl.disable( id );
  41359. enabled[ id ] = false;
  41360. }
  41361. }
  41362. /**
  41363. * Specifies whether polygons are front- or back-facing
  41364. * by setting the winding orientation.
  41365. *
  41366. * This method caches the state so `gl.frontFace()` is only
  41367. * called when necessary.
  41368. *
  41369. * @param {boolean} flipSided - Whether triangles flipped their sides or not.
  41370. */
  41371. setFlipSided( flipSided ) {
  41372. if ( this.currentFlipSided !== flipSided ) {
  41373. const { gl } = this;
  41374. if ( flipSided ) {
  41375. gl.frontFace( gl.CW );
  41376. } else {
  41377. gl.frontFace( gl.CCW );
  41378. }
  41379. this.currentFlipSided = flipSided;
  41380. }
  41381. }
  41382. /**
  41383. * Specifies whether or not front- and/or back-facing
  41384. * polygons can be culled.
  41385. *
  41386. * This method caches the state so `gl.cullFace()` is only
  41387. * called when necessary.
  41388. *
  41389. * @param {number} cullFace - Defines which polygons are candidates for culling.
  41390. */
  41391. setCullFace( cullFace ) {
  41392. const { gl } = this;
  41393. if ( cullFace !== CullFaceNone ) {
  41394. this.enable( gl.CULL_FACE );
  41395. if ( cullFace !== this.currentCullFace ) {
  41396. if ( cullFace === CullFaceBack ) {
  41397. gl.cullFace( gl.BACK );
  41398. } else if ( cullFace === CullFaceFront ) {
  41399. gl.cullFace( gl.FRONT );
  41400. } else {
  41401. gl.cullFace( gl.FRONT_AND_BACK );
  41402. }
  41403. }
  41404. } else {
  41405. this.disable( gl.CULL_FACE );
  41406. }
  41407. this.currentCullFace = cullFace;
  41408. }
  41409. /**
  41410. * Specifies the width of line primitives.
  41411. *
  41412. * This method caches the state so `gl.lineWidth()` is only
  41413. * called when necessary.
  41414. *
  41415. * @param {number} width - The line width.
  41416. */
  41417. setLineWidth( width ) {
  41418. const { currentLineWidth, gl } = this;
  41419. if ( width !== currentLineWidth ) {
  41420. gl.lineWidth( width );
  41421. this.currentLineWidth = width;
  41422. }
  41423. }
  41424. /**
  41425. * Defines the blending.
  41426. *
  41427. * This method caches the state so `gl.blendEquation()`, `gl.blendEquationSeparate()`,
  41428. * `gl.blendFunc()` and `gl.blendFuncSeparate()` are only called when necessary.
  41429. *
  41430. * @param {number} blending - The blending type.
  41431. * @param {number} blendEquation - The blending equation.
  41432. * @param {number} blendSrc - Only relevant for custom blending. The RGB source blending factor.
  41433. * @param {number} blendDst - Only relevant for custom blending. The RGB destination blending factor.
  41434. * @param {number} blendEquationAlpha - Only relevant for custom blending. The blending equation for alpha.
  41435. * @param {number} blendSrcAlpha - Only relevant for custom blending. The alpha source blending factor.
  41436. * @param {number} blendDstAlpha - Only relevant for custom blending. The alpha destination blending factor.
  41437. * @param {boolean} premultipliedAlpha - Whether premultiplied alpha is enabled or not.
  41438. */
  41439. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  41440. const { gl } = this;
  41441. if ( blending === NoBlending ) {
  41442. if ( this.currentBlendingEnabled === true ) {
  41443. this.disable( gl.BLEND );
  41444. this.currentBlendingEnabled = false;
  41445. }
  41446. return;
  41447. }
  41448. if ( this.currentBlendingEnabled === false ) {
  41449. this.enable( gl.BLEND );
  41450. this.currentBlendingEnabled = true;
  41451. }
  41452. if ( blending !== CustomBlending ) {
  41453. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  41454. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  41455. gl.blendEquation( gl.FUNC_ADD );
  41456. this.currentBlendEquation = AddEquation;
  41457. this.currentBlendEquationAlpha = AddEquation;
  41458. }
  41459. if ( premultipliedAlpha ) {
  41460. switch ( blending ) {
  41461. case NormalBlending:
  41462. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  41463. break;
  41464. case AdditiveBlending:
  41465. gl.blendFunc( gl.ONE, gl.ONE );
  41466. break;
  41467. case SubtractiveBlending:
  41468. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  41469. break;
  41470. case MultiplyBlending:
  41471. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  41472. break;
  41473. default:
  41474. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  41475. break;
  41476. }
  41477. } else {
  41478. switch ( blending ) {
  41479. case NormalBlending:
  41480. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  41481. break;
  41482. case AdditiveBlending:
  41483. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  41484. break;
  41485. case SubtractiveBlending:
  41486. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  41487. break;
  41488. case MultiplyBlending:
  41489. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  41490. break;
  41491. default:
  41492. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  41493. break;
  41494. }
  41495. }
  41496. this.currentBlendSrc = null;
  41497. this.currentBlendDst = null;
  41498. this.currentBlendSrcAlpha = null;
  41499. this.currentBlendDstAlpha = null;
  41500. this.currentBlending = blending;
  41501. this.currentPremultipledAlpha = premultipliedAlpha;
  41502. }
  41503. return;
  41504. }
  41505. // custom blending
  41506. blendEquationAlpha = blendEquationAlpha || blendEquation;
  41507. blendSrcAlpha = blendSrcAlpha || blendSrc;
  41508. blendDstAlpha = blendDstAlpha || blendDst;
  41509. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  41510. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  41511. this.currentBlendEquation = blendEquation;
  41512. this.currentBlendEquationAlpha = blendEquationAlpha;
  41513. }
  41514. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  41515. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  41516. this.currentBlendSrc = blendSrc;
  41517. this.currentBlendDst = blendDst;
  41518. this.currentBlendSrcAlpha = blendSrcAlpha;
  41519. this.currentBlendDstAlpha = blendDstAlpha;
  41520. }
  41521. this.currentBlending = blending;
  41522. this.currentPremultipledAlpha = false;
  41523. }
  41524. /**
  41525. * Specifies whether colors can be written when rendering
  41526. * into a framebuffer or not.
  41527. *
  41528. * This method caches the state so `gl.colorMask()` is only
  41529. * called when necessary.
  41530. *
  41531. * @param {boolean} colorMask - The color mask.
  41532. */
  41533. setColorMask( colorMask ) {
  41534. if ( this.currentColorMask !== colorMask ) {
  41535. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  41536. this.currentColorMask = colorMask;
  41537. }
  41538. }
  41539. /**
  41540. * Specifies whether the depth test is enabled or not.
  41541. *
  41542. * @param {boolean} depthTest - Whether the depth test is enabled or not.
  41543. */
  41544. setDepthTest( depthTest ) {
  41545. const { gl } = this;
  41546. if ( depthTest ) {
  41547. this.enable( gl.DEPTH_TEST );
  41548. } else {
  41549. this.disable( gl.DEPTH_TEST );
  41550. }
  41551. }
  41552. /**
  41553. * Specifies whether depth values can be written when rendering
  41554. * into a framebuffer or not.
  41555. *
  41556. * This method caches the state so `gl.depthMask()` is only
  41557. * called when necessary.
  41558. *
  41559. * @param {boolean} depthMask - The depth mask.
  41560. */
  41561. setDepthMask( depthMask ) {
  41562. if ( this.currentDepthMask !== depthMask ) {
  41563. this.gl.depthMask( depthMask );
  41564. this.currentDepthMask = depthMask;
  41565. }
  41566. }
  41567. /**
  41568. * Specifies the depth compare function.
  41569. *
  41570. * This method caches the state so `gl.depthFunc()` is only
  41571. * called when necessary.
  41572. *
  41573. * @param {number} depthFunc - The depth compare function.
  41574. */
  41575. setDepthFunc( depthFunc ) {
  41576. if ( this.currentDepthFunc !== depthFunc ) {
  41577. const { gl } = this;
  41578. switch ( depthFunc ) {
  41579. case NeverDepth:
  41580. gl.depthFunc( gl.NEVER );
  41581. break;
  41582. case AlwaysDepth:
  41583. gl.depthFunc( gl.ALWAYS );
  41584. break;
  41585. case LessDepth:
  41586. gl.depthFunc( gl.LESS );
  41587. break;
  41588. case LessEqualDepth:
  41589. gl.depthFunc( gl.LEQUAL );
  41590. break;
  41591. case EqualDepth:
  41592. gl.depthFunc( gl.EQUAL );
  41593. break;
  41594. case GreaterEqualDepth:
  41595. gl.depthFunc( gl.GEQUAL );
  41596. break;
  41597. case GreaterDepth:
  41598. gl.depthFunc( gl.GREATER );
  41599. break;
  41600. case NotEqualDepth:
  41601. gl.depthFunc( gl.NOTEQUAL );
  41602. break;
  41603. default:
  41604. gl.depthFunc( gl.LEQUAL );
  41605. }
  41606. this.currentDepthFunc = depthFunc;
  41607. }
  41608. }
  41609. /**
  41610. * Specifies the scissor box.
  41611. *
  41612. * @param {number} x - The x-coordinate of the lower left corner of the viewport.
  41613. * @param {number} y - The y-coordinate of the lower left corner of the viewport.
  41614. * @param {number} width - The width of the viewport.
  41615. * @param {number} height - The height of the viewport.
  41616. *
  41617. */
  41618. scissor( x, y, width, height ) {
  41619. const scissor = this._tempVec4.set( x, y, width, height );
  41620. if ( this.currentScissor.equals( scissor ) === false ) {
  41621. const { gl } = this;
  41622. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  41623. this.currentScissor.copy( scissor );
  41624. }
  41625. }
  41626. /**
  41627. * Specifies the viewport.
  41628. *
  41629. * @param {number} x - The x-coordinate of the lower left corner of the viewport.
  41630. * @param {number} y - The y-coordinate of the lower left corner of the viewport.
  41631. * @param {number} width - The width of the viewport.
  41632. * @param {number} height - The height of the viewport.
  41633. *
  41634. */
  41635. viewport( x, y, width, height ) {
  41636. const viewport = this._tempVec4.set( x, y, width, height );
  41637. if ( this.currentViewport.equals( viewport ) === false ) {
  41638. const { gl } = this;
  41639. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  41640. this.currentViewport.copy( viewport );
  41641. }
  41642. }
  41643. /**
  41644. * Defines the scissor test.
  41645. *
  41646. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  41647. */
  41648. setScissorTest( boolean ) {
  41649. const gl = this.gl;
  41650. if ( boolean ) {
  41651. gl.enable( gl.SCISSOR_TEST );
  41652. } else {
  41653. gl.disable( gl.SCISSOR_TEST );
  41654. }
  41655. }
  41656. /**
  41657. * Specifies whether the stencil test is enabled or not.
  41658. *
  41659. * @param {boolean} stencilTest - Whether the stencil test is enabled or not.
  41660. */
  41661. setStencilTest( stencilTest ) {
  41662. const { gl } = this;
  41663. if ( stencilTest ) {
  41664. this.enable( gl.STENCIL_TEST );
  41665. } else {
  41666. this.disable( gl.STENCIL_TEST );
  41667. }
  41668. }
  41669. /**
  41670. * Specifies whether stencil values can be written when rendering
  41671. * into a framebuffer or not.
  41672. *
  41673. * This method caches the state so `gl.stencilMask()` is only
  41674. * called when necessary.
  41675. *
  41676. * @param {boolean} stencilMask - The stencil mask.
  41677. */
  41678. setStencilMask( stencilMask ) {
  41679. if ( this.currentStencilMask !== stencilMask ) {
  41680. this.gl.stencilMask( stencilMask );
  41681. this.currentStencilMask = stencilMask;
  41682. }
  41683. }
  41684. /**
  41685. * Specifies whether the stencil test functions.
  41686. *
  41687. * This method caches the state so `gl.stencilFunc()` is only
  41688. * called when necessary.
  41689. *
  41690. * @param {number} stencilFunc - The stencil compare function.
  41691. * @param {number} stencilRef - The reference value for the stencil test.
  41692. * @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.
  41693. */
  41694. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  41695. if ( this.currentStencilFunc !== stencilFunc ||
  41696. this.currentStencilRef !== stencilRef ||
  41697. this.currentStencilFuncMask !== stencilMask ) {
  41698. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  41699. this.currentStencilFunc = stencilFunc;
  41700. this.currentStencilRef = stencilRef;
  41701. this.currentStencilFuncMask = stencilMask;
  41702. }
  41703. }
  41704. /**
  41705. * Specifies whether the stencil test operation.
  41706. *
  41707. * This method caches the state so `gl.stencilOp()` is only
  41708. * called when necessary.
  41709. *
  41710. * @param {number} stencilFail - The function to use when the stencil test fails.
  41711. * @param {number} stencilZFail - The function to use when the stencil test passes, but the depth test fail.
  41712. * @param {number} stencilZPass - The function to use when both the stencil test and the depth test pass,
  41713. * or when the stencil test passes and there is no depth buffer or depth testing is disabled.
  41714. */
  41715. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  41716. if ( this.currentStencilFail !== stencilFail ||
  41717. this.currentStencilZFail !== stencilZFail ||
  41718. this.currentStencilZPass !== stencilZPass ) {
  41719. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  41720. this.currentStencilFail = stencilFail;
  41721. this.currentStencilZFail = stencilZFail;
  41722. this.currentStencilZPass = stencilZPass;
  41723. }
  41724. }
  41725. /**
  41726. * Configures the WebGL state for the given material.
  41727. *
  41728. * @param {Material} material - The material to configure the state for.
  41729. * @param {number} frontFaceCW - Whether the front faces are counter-clockwise or not.
  41730. * @param {number} hardwareClippingPlanes - The number of hardware clipping planes.
  41731. */
  41732. setMaterial( material, frontFaceCW, hardwareClippingPlanes ) {
  41733. const { gl } = this;
  41734. material.side === DoubleSide
  41735. ? this.disable( gl.CULL_FACE )
  41736. : this.enable( gl.CULL_FACE );
  41737. let flipSided = ( material.side === BackSide );
  41738. if ( frontFaceCW ) flipSided = ! flipSided;
  41739. this.setFlipSided( flipSided );
  41740. ( material.blending === NormalBlending && material.transparent === false )
  41741. ? this.setBlending( NoBlending )
  41742. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  41743. this.setDepthFunc( material.depthFunc );
  41744. this.setDepthTest( material.depthTest );
  41745. this.setDepthMask( material.depthWrite );
  41746. this.setColorMask( material.colorWrite );
  41747. const stencilWrite = material.stencilWrite;
  41748. this.setStencilTest( stencilWrite );
  41749. if ( stencilWrite ) {
  41750. this.setStencilMask( material.stencilWriteMask );
  41751. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  41752. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  41753. }
  41754. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  41755. material.alphaToCoverage === true && this.backend.renderer.samples > 1
  41756. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  41757. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  41758. if ( hardwareClippingPlanes > 0 ) {
  41759. if ( this.currentClippingPlanes !== hardwareClippingPlanes ) {
  41760. const CLIP_DISTANCE0_WEBGL = 0x3000;
  41761. for ( let i = 0; i < 8; i ++ ) {
  41762. if ( i < hardwareClippingPlanes ) {
  41763. this.enable( CLIP_DISTANCE0_WEBGL + i );
  41764. } else {
  41765. this.disable( CLIP_DISTANCE0_WEBGL + i );
  41766. }
  41767. }
  41768. }
  41769. }
  41770. }
  41771. /**
  41772. * Specifies the polygon offset.
  41773. *
  41774. * This method caches the state so `gl.polygonOffset()` is only
  41775. * called when necessary.
  41776. *
  41777. * @param {boolean} polygonOffset - Whether polygon offset is enabled or not.
  41778. * @param {number} factor - The scale factor for the variable depth offset for each polygon.
  41779. * @param {number} units - The multiplier by which an implementation-specific value is multiplied with to create a constant depth offset.
  41780. */
  41781. setPolygonOffset( polygonOffset, factor, units ) {
  41782. const { gl } = this;
  41783. if ( polygonOffset ) {
  41784. this.enable( gl.POLYGON_OFFSET_FILL );
  41785. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  41786. gl.polygonOffset( factor, units );
  41787. this.currentPolygonOffsetFactor = factor;
  41788. this.currentPolygonOffsetUnits = units;
  41789. }
  41790. } else {
  41791. this.disable( gl.POLYGON_OFFSET_FILL );
  41792. }
  41793. }
  41794. /**
  41795. * Defines the usage of the given WebGL program.
  41796. *
  41797. * This method caches the state so `gl.useProgram()` is only
  41798. * called when necessary.
  41799. *
  41800. * @param {WebGLProgram} program - The WebGL program to use.
  41801. * @return {boolean} Whether a program change has been executed or not.
  41802. */
  41803. useProgram( program ) {
  41804. if ( this.currentProgram !== program ) {
  41805. this.gl.useProgram( program );
  41806. this.currentProgram = program;
  41807. return true;
  41808. }
  41809. return false;
  41810. }
  41811. /**
  41812. * Sets the vertex state by binding the given VAO and element buffer.
  41813. *
  41814. * @param {WebGLVertexArrayObject} vao - The VAO.
  41815. * @param {WebGLBuffer} indexBuffer - The index buffer.
  41816. * @return {boolean} Whether a vertex state has been changed or not.
  41817. */
  41818. setVertexState( vao, indexBuffer = null ) {
  41819. const gl = this.gl;
  41820. if ( this.currentVAO !== vao || this.currentIndex !== indexBuffer ) {
  41821. gl.bindVertexArray( vao );
  41822. if ( indexBuffer !== null ) {
  41823. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexBuffer );
  41824. }
  41825. this.currentVAO = vao;
  41826. this.currentIndex = indexBuffer;
  41827. return true;
  41828. }
  41829. return false;
  41830. }
  41831. /**
  41832. * Resets the vertex array state by resetting the VAO and element buffer.
  41833. */
  41834. resetVertexState() {
  41835. const gl = this.gl;
  41836. gl.bindVertexArray( null );
  41837. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, null );
  41838. this.currentVAO = null;
  41839. this.currentIndex = null;
  41840. }
  41841. // framebuffer
  41842. /**
  41843. * Binds the given framebuffer.
  41844. *
  41845. * This method caches the state so `gl.bindFramebuffer()` is only
  41846. * called when necessary.
  41847. *
  41848. * @param {number} target - The binding point (target).
  41849. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer to bind.
  41850. * @return {boolean} Whether a bind has been executed or not.
  41851. */
  41852. bindFramebuffer( target, framebuffer ) {
  41853. const { gl, currentBoundFramebuffers } = this;
  41854. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  41855. gl.bindFramebuffer( target, framebuffer );
  41856. currentBoundFramebuffers[ target ] = framebuffer;
  41857. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  41858. if ( target === gl.DRAW_FRAMEBUFFER ) {
  41859. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  41860. }
  41861. if ( target === gl.FRAMEBUFFER ) {
  41862. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  41863. }
  41864. return true;
  41865. }
  41866. return false;
  41867. }
  41868. /**
  41869. * Defines draw buffers to which fragment colors are written into.
  41870. * Configures the MRT setup of custom framebuffers.
  41871. *
  41872. * This method caches the state so `gl.drawBuffers()` is only
  41873. * called when necessary.
  41874. *
  41875. * @param {RenderContext} renderContext - The render context.
  41876. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer.
  41877. */
  41878. drawBuffers( renderContext, framebuffer ) {
  41879. const { gl } = this;
  41880. let drawBuffers = [];
  41881. let needsUpdate = false;
  41882. if ( renderContext.textures !== null ) {
  41883. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  41884. if ( drawBuffers === undefined ) {
  41885. drawBuffers = [];
  41886. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  41887. }
  41888. const textures = renderContext.textures;
  41889. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  41890. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  41891. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  41892. }
  41893. drawBuffers.length = textures.length;
  41894. needsUpdate = true;
  41895. }
  41896. } else {
  41897. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  41898. drawBuffers[ 0 ] = gl.BACK;
  41899. needsUpdate = true;
  41900. }
  41901. }
  41902. if ( needsUpdate ) {
  41903. gl.drawBuffers( drawBuffers );
  41904. }
  41905. }
  41906. // texture
  41907. /**
  41908. * Makes the given texture unit active.
  41909. *
  41910. * This method caches the state so `gl.activeTexture()` is only
  41911. * called when necessary.
  41912. *
  41913. * @param {number} webglSlot - The texture unit to make active.
  41914. */
  41915. activeTexture( webglSlot ) {
  41916. const { gl, currentTextureSlot, maxTextures } = this;
  41917. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  41918. if ( currentTextureSlot !== webglSlot ) {
  41919. gl.activeTexture( webglSlot );
  41920. this.currentTextureSlot = webglSlot;
  41921. }
  41922. }
  41923. /**
  41924. * Binds the given WebGL texture to a target.
  41925. *
  41926. * This method caches the state so `gl.bindTexture()` is only
  41927. * called when necessary.
  41928. *
  41929. * @param {number} webglType - The binding point (target).
  41930. * @param {WebGLTexture} webglTexture - The WebGL texture to bind.
  41931. * @param {number} webglSlot - The texture.
  41932. */
  41933. bindTexture( webglType, webglTexture, webglSlot ) {
  41934. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  41935. if ( webglSlot === undefined ) {
  41936. if ( currentTextureSlot === null ) {
  41937. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  41938. } else {
  41939. webglSlot = currentTextureSlot;
  41940. }
  41941. }
  41942. let boundTexture = currentBoundTextures[ webglSlot ];
  41943. if ( boundTexture === undefined ) {
  41944. boundTexture = { type: undefined, texture: undefined };
  41945. currentBoundTextures[ webglSlot ] = boundTexture;
  41946. }
  41947. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  41948. if ( currentTextureSlot !== webglSlot ) {
  41949. gl.activeTexture( webglSlot );
  41950. this.currentTextureSlot = webglSlot;
  41951. }
  41952. gl.bindTexture( webglType, webglTexture );
  41953. boundTexture.type = webglType;
  41954. boundTexture.texture = webglTexture;
  41955. }
  41956. }
  41957. /**
  41958. * Binds a given WebGL buffer to a given binding point (target) at a given index.
  41959. *
  41960. * This method caches the state so `gl.bindBufferBase()` is only
  41961. * called when necessary.
  41962. *
  41963. * @param {number} target - The target for the bind operation.
  41964. * @param {number} index - The index of the target.
  41965. * @param {WebGLBuffer} buffer - The WebGL buffer.
  41966. * @return {boolean} Whether a bind has been executed or not.
  41967. */
  41968. bindBufferBase( target, index, buffer ) {
  41969. const { gl } = this;
  41970. const key = `${target}-${index}`;
  41971. if ( this.currentBoundBufferBases[ key ] !== buffer ) {
  41972. gl.bindBufferBase( target, index, buffer );
  41973. this.currentBoundBufferBases[ key ] = buffer;
  41974. return true;
  41975. }
  41976. return false;
  41977. }
  41978. /**
  41979. * Unbinds the current bound texture.
  41980. *
  41981. * This method caches the state so `gl.bindTexture()` is only
  41982. * called when necessary.
  41983. */
  41984. unbindTexture() {
  41985. const { gl, currentTextureSlot, currentBoundTextures } = this;
  41986. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  41987. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  41988. gl.bindTexture( boundTexture.type, null );
  41989. boundTexture.type = undefined;
  41990. boundTexture.texture = undefined;
  41991. }
  41992. }
  41993. }
  41994. /**
  41995. * A WebGL 2 backend utility module with common helpers.
  41996. *
  41997. * @private
  41998. */
  41999. class WebGLUtils {
  42000. /**
  42001. * Constructs a new utility object.
  42002. *
  42003. * @param {WebGLBackend} backend - The WebGL 2 backend.
  42004. */
  42005. constructor( backend ) {
  42006. /**
  42007. * A reference to the WebGL 2 backend.
  42008. *
  42009. * @type {WebGLBackend}
  42010. */
  42011. this.backend = backend;
  42012. /**
  42013. * A reference to the rendering context.
  42014. *
  42015. * @type {WebGL2RenderingContext}
  42016. */
  42017. this.gl = this.backend.gl;
  42018. /**
  42019. * A reference to a backend module holding extension-related
  42020. * utility functions.
  42021. *
  42022. * @type {WebGLExtensions}
  42023. */
  42024. this.extensions = backend.extensions;
  42025. }
  42026. /**
  42027. * Converts the given three.js constant into a WebGL constant.
  42028. * The method currently supports the conversion of texture formats
  42029. * and types.
  42030. *
  42031. * @param {number} p - The three.js constant.
  42032. * @param {string} [colorSpace=NoColorSpace] - The color space.
  42033. * @return {?number} The corresponding WebGL constant.
  42034. */
  42035. convert( p, colorSpace = NoColorSpace ) {
  42036. const { gl, extensions } = this;
  42037. let extension;
  42038. const transfer = ColorManagement.getTransfer( colorSpace );
  42039. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  42040. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  42041. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  42042. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  42043. if ( p === ByteType ) return gl.BYTE;
  42044. if ( p === ShortType ) return gl.SHORT;
  42045. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  42046. if ( p === IntType ) return gl.INT;
  42047. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  42048. if ( p === FloatType ) return gl.FLOAT;
  42049. if ( p === HalfFloatType ) {
  42050. return gl.HALF_FLOAT;
  42051. }
  42052. if ( p === AlphaFormat ) return gl.ALPHA;
  42053. if ( p === RGBFormat ) return gl.RGB;
  42054. if ( p === RGBAFormat ) return gl.RGBA;
  42055. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  42056. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  42057. // WebGL2 formats.
  42058. if ( p === RedFormat ) return gl.RED;
  42059. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  42060. if ( p === RGFormat ) return gl.RG;
  42061. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  42062. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  42063. // S3TC
  42064. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  42065. if ( transfer === SRGBTransfer ) {
  42066. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  42067. if ( extension !== null ) {
  42068. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  42069. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  42070. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  42071. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  42072. } else {
  42073. return null;
  42074. }
  42075. } else {
  42076. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  42077. if ( extension !== null ) {
  42078. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  42079. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  42080. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  42081. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  42082. } else {
  42083. return null;
  42084. }
  42085. }
  42086. }
  42087. // PVRTC
  42088. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  42089. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  42090. if ( extension !== null ) {
  42091. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  42092. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  42093. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  42094. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  42095. } else {
  42096. return null;
  42097. }
  42098. }
  42099. // ETC
  42100. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  42101. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  42102. if ( extension !== null ) {
  42103. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  42104. if ( p === RGBA_ETC2_EAC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  42105. } else {
  42106. return null;
  42107. }
  42108. }
  42109. // ASTC
  42110. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  42111. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  42112. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  42113. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  42114. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  42115. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  42116. if ( extension !== null ) {
  42117. if ( p === RGBA_ASTC_4x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  42118. if ( p === RGBA_ASTC_5x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  42119. if ( p === RGBA_ASTC_5x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  42120. if ( p === RGBA_ASTC_6x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  42121. if ( p === RGBA_ASTC_6x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  42122. if ( p === RGBA_ASTC_8x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  42123. if ( p === RGBA_ASTC_8x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  42124. if ( p === RGBA_ASTC_8x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  42125. if ( p === RGBA_ASTC_10x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  42126. if ( p === RGBA_ASTC_10x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  42127. if ( p === RGBA_ASTC_10x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  42128. if ( p === RGBA_ASTC_10x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  42129. if ( p === RGBA_ASTC_12x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  42130. if ( p === RGBA_ASTC_12x12_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  42131. } else {
  42132. return null;
  42133. }
  42134. }
  42135. // BPTC
  42136. if ( p === RGBA_BPTC_Format ) {
  42137. extension = extensions.get( 'EXT_texture_compression_bptc' );
  42138. if ( extension !== null ) {
  42139. if ( p === RGBA_BPTC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  42140. } else {
  42141. return null;
  42142. }
  42143. }
  42144. // RGTC
  42145. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  42146. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  42147. if ( extension !== null ) {
  42148. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  42149. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  42150. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  42151. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  42152. } else {
  42153. return null;
  42154. }
  42155. }
  42156. //
  42157. if ( p === UnsignedInt248Type ) {
  42158. return gl.UNSIGNED_INT_24_8;
  42159. }
  42160. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  42161. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  42162. }
  42163. /**
  42164. * This method can be used to synchronize the CPU with the GPU by waiting until
  42165. * ongoing GPU commands have been completed.
  42166. *
  42167. * @private
  42168. * @return {Promise} A promise that resolves when all ongoing GPU commands have been completed.
  42169. */
  42170. _clientWaitAsync() {
  42171. const { gl } = this;
  42172. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  42173. gl.flush();
  42174. return new Promise( ( resolve, reject ) => {
  42175. function test() {
  42176. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  42177. if ( res === gl.WAIT_FAILED ) {
  42178. gl.deleteSync( sync );
  42179. reject();
  42180. return;
  42181. }
  42182. if ( res === gl.TIMEOUT_EXPIRED ) {
  42183. requestAnimationFrame( test );
  42184. return;
  42185. }
  42186. gl.deleteSync( sync );
  42187. resolve();
  42188. }
  42189. test();
  42190. } );
  42191. }
  42192. }
  42193. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  42194. /**
  42195. * A WebGL 2 backend utility module for managing textures.
  42196. *
  42197. * @private
  42198. */
  42199. class WebGLTextureUtils {
  42200. /**
  42201. * Constructs a new utility object.
  42202. *
  42203. * @param {WebGLBackend} backend - The WebGL 2 backend.
  42204. */
  42205. constructor( backend ) {
  42206. /**
  42207. * A reference to the WebGL 2 backend.
  42208. *
  42209. * @type {WebGLBackend}
  42210. */
  42211. this.backend = backend;
  42212. /**
  42213. * A reference to the rendering context.
  42214. *
  42215. * @type {WebGL2RenderingContext}
  42216. */
  42217. this.gl = backend.gl;
  42218. /**
  42219. * A reference to a backend module holding extension-related
  42220. * utility functions.
  42221. *
  42222. * @type {WebGLExtensions}
  42223. */
  42224. this.extensions = backend.extensions;
  42225. /**
  42226. * A dictionary for managing default textures. The key
  42227. * is the binding point (target), the value the WEbGL texture object.
  42228. *
  42229. * @type {Object<GLenum,WebGLTexture>}
  42230. */
  42231. this.defaultTextures = {};
  42232. if ( initialized === false ) {
  42233. this._init();
  42234. initialized = true;
  42235. }
  42236. }
  42237. /**
  42238. * Inits the state of the utility.
  42239. *
  42240. * @private
  42241. */
  42242. _init() {
  42243. const gl = this.gl;
  42244. // Store only WebGL constants here.
  42245. wrappingToGL = {
  42246. [ RepeatWrapping ]: gl.REPEAT,
  42247. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  42248. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  42249. };
  42250. filterToGL = {
  42251. [ NearestFilter ]: gl.NEAREST,
  42252. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  42253. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  42254. [ LinearFilter ]: gl.LINEAR,
  42255. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  42256. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  42257. };
  42258. compareToGL = {
  42259. [ NeverCompare ]: gl.NEVER,
  42260. [ AlwaysCompare ]: gl.ALWAYS,
  42261. [ LessCompare ]: gl.LESS,
  42262. [ LessEqualCompare ]: gl.LEQUAL,
  42263. [ EqualCompare ]: gl.EQUAL,
  42264. [ GreaterEqualCompare ]: gl.GEQUAL,
  42265. [ GreaterCompare ]: gl.GREATER,
  42266. [ NotEqualCompare ]: gl.NOTEQUAL
  42267. };
  42268. }
  42269. /**
  42270. * Returns the native texture type for the given texture.
  42271. *
  42272. * @param {Texture} texture - The texture.
  42273. * @return {GLenum} The native texture type.
  42274. */
  42275. getGLTextureType( texture ) {
  42276. const { gl } = this;
  42277. let glTextureType;
  42278. if ( texture.isCubeTexture === true ) {
  42279. glTextureType = gl.TEXTURE_CUBE_MAP;
  42280. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  42281. glTextureType = gl.TEXTURE_2D_ARRAY;
  42282. } else if ( texture.isData3DTexture === true ) { // TODO: isCompressed3DTexture, wait for #26642
  42283. glTextureType = gl.TEXTURE_3D;
  42284. } else {
  42285. glTextureType = gl.TEXTURE_2D;
  42286. }
  42287. return glTextureType;
  42288. }
  42289. /**
  42290. * Returns the native texture type for the given texture.
  42291. *
  42292. * @param {?string} internalFormatName - The internal format name. When `null`, the internal format is derived from the subsequent parameters.
  42293. * @param {GLenum} glFormat - The WebGL format.
  42294. * @param {GLenum} glType - The WebGL type.
  42295. * @param {string} colorSpace - The texture's color space.
  42296. * @param {boolean} [forceLinearTransfer=false] - Whether to force a linear transfer or not.
  42297. * @return {GLenum} The internal format.
  42298. */
  42299. getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  42300. const { gl, extensions } = this;
  42301. if ( internalFormatName !== null ) {
  42302. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  42303. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  42304. }
  42305. let internalFormat = glFormat;
  42306. if ( glFormat === gl.RED ) {
  42307. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  42308. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  42309. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  42310. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16;
  42311. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  42312. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  42313. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  42314. if ( glType === gl.INT ) internalFormat = gl.R32I;
  42315. }
  42316. if ( glFormat === gl.RED_INTEGER ) {
  42317. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  42318. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  42319. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  42320. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  42321. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  42322. if ( glType === gl.INT ) internalFormat = gl.R32I;
  42323. }
  42324. if ( glFormat === gl.RG ) {
  42325. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  42326. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  42327. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  42328. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16;
  42329. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  42330. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  42331. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  42332. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  42333. }
  42334. if ( glFormat === gl.RG_INTEGER ) {
  42335. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  42336. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  42337. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  42338. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  42339. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  42340. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  42341. }
  42342. if ( glFormat === gl.RGB ) {
  42343. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  42344. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  42345. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  42346. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8;
  42347. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16;
  42348. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  42349. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  42350. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  42351. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  42352. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? gl.SRGB8 : gl.RGB8;
  42353. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  42354. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  42355. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  42356. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  42357. }
  42358. if ( glFormat === gl.RGB_INTEGER ) {
  42359. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  42360. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  42361. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  42362. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  42363. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  42364. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  42365. }
  42366. if ( glFormat === gl.RGBA ) {
  42367. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  42368. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  42369. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  42370. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8;
  42371. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16;
  42372. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  42373. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  42374. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  42375. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  42376. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  42377. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  42378. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  42379. }
  42380. if ( glFormat === gl.RGBA_INTEGER ) {
  42381. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  42382. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  42383. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  42384. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  42385. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  42386. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  42387. }
  42388. if ( glFormat === gl.DEPTH_COMPONENT ) {
  42389. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.DEPTH_COMPONENT16;
  42390. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH_COMPONENT24;
  42391. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  42392. }
  42393. if ( glFormat === gl.DEPTH_STENCIL ) {
  42394. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  42395. }
  42396. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  42397. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  42398. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  42399. extensions.get( 'EXT_color_buffer_float' );
  42400. }
  42401. return internalFormat;
  42402. }
  42403. /**
  42404. * Sets the texture parameters for the given texture.
  42405. *
  42406. * @param {GLenum} textureType - The texture type.
  42407. * @param {Texture} texture - The texture.
  42408. */
  42409. setTextureParameters( textureType, texture ) {
  42410. const { gl, extensions, backend } = this;
  42411. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  42412. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  42413. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? gl.NONE : gl.BROWSER_DEFAULT_WEBGL;
  42414. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  42415. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  42416. gl.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  42417. gl.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  42418. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  42419. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  42420. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  42421. // WebGL 2 does not support wrapping for depth 2D array textures
  42422. if ( ! texture.isArrayTexture ) {
  42423. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  42424. }
  42425. }
  42426. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  42427. const hasMipmaps = texture.mipmaps !== undefined && texture.mipmaps.length > 0;
  42428. // follow WebGPU backend mapping for texture filtering
  42429. const minFilter = texture.minFilter === LinearFilter && hasMipmaps ? LinearMipmapLinearFilter : texture.minFilter;
  42430. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  42431. if ( texture.compareFunction ) {
  42432. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  42433. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  42434. }
  42435. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  42436. if ( texture.magFilter === NearestFilter ) return;
  42437. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  42438. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  42439. if ( texture.anisotropy > 1 ) {
  42440. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  42441. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) );
  42442. }
  42443. }
  42444. }
  42445. /**
  42446. * Creates a default texture for the given texture that can be used
  42447. * as a placeholder until the actual texture is ready for usage.
  42448. *
  42449. * @param {Texture} texture - The texture to create a default texture for.
  42450. */
  42451. createDefaultTexture( texture ) {
  42452. const { gl, backend, defaultTextures } = this;
  42453. const glTextureType = this.getGLTextureType( texture );
  42454. let textureGPU = defaultTextures[ glTextureType ];
  42455. if ( textureGPU === undefined ) {
  42456. textureGPU = gl.createTexture();
  42457. backend.state.bindTexture( glTextureType, textureGPU );
  42458. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  42459. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  42460. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  42461. defaultTextures[ glTextureType ] = textureGPU;
  42462. }
  42463. backend.set( texture, {
  42464. textureGPU,
  42465. glTextureType,
  42466. isDefault: true
  42467. } );
  42468. }
  42469. /**
  42470. * Defines a texture on the GPU for the given texture object.
  42471. *
  42472. * @param {Texture} texture - The texture.
  42473. * @param {Object} [options={}] - Optional configuration parameter.
  42474. * @return {undefined}
  42475. */
  42476. createTexture( texture, options ) {
  42477. const { gl, backend } = this;
  42478. const { levels, width, height, depth } = options;
  42479. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  42480. const glType = backend.utils.convert( texture.type );
  42481. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  42482. const textureGPU = gl.createTexture();
  42483. const glTextureType = this.getGLTextureType( texture );
  42484. backend.state.bindTexture( glTextureType, textureGPU );
  42485. this.setTextureParameters( glTextureType, texture );
  42486. if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  42487. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  42488. } else if ( texture.isData3DTexture ) {
  42489. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  42490. } else if ( ! texture.isVideoTexture ) {
  42491. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  42492. }
  42493. backend.set( texture, {
  42494. textureGPU,
  42495. glTextureType,
  42496. glFormat,
  42497. glType,
  42498. glInternalFormat
  42499. } );
  42500. }
  42501. /**
  42502. * Uploads texture buffer data to the GPU memory.
  42503. *
  42504. * @param {WebGLBuffer} buffer - The buffer data.
  42505. * @param {Texture} texture - The texture,
  42506. */
  42507. copyBufferToTexture( buffer, texture ) {
  42508. const { gl, backend } = this;
  42509. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  42510. const { width, height } = texture.source.data;
  42511. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  42512. backend.state.bindTexture( glTextureType, textureGPU );
  42513. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  42514. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  42515. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  42516. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  42517. backend.state.unbindTexture();
  42518. // debug
  42519. // const framebuffer = gl.createFramebuffer();
  42520. // gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  42521. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  42522. // const readout = new Float32Array( width * height * 4 );
  42523. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  42524. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  42525. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  42526. // gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  42527. // console.log( readout );
  42528. }
  42529. /**
  42530. * Uploads the updated texture data to the GPU.
  42531. *
  42532. * @param {Texture} texture - The texture.
  42533. * @param {Object} [options={}] - Optional configuration parameter.
  42534. */
  42535. updateTexture( texture, options ) {
  42536. const { gl } = this;
  42537. const { width, height } = options;
  42538. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  42539. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  42540. return;
  42541. this.backend.state.bindTexture( glTextureType, textureGPU );
  42542. this.setTextureParameters( glTextureType, texture );
  42543. if ( texture.isCompressedTexture ) {
  42544. const mipmaps = texture.mipmaps;
  42545. const image = options.image;
  42546. for ( let i = 0; i < mipmaps.length; i ++ ) {
  42547. const mipmap = mipmaps[ i ];
  42548. if ( texture.isCompressedArrayTexture ) {
  42549. if ( texture.format !== gl.RGBA ) {
  42550. if ( glFormat !== null ) {
  42551. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  42552. } else {
  42553. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  42554. }
  42555. } else {
  42556. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  42557. }
  42558. } else {
  42559. if ( glFormat !== null ) {
  42560. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  42561. } else {
  42562. console.warn( 'Unsupported compressed texture format' );
  42563. }
  42564. }
  42565. }
  42566. } else if ( texture.isCubeTexture ) {
  42567. const images = options.images;
  42568. for ( let i = 0; i < 6; i ++ ) {
  42569. const image = getImage( images[ i ] );
  42570. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  42571. }
  42572. } else if ( texture.isDataArrayTexture || texture.isArrayTexture ) {
  42573. const image = options.image;
  42574. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  42575. } else if ( texture.isData3DTexture ) {
  42576. const image = options.image;
  42577. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  42578. } else if ( texture.isVideoTexture ) {
  42579. texture.update();
  42580. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  42581. } else {
  42582. const image = getImage( options.image );
  42583. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  42584. }
  42585. }
  42586. /**
  42587. * Generates mipmaps for the given texture.
  42588. *
  42589. * @param {Texture} texture - The texture.
  42590. */
  42591. generateMipmaps( texture ) {
  42592. const { gl, backend } = this;
  42593. const { textureGPU, glTextureType } = backend.get( texture );
  42594. backend.state.bindTexture( glTextureType, textureGPU );
  42595. gl.generateMipmap( glTextureType );
  42596. }
  42597. /**
  42598. * Deallocates the render buffers of the given render target.
  42599. *
  42600. * @param {RenderTarget} renderTarget - The render target.
  42601. */
  42602. deallocateRenderBuffers( renderTarget ) {
  42603. const { gl, backend } = this;
  42604. // remove framebuffer reference
  42605. if ( renderTarget ) {
  42606. const renderContextData = backend.get( renderTarget );
  42607. renderContextData.renderBufferStorageSetup = undefined;
  42608. if ( renderContextData.framebuffers ) {
  42609. for ( const cacheKey in renderContextData.framebuffers ) {
  42610. gl.deleteFramebuffer( renderContextData.framebuffers[ cacheKey ] );
  42611. }
  42612. delete renderContextData.framebuffers;
  42613. }
  42614. if ( renderContextData.depthRenderbuffer ) {
  42615. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  42616. delete renderContextData.depthRenderbuffer;
  42617. }
  42618. if ( renderContextData.stencilRenderbuffer ) {
  42619. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  42620. delete renderContextData.stencilRenderbuffer;
  42621. }
  42622. if ( renderContextData.msaaFrameBuffer ) {
  42623. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  42624. delete renderContextData.msaaFrameBuffer;
  42625. }
  42626. if ( renderContextData.msaaRenderbuffers ) {
  42627. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  42628. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  42629. }
  42630. delete renderContextData.msaaRenderbuffers;
  42631. }
  42632. }
  42633. }
  42634. /**
  42635. * Destroys the GPU data for the given texture object.
  42636. *
  42637. * @param {Texture} texture - The texture.
  42638. */
  42639. destroyTexture( texture ) {
  42640. const { gl, backend } = this;
  42641. const { textureGPU, renderTarget } = backend.get( texture );
  42642. this.deallocateRenderBuffers( renderTarget );
  42643. gl.deleteTexture( textureGPU );
  42644. backend.delete( texture );
  42645. }
  42646. /**
  42647. * Copies data of the given source texture to the given destination texture.
  42648. *
  42649. * @param {Texture} srcTexture - The source texture.
  42650. * @param {Texture} dstTexture - The destination texture.
  42651. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  42652. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  42653. * @param {number} [srcLevel=0] - The source mip level to copy from.
  42654. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  42655. */
  42656. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  42657. const { gl, backend } = this;
  42658. const { state } = this.backend;
  42659. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  42660. state.bindTexture( glTextureType, dstTextureGPU );
  42661. // gather the necessary dimensions to copy
  42662. let width, height, depth, minX, minY, minZ;
  42663. let dstX, dstY, dstZ;
  42664. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ dstLevel ] : srcTexture.image;
  42665. if ( srcRegion !== null ) {
  42666. width = srcRegion.max.x - srcRegion.min.x;
  42667. height = srcRegion.max.y - srcRegion.min.y;
  42668. depth = srcRegion.isBox3 ? srcRegion.max.z - srcRegion.min.z : 1;
  42669. minX = srcRegion.min.x;
  42670. minY = srcRegion.min.y;
  42671. minZ = srcRegion.isBox3 ? srcRegion.min.z : 0;
  42672. } else {
  42673. const levelScale = Math.pow( 2, - srcLevel );
  42674. width = Math.floor( image.width * levelScale );
  42675. height = Math.floor( image.height * levelScale );
  42676. if ( srcTexture.isDataArrayTexture || srcTexture.isArrayTexture ) {
  42677. depth = image.depth;
  42678. } else if ( srcTexture.isData3DTexture ) {
  42679. depth = Math.floor( image.depth * levelScale );
  42680. } else {
  42681. depth = 1;
  42682. }
  42683. minX = 0;
  42684. minY = 0;
  42685. minZ = 0;
  42686. }
  42687. if ( dstPosition !== null ) {
  42688. dstX = dstPosition.x;
  42689. dstY = dstPosition.y;
  42690. dstZ = dstPosition.z;
  42691. } else {
  42692. dstX = 0;
  42693. dstY = 0;
  42694. dstZ = 0;
  42695. }
  42696. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  42697. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  42698. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  42699. // used for copying data from cpu
  42700. const currentUnpackRowLen = gl.getParameter( gl.UNPACK_ROW_LENGTH );
  42701. const currentUnpackImageHeight = gl.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  42702. const currentUnpackSkipPixels = gl.getParameter( gl.UNPACK_SKIP_PIXELS );
  42703. const currentUnpackSkipRows = gl.getParameter( gl.UNPACK_SKIP_ROWS );
  42704. const currentUnpackSkipImages = gl.getParameter( gl.UNPACK_SKIP_IMAGES );
  42705. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  42706. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  42707. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  42708. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  42709. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, minZ );
  42710. // set up the src texture
  42711. const isDst3D = dstTexture.isDataArrayTexture || dstTexture.isData3DTexture || dstTexture.isArrayTexture;
  42712. if ( srcTexture.isRenderTargetTexture || srcTexture.isDepthTexture ) {
  42713. const srcTextureData = backend.get( srcTexture );
  42714. const dstTextureData = backend.get( dstTexture );
  42715. const srcRenderContextData = backend.get( srcTextureData.renderTarget );
  42716. const dstRenderContextData = backend.get( dstTextureData.renderTarget );
  42717. const srcFramebuffer = srcRenderContextData.framebuffers[ srcTextureData.cacheKey ];
  42718. const dstFramebuffer = dstRenderContextData.framebuffers[ dstTextureData.cacheKey ];
  42719. state.bindFramebuffer( gl.READ_FRAMEBUFFER, srcFramebuffer );
  42720. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, dstFramebuffer );
  42721. let mask = gl.COLOR_BUFFER_BIT;
  42722. if ( srcTexture.isDepthTexture ) mask = gl.DEPTH_BUFFER_BIT;
  42723. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, mask, gl.NEAREST );
  42724. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  42725. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  42726. } else {
  42727. if ( isDst3D ) {
  42728. // copy data into the 3d texture
  42729. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  42730. gl.texSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image.data );
  42731. } else if ( dstTexture.isCompressedArrayTexture ) {
  42732. gl.compressedTexSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, image.data );
  42733. } else {
  42734. gl.texSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image );
  42735. }
  42736. } else {
  42737. // copy data into the 2d texture
  42738. if ( srcTexture.isDataTexture ) {
  42739. gl.texSubImage2D( glTextureType, dstLevel, dstX, dstY, width, height, glFormat, glType, image.data );
  42740. } else if ( srcTexture.isCompressedTexture ) {
  42741. gl.compressedTexSubImage2D( glTextureType, dstLevel, dstX, dstY, image.width, image.height, glFormat, image.data );
  42742. } else {
  42743. gl.texSubImage2D( glTextureType, dstLevel, dstX, dstY, width, height, glFormat, glType, image );
  42744. }
  42745. }
  42746. }
  42747. // reset values
  42748. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  42749. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  42750. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  42751. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  42752. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  42753. // Generate mipmaps only when copying level 0
  42754. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  42755. gl.generateMipmap( glTextureType );
  42756. }
  42757. state.unbindTexture();
  42758. }
  42759. /**
  42760. * Copies the current bound framebuffer to the given texture.
  42761. *
  42762. * @param {Texture} texture - The destination texture.
  42763. * @param {RenderContext} renderContext - The render context.
  42764. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  42765. */
  42766. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  42767. const { gl } = this;
  42768. const { state } = this.backend;
  42769. const { textureGPU } = this.backend.get( texture );
  42770. const { x, y, z: width, w: height } = rectangle;
  42771. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  42772. const srcHeight = renderContext.renderTarget ? renderContext.renderTarget.height : this.backend.getDrawingBufferSize().y;
  42773. if ( requireDrawFrameBuffer ) {
  42774. const partial = ( x !== 0 || y !== 0 );
  42775. let mask;
  42776. let attachment;
  42777. if ( texture.isDepthTexture === true ) {
  42778. mask = gl.DEPTH_BUFFER_BIT;
  42779. attachment = gl.DEPTH_ATTACHMENT;
  42780. if ( renderContext.stencil ) {
  42781. mask |= gl.STENCIL_BUFFER_BIT;
  42782. }
  42783. } else {
  42784. mask = gl.COLOR_BUFFER_BIT;
  42785. attachment = gl.COLOR_ATTACHMENT0;
  42786. }
  42787. if ( partial ) {
  42788. const renderTargetContextData = this.backend.get( renderContext.renderTarget );
  42789. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  42790. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  42791. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  42792. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  42793. const flippedY = srcHeight - y - height;
  42794. gl.blitFramebuffer( x, flippedY, x + width, flippedY + height, x, flippedY, x + width, flippedY + height, mask, gl.NEAREST );
  42795. state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  42796. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  42797. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, flippedY, width, height );
  42798. state.unbindTexture();
  42799. } else {
  42800. const fb = gl.createFramebuffer();
  42801. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  42802. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  42803. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  42804. gl.deleteFramebuffer( fb );
  42805. }
  42806. } else {
  42807. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  42808. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, srcHeight - height - y, width, height );
  42809. state.unbindTexture();
  42810. }
  42811. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  42812. this.backend._setFramebuffer( renderContext );
  42813. }
  42814. /**
  42815. * SetupS storage for internal depth/stencil buffers and bind to correct framebuffer.
  42816. *
  42817. * @param {WebGLRenderbuffer} renderbuffer - The render buffer.
  42818. * @param {RenderContext} renderContext - The render context.
  42819. * @param {number} samples - The MSAA sample count.
  42820. * @param {boolean} [useMultisampledRTT=false] - Whether to use WEBGL_multisampled_render_to_texture or not.
  42821. */
  42822. setupRenderBufferStorage( renderbuffer, renderContext, samples, useMultisampledRTT = false ) {
  42823. const { gl } = this;
  42824. const renderTarget = renderContext.renderTarget;
  42825. const { depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  42826. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  42827. if ( depthBuffer && ! stencilBuffer ) {
  42828. let glInternalFormat = gl.DEPTH_COMPONENT24;
  42829. if ( useMultisampledRTT === true ) {
  42830. const multisampledRTTExt = this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  42831. multisampledRTTExt.renderbufferStorageMultisampleEXT( gl.RENDERBUFFER, renderTarget.samples, glInternalFormat, width, height );
  42832. } else if ( samples > 0 ) {
  42833. if ( depthTexture && depthTexture.isDepthTexture ) {
  42834. if ( depthTexture.type === gl.FLOAT ) {
  42835. glInternalFormat = gl.DEPTH_COMPONENT32F;
  42836. }
  42837. }
  42838. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  42839. } else {
  42840. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  42841. }
  42842. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  42843. } else if ( depthBuffer && stencilBuffer ) {
  42844. if ( samples > 0 ) {
  42845. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  42846. } else {
  42847. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  42848. }
  42849. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  42850. }
  42851. }
  42852. /**
  42853. * Returns texture data as a typed array.
  42854. *
  42855. * @async
  42856. * @param {Texture} texture - The texture to copy.
  42857. * @param {number} x - The x coordinate of the copy origin.
  42858. * @param {number} y - The y coordinate of the copy origin.
  42859. * @param {number} width - The width of the copy.
  42860. * @param {number} height - The height of the copy.
  42861. * @param {number} faceIndex - The face index.
  42862. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  42863. */
  42864. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  42865. const { backend, gl } = this;
  42866. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  42867. const fb = gl.createFramebuffer();
  42868. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  42869. const target = texture.isCubeTexture ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex : gl.TEXTURE_2D;
  42870. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, target, textureGPU, 0 );
  42871. const typedArrayType = this._getTypedArrayType( glType );
  42872. const bytesPerTexel = this._getBytesPerTexel( glType, glFormat );
  42873. const elementCount = width * height;
  42874. const byteLength = elementCount * bytesPerTexel;
  42875. const buffer = gl.createBuffer();
  42876. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  42877. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  42878. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  42879. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  42880. await backend.utils._clientWaitAsync();
  42881. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  42882. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  42883. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  42884. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  42885. gl.deleteFramebuffer( fb );
  42886. return dstBuffer;
  42887. }
  42888. /**
  42889. * Returns the corresponding typed array type for the given WebGL data type.
  42890. *
  42891. * @private
  42892. * @param {GLenum} glType - The WebGL data type.
  42893. * @return {TypedArray.constructor} The typed array type.
  42894. */
  42895. _getTypedArrayType( glType ) {
  42896. const { gl } = this;
  42897. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  42898. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  42899. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  42900. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  42901. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  42902. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  42903. if ( glType === gl.HALF_FLOAT ) return Uint16Array;
  42904. if ( glType === gl.FLOAT ) return Float32Array;
  42905. throw new Error( `Unsupported WebGL type: ${glType}` );
  42906. }
  42907. /**
  42908. * Returns the bytes-per-texel value for the given WebGL data type and texture format.
  42909. *
  42910. * @private
  42911. * @param {GLenum} glType - The WebGL data type.
  42912. * @param {GLenum} glFormat - The WebGL texture format.
  42913. * @return {number} The bytes-per-texel.
  42914. */
  42915. _getBytesPerTexel( glType, glFormat ) {
  42916. const { gl } = this;
  42917. let bytesPerComponent = 0;
  42918. if ( glType === gl.UNSIGNED_BYTE ) bytesPerComponent = 1;
  42919. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ||
  42920. glType === gl.UNSIGNED_SHORT_5_5_5_1 ||
  42921. glType === gl.UNSIGNED_SHORT_5_6_5 ||
  42922. glType === gl.UNSIGNED_SHORT ||
  42923. glType === gl.HALF_FLOAT ) bytesPerComponent = 2;
  42924. if ( glType === gl.UNSIGNED_INT ||
  42925. glType === gl.FLOAT ) bytesPerComponent = 4;
  42926. if ( glFormat === gl.RGBA ) return bytesPerComponent * 4;
  42927. if ( glFormat === gl.RGB ) return bytesPerComponent * 3;
  42928. if ( glFormat === gl.ALPHA ) return bytesPerComponent;
  42929. }
  42930. }
  42931. function getImage( source ) {
  42932. if ( source.isDataTexture ) {
  42933. return source.image.data;
  42934. } else if ( ( typeof HTMLImageElement !== 'undefined' && source instanceof HTMLImageElement ) ||
  42935. ( typeof HTMLCanvasElement !== 'undefined' && source instanceof HTMLCanvasElement ) ||
  42936. ( typeof ImageBitmap !== 'undefined' && source instanceof ImageBitmap ) ||
  42937. ( typeof OffscreenCanvas !== 'undefined' && source instanceof OffscreenCanvas ) ) {
  42938. return source;
  42939. }
  42940. return source.data;
  42941. }
  42942. /**
  42943. * A WebGL 2 backend utility module for managing extensions.
  42944. *
  42945. * @private
  42946. */
  42947. class WebGLExtensions {
  42948. /**
  42949. * Constructs a new utility object.
  42950. *
  42951. * @param {WebGLBackend} backend - The WebGL 2 backend.
  42952. */
  42953. constructor( backend ) {
  42954. /**
  42955. * A reference to the WebGL 2 backend.
  42956. *
  42957. * @type {WebGLBackend}
  42958. */
  42959. this.backend = backend;
  42960. /**
  42961. * A reference to the rendering context.
  42962. *
  42963. * @type {WebGL2RenderingContext}
  42964. */
  42965. this.gl = this.backend.gl;
  42966. /**
  42967. * A list with all the supported WebGL extensions.
  42968. *
  42969. * @type {Array<string>}
  42970. */
  42971. this.availableExtensions = this.gl.getSupportedExtensions();
  42972. /**
  42973. * A dictionary with requested WebGL extensions.
  42974. * The key is the name of the extension, the value
  42975. * the requested extension object.
  42976. *
  42977. * @type {Object<string,Object>}
  42978. */
  42979. this.extensions = {};
  42980. }
  42981. /**
  42982. * Returns the extension object for the given extension name.
  42983. *
  42984. * @param {string} name - The extension name.
  42985. * @return {Object} The extension object.
  42986. */
  42987. get( name ) {
  42988. let extension = this.extensions[ name ];
  42989. if ( extension === undefined ) {
  42990. extension = this.gl.getExtension( name );
  42991. this.extensions[ name ] = extension;
  42992. }
  42993. return extension;
  42994. }
  42995. /**
  42996. * Returns `true` if the requested extension is available.
  42997. *
  42998. * @param {string} name - The extension name.
  42999. * @return {boolean} Whether the given extension is available or not.
  43000. */
  43001. has( name ) {
  43002. return this.availableExtensions.includes( name );
  43003. }
  43004. }
  43005. /**
  43006. * A WebGL 2 backend utility module for managing the device's capabilities.
  43007. *
  43008. * @private
  43009. */
  43010. class WebGLCapabilities {
  43011. /**
  43012. * Constructs a new utility object.
  43013. *
  43014. * @param {WebGLBackend} backend - The WebGL 2 backend.
  43015. */
  43016. constructor( backend ) {
  43017. /**
  43018. * A reference to the WebGL 2 backend.
  43019. *
  43020. * @type {WebGLBackend}
  43021. */
  43022. this.backend = backend;
  43023. /**
  43024. * This value holds the cached max anisotropy value.
  43025. *
  43026. * @type {?number}
  43027. * @default null
  43028. */
  43029. this.maxAnisotropy = null;
  43030. }
  43031. /**
  43032. * Returns the maximum anisotropy texture filtering value. This value
  43033. * depends on the device and is reported by the `EXT_texture_filter_anisotropic`
  43034. * WebGL extension.
  43035. *
  43036. * @return {number} The maximum anisotropy texture filtering value.
  43037. */
  43038. getMaxAnisotropy() {
  43039. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  43040. const gl = this.backend.gl;
  43041. const extensions = this.backend.extensions;
  43042. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  43043. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  43044. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  43045. } else {
  43046. this.maxAnisotropy = 0;
  43047. }
  43048. return this.maxAnisotropy;
  43049. }
  43050. }
  43051. const GLFeatureName = {
  43052. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  43053. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  43054. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  43055. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  43056. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  43057. 'WEBKIT_WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  43058. 'WEBGL_compressed_texture_s3tc': 'texture-compression-bc',
  43059. 'EXT_texture_compression_bptc': 'texture-compression-bptc',
  43060. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  43061. 'OVR_multiview2': 'OVR_multiview2'
  43062. };
  43063. class WebGLBufferRenderer {
  43064. constructor( backend ) {
  43065. this.gl = backend.gl;
  43066. this.extensions = backend.extensions;
  43067. this.info = backend.renderer.info;
  43068. this.mode = null;
  43069. this.index = 0;
  43070. this.type = null;
  43071. this.object = null;
  43072. }
  43073. render( start, count ) {
  43074. const { gl, mode, object, type, info, index } = this;
  43075. if ( index !== 0 ) {
  43076. gl.drawElements( mode, count, type, start );
  43077. } else {
  43078. gl.drawArrays( mode, start, count );
  43079. }
  43080. info.update( object, count, 1 );
  43081. }
  43082. renderInstances( start, count, primcount ) {
  43083. const { gl, mode, type, index, object, info } = this;
  43084. if ( primcount === 0 ) return;
  43085. if ( index !== 0 ) {
  43086. gl.drawElementsInstanced( mode, count, type, start, primcount );
  43087. } else {
  43088. gl.drawArraysInstanced( mode, start, count, primcount );
  43089. }
  43090. info.update( object, count, primcount );
  43091. }
  43092. renderMultiDraw( starts, counts, drawCount ) {
  43093. const { extensions, mode, object, info } = this;
  43094. if ( drawCount === 0 ) return;
  43095. const extension = extensions.get( 'WEBGL_multi_draw' );
  43096. if ( extension === null ) {
  43097. for ( let i = 0; i < drawCount; i ++ ) {
  43098. this.render( starts[ i ], counts[ i ] );
  43099. }
  43100. } else {
  43101. if ( this.index !== 0 ) {
  43102. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  43103. } else {
  43104. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  43105. }
  43106. let elementCount = 0;
  43107. for ( let i = 0; i < drawCount; i ++ ) {
  43108. elementCount += counts[ i ];
  43109. }
  43110. info.update( object, elementCount, 1 );
  43111. }
  43112. }
  43113. renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  43114. const { extensions, mode, object, info } = this;
  43115. if ( drawCount === 0 ) return;
  43116. const extension = extensions.get( 'WEBGL_multi_draw' );
  43117. if ( extension === null ) {
  43118. for ( let i = 0; i < drawCount; i ++ ) {
  43119. this.renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  43120. }
  43121. } else {
  43122. if ( this.index !== 0 ) {
  43123. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, this.type, starts, 0, primcount, 0, drawCount );
  43124. } else {
  43125. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  43126. }
  43127. let elementCount = 0;
  43128. for ( let i = 0; i < drawCount; i ++ ) {
  43129. elementCount += counts[ i ] * primcount[ i ];
  43130. }
  43131. info.update( object, elementCount, 1 );
  43132. }
  43133. }
  43134. //
  43135. }
  43136. /**
  43137. * Abstract base class of a timestamp query pool.
  43138. *
  43139. * @abstract
  43140. */
  43141. class TimestampQueryPool {
  43142. /**
  43143. * Creates a new timestamp query pool.
  43144. *
  43145. * @param {number} [maxQueries=256] - Maximum number of queries this pool can hold.
  43146. */
  43147. constructor( maxQueries = 256 ) {
  43148. /**
  43149. * Whether to track timestamps or not.
  43150. *
  43151. * @type {boolean}
  43152. * @default true
  43153. */
  43154. this.trackTimestamp = true;
  43155. /**
  43156. * Maximum number of queries this pool can hold.
  43157. *
  43158. * @type {number}
  43159. * @default 256
  43160. */
  43161. this.maxQueries = maxQueries;
  43162. /**
  43163. * How many queries allocated so far.
  43164. *
  43165. * @type {number}
  43166. * @default 0
  43167. */
  43168. this.currentQueryIndex = 0;
  43169. /**
  43170. * Tracks offsets for different contexts.
  43171. *
  43172. * @type {Map<string, number>}
  43173. */
  43174. this.queryOffsets = new Map();
  43175. /**
  43176. * Whether the pool has been disposed or not.
  43177. *
  43178. * @type {boolean}
  43179. * @default false
  43180. */
  43181. this.isDisposed = false;
  43182. /**
  43183. * TODO
  43184. *
  43185. * @type {number}
  43186. * @default 0
  43187. */
  43188. this.lastValue = 0;
  43189. /**
  43190. * TODO
  43191. *
  43192. * @type {boolean}
  43193. * @default false
  43194. */
  43195. this.pendingResolve = false;
  43196. }
  43197. /**
  43198. * Allocate queries for a specific renderContext.
  43199. *
  43200. * @abstract
  43201. * @param {Object} renderContext - The render context to allocate queries for.
  43202. * @returns {?number}
  43203. */
  43204. allocateQueriesForContext( /* renderContext */ ) {}
  43205. /**
  43206. * Resolve all timestamps and return data (or process them).
  43207. *
  43208. * @abstract
  43209. * @async
  43210. * @returns {Promise<number>|number} The resolved timestamp value.
  43211. */
  43212. async resolveQueriesAsync() {}
  43213. /**
  43214. * Dispose of the query pool.
  43215. *
  43216. * @abstract
  43217. */
  43218. dispose() {}
  43219. }
  43220. /**
  43221. * Manages a pool of WebGL timestamp queries for performance measurement.
  43222. * Handles creation, execution, and resolution of timer queries using WebGL extensions.
  43223. *
  43224. * @augments TimestampQueryPool
  43225. */
  43226. class WebGLTimestampQueryPool extends TimestampQueryPool {
  43227. /**
  43228. * Creates a new WebGL timestamp query pool.
  43229. *
  43230. * @param {WebGLRenderingContext|WebGL2RenderingContext} gl - The WebGL context.
  43231. * @param {string} type - The type identifier for this query pool.
  43232. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  43233. */
  43234. constructor( gl, type, maxQueries = 2048 ) {
  43235. super( maxQueries );
  43236. this.gl = gl;
  43237. this.type = type;
  43238. // Check for timer query extensions
  43239. this.ext = gl.getExtension( 'EXT_disjoint_timer_query_webgl2' ) ||
  43240. gl.getExtension( 'EXT_disjoint_timer_query' );
  43241. if ( ! this.ext ) {
  43242. console.warn( 'EXT_disjoint_timer_query not supported; timestamps will be disabled.' );
  43243. this.trackTimestamp = false;
  43244. return;
  43245. }
  43246. // Create query objects
  43247. this.queries = [];
  43248. for ( let i = 0; i < this.maxQueries; i ++ ) {
  43249. this.queries.push( gl.createQuery() );
  43250. }
  43251. this.activeQuery = null;
  43252. this.queryStates = new Map(); // Track state of each query: 'inactive', 'started', 'ended'
  43253. }
  43254. /**
  43255. * Allocates a pair of queries for a given render context.
  43256. *
  43257. * @param {Object} renderContext - The render context to allocate queries for.
  43258. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  43259. */
  43260. allocateQueriesForContext( renderContext ) {
  43261. if ( ! this.trackTimestamp ) return null;
  43262. // Check if we have enough space for a new query pair
  43263. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  43264. 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() } ).` );
  43265. return null;
  43266. }
  43267. const baseOffset = this.currentQueryIndex;
  43268. this.currentQueryIndex += 2;
  43269. // Initialize query states
  43270. this.queryStates.set( baseOffset, 'inactive' );
  43271. this.queryOffsets.set( renderContext.id, baseOffset );
  43272. return baseOffset;
  43273. }
  43274. /**
  43275. * Begins a timestamp query for the specified render context.
  43276. *
  43277. * @param {Object} renderContext - The render context to begin timing for.
  43278. */
  43279. beginQuery( renderContext ) {
  43280. if ( ! this.trackTimestamp || this.isDisposed ) {
  43281. return;
  43282. }
  43283. const baseOffset = this.queryOffsets.get( renderContext.id );
  43284. if ( baseOffset == null ) {
  43285. return;
  43286. }
  43287. // Don't start a new query if there's an active one
  43288. if ( this.activeQuery !== null ) {
  43289. return;
  43290. }
  43291. const query = this.queries[ baseOffset ];
  43292. if ( ! query ) {
  43293. return;
  43294. }
  43295. try {
  43296. // Only begin if query is inactive
  43297. if ( this.queryStates.get( baseOffset ) === 'inactive' ) {
  43298. this.gl.beginQuery( this.ext.TIME_ELAPSED_EXT, query );
  43299. this.activeQuery = baseOffset;
  43300. this.queryStates.set( baseOffset, 'started' );
  43301. }
  43302. } catch ( error ) {
  43303. console.error( 'Error in beginQuery:', error );
  43304. this.activeQuery = null;
  43305. this.queryStates.set( baseOffset, 'inactive' );
  43306. }
  43307. }
  43308. /**
  43309. * Ends the active timestamp query for the specified render context.
  43310. *
  43311. * @param {Object} renderContext - The render context to end timing for.
  43312. * @param {string} renderContext.id - Unique identifier for the render context.
  43313. */
  43314. endQuery( renderContext ) {
  43315. if ( ! this.trackTimestamp || this.isDisposed ) {
  43316. return;
  43317. }
  43318. const baseOffset = this.queryOffsets.get( renderContext.id );
  43319. if ( baseOffset == null ) {
  43320. return;
  43321. }
  43322. // Only end if this is the active query
  43323. if ( this.activeQuery !== baseOffset ) {
  43324. return;
  43325. }
  43326. try {
  43327. this.gl.endQuery( this.ext.TIME_ELAPSED_EXT );
  43328. this.queryStates.set( baseOffset, 'ended' );
  43329. this.activeQuery = null;
  43330. } catch ( error ) {
  43331. console.error( 'Error in endQuery:', error );
  43332. // Reset state on error
  43333. this.queryStates.set( baseOffset, 'inactive' );
  43334. this.activeQuery = null;
  43335. }
  43336. }
  43337. /**
  43338. * Asynchronously resolves all completed queries and returns the total duration.
  43339. *
  43340. * @async
  43341. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  43342. */
  43343. async resolveQueriesAsync() {
  43344. if ( ! this.trackTimestamp || this.pendingResolve ) {
  43345. return this.lastValue;
  43346. }
  43347. this.pendingResolve = true;
  43348. try {
  43349. // Wait for all ended queries to complete
  43350. const resolvePromises = [];
  43351. for ( const [ baseOffset, state ] of this.queryStates ) {
  43352. if ( state === 'ended' ) {
  43353. const query = this.queries[ baseOffset ];
  43354. resolvePromises.push( this.resolveQuery( query ) );
  43355. }
  43356. }
  43357. if ( resolvePromises.length === 0 ) {
  43358. return this.lastValue;
  43359. }
  43360. const results = await Promise.all( resolvePromises );
  43361. const totalDuration = results.reduce( ( acc, val ) => acc + val, 0 );
  43362. // Store the last valid result
  43363. this.lastValue = totalDuration;
  43364. // Reset states
  43365. this.currentQueryIndex = 0;
  43366. this.queryOffsets.clear();
  43367. this.queryStates.clear();
  43368. this.activeQuery = null;
  43369. return totalDuration;
  43370. } catch ( error ) {
  43371. console.error( 'Error resolving queries:', error );
  43372. return this.lastValue;
  43373. } finally {
  43374. this.pendingResolve = false;
  43375. }
  43376. }
  43377. /**
  43378. * Resolves a single query, checking for completion and disjoint operation.
  43379. *
  43380. * @async
  43381. * @param {WebGLQuery} query - The query object to resolve.
  43382. * @returns {Promise<number>} The elapsed time in milliseconds.
  43383. */
  43384. async resolveQuery( query ) {
  43385. return new Promise( ( resolve ) => {
  43386. if ( this.isDisposed ) {
  43387. resolve( this.lastValue );
  43388. return;
  43389. }
  43390. let timeoutId;
  43391. let isResolved = false;
  43392. const cleanup = () => {
  43393. if ( timeoutId ) {
  43394. clearTimeout( timeoutId );
  43395. timeoutId = null;
  43396. }
  43397. };
  43398. const finalizeResolution = ( value ) => {
  43399. if ( ! isResolved ) {
  43400. isResolved = true;
  43401. cleanup();
  43402. resolve( value );
  43403. }
  43404. };
  43405. const checkQuery = () => {
  43406. if ( this.isDisposed ) {
  43407. finalizeResolution( this.lastValue );
  43408. return;
  43409. }
  43410. try {
  43411. // Check if the GPU timer was disjoint (i.e., timing was unreliable)
  43412. const disjoint = this.gl.getParameter( this.ext.GPU_DISJOINT_EXT );
  43413. if ( disjoint ) {
  43414. finalizeResolution( this.lastValue );
  43415. return;
  43416. }
  43417. const available = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT_AVAILABLE );
  43418. if ( ! available ) {
  43419. timeoutId = setTimeout( checkQuery, 1 );
  43420. return;
  43421. }
  43422. const elapsed = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT );
  43423. resolve( Number( elapsed ) / 1e6 ); // Convert nanoseconds to milliseconds
  43424. } catch ( error ) {
  43425. console.error( 'Error checking query:', error );
  43426. resolve( this.lastValue );
  43427. }
  43428. };
  43429. checkQuery();
  43430. } );
  43431. }
  43432. /**
  43433. * Releases all resources held by this query pool.
  43434. * This includes deleting all query objects and clearing internal state.
  43435. */
  43436. dispose() {
  43437. if ( this.isDisposed ) {
  43438. return;
  43439. }
  43440. this.isDisposed = true;
  43441. if ( ! this.trackTimestamp ) return;
  43442. for ( const query of this.queries ) {
  43443. this.gl.deleteQuery( query );
  43444. }
  43445. this.queries = [];
  43446. this.queryStates.clear();
  43447. this.queryOffsets.clear();
  43448. this.lastValue = 0;
  43449. this.activeQuery = null;
  43450. }
  43451. }
  43452. const _drawingBufferSize = /*@__PURE__*/ new Vector2();
  43453. /**
  43454. * A backend implementation targeting WebGL 2.
  43455. *
  43456. * @private
  43457. * @augments Backend
  43458. */
  43459. class WebGLBackend extends Backend {
  43460. /**
  43461. * WebGLBackend options.
  43462. *
  43463. * @typedef {Object} WebGLBackend~Options
  43464. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  43465. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  43466. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  43467. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  43468. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  43469. * @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.
  43470. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  43471. * @property {WebGL2RenderingContext} [context=undefined] - A WebGL 2 rendering context.
  43472. */
  43473. /**
  43474. * Constructs a new WebGPU backend.
  43475. *
  43476. * @param {WebGLBackend~Options} [parameters] - The configuration parameter.
  43477. */
  43478. constructor( parameters = {} ) {
  43479. super( parameters );
  43480. /**
  43481. * This flag can be used for type testing.
  43482. *
  43483. * @type {boolean}
  43484. * @readonly
  43485. * @default true
  43486. */
  43487. this.isWebGLBackend = true;
  43488. /**
  43489. * A reference to a backend module holding shader attribute-related
  43490. * utility functions.
  43491. *
  43492. * @type {?WebGLAttributeUtils}
  43493. * @default null
  43494. */
  43495. this.attributeUtils = null;
  43496. /**
  43497. * A reference to a backend module holding extension-related
  43498. * utility functions.
  43499. *
  43500. * @type {?WebGLExtensions}
  43501. * @default null
  43502. */
  43503. this.extensions = null;
  43504. /**
  43505. * A reference to a backend module holding capability-related
  43506. * utility functions.
  43507. *
  43508. * @type {?WebGLCapabilities}
  43509. * @default null
  43510. */
  43511. this.capabilities = null;
  43512. /**
  43513. * A reference to a backend module holding texture-related
  43514. * utility functions.
  43515. *
  43516. * @type {?WebGLTextureUtils}
  43517. * @default null
  43518. */
  43519. this.textureUtils = null;
  43520. /**
  43521. * A reference to a backend module holding renderer-related
  43522. * utility functions.
  43523. *
  43524. * @type {?WebGLBufferRenderer}
  43525. * @default null
  43526. */
  43527. this.bufferRenderer = null;
  43528. /**
  43529. * A reference to the rendering context.
  43530. *
  43531. * @type {?WebGL2RenderingContext}
  43532. * @default null
  43533. */
  43534. this.gl = null;
  43535. /**
  43536. * A reference to a backend module holding state-related
  43537. * utility functions.
  43538. *
  43539. * @type {?WebGLState}
  43540. * @default null
  43541. */
  43542. this.state = null;
  43543. /**
  43544. * A reference to a backend module holding common
  43545. * utility functions.
  43546. *
  43547. * @type {?WebGLUtils}
  43548. * @default null
  43549. */
  43550. this.utils = null;
  43551. /**
  43552. * Dictionary for caching VAOs.
  43553. *
  43554. * @type {Object<string,WebGLVertexArrayObject>}
  43555. */
  43556. this.vaoCache = {};
  43557. /**
  43558. * Dictionary for caching transform feedback objects.
  43559. *
  43560. * @type {Object<string,WebGLTransformFeedback>}
  43561. */
  43562. this.transformFeedbackCache = {};
  43563. /**
  43564. * Controls if `gl.RASTERIZER_DISCARD` should be enabled or not.
  43565. * Only relevant when using compute shaders.
  43566. *
  43567. * @type {boolean}
  43568. * @default false
  43569. */
  43570. this.discard = false;
  43571. /**
  43572. * A reference to the `EXT_disjoint_timer_query_webgl2` extension. `null` if the
  43573. * device does not support the extension.
  43574. *
  43575. * @type {?EXTDisjointTimerQueryWebGL2}
  43576. * @default null
  43577. */
  43578. this.disjoint = null;
  43579. /**
  43580. * A reference to the `KHR_parallel_shader_compile` extension. `null` if the
  43581. * device does not support the extension.
  43582. *
  43583. * @type {?KHRParallelShaderCompile}
  43584. * @default null
  43585. */
  43586. this.parallel = null;
  43587. /**
  43588. * A reference to the current render context.
  43589. *
  43590. * @private
  43591. * @type {RenderContext}
  43592. * @default null
  43593. */
  43594. this._currentContext = null;
  43595. /**
  43596. * A unique collection of bindings.
  43597. *
  43598. * @private
  43599. * @type {WeakSet}
  43600. */
  43601. this._knownBindings = new WeakSet();
  43602. /**
  43603. * Whether the device supports framebuffers invalidation or not.
  43604. *
  43605. * @private
  43606. * @type {boolean}
  43607. */
  43608. this._supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent );
  43609. /**
  43610. * The target framebuffer when rendering with
  43611. * the WebXR device API.
  43612. *
  43613. * @private
  43614. * @type {WebGLFramebuffer}
  43615. * @default null
  43616. */
  43617. this._xrFramebuffer = null;
  43618. }
  43619. /**
  43620. * Initializes the backend so it is ready for usage.
  43621. *
  43622. * @param {Renderer} renderer - The renderer.
  43623. */
  43624. init( renderer ) {
  43625. super.init( renderer );
  43626. //
  43627. const parameters = this.parameters;
  43628. const contextAttributes = {
  43629. antialias: renderer.samples > 0,
  43630. alpha: true, // always true for performance reasons
  43631. depth: renderer.depth,
  43632. stencil: renderer.stencil
  43633. };
  43634. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2', contextAttributes );
  43635. function onContextLost( event ) {
  43636. event.preventDefault();
  43637. const contextLossInfo = {
  43638. api: 'WebGL',
  43639. message: event.statusMessage || 'Unknown reason',
  43640. reason: null,
  43641. originalEvent: event
  43642. };
  43643. renderer.onDeviceLost( contextLossInfo );
  43644. }
  43645. this._onContextLost = onContextLost;
  43646. renderer.domElement.addEventListener( 'webglcontextlost', onContextLost, false );
  43647. this.gl = glContext;
  43648. this.extensions = new WebGLExtensions( this );
  43649. this.capabilities = new WebGLCapabilities( this );
  43650. this.attributeUtils = new WebGLAttributeUtils( this );
  43651. this.textureUtils = new WebGLTextureUtils( this );
  43652. this.bufferRenderer = new WebGLBufferRenderer( this );
  43653. this.state = new WebGLState( this );
  43654. this.utils = new WebGLUtils( this );
  43655. this.extensions.get( 'EXT_color_buffer_float' );
  43656. this.extensions.get( 'WEBGL_clip_cull_distance' );
  43657. this.extensions.get( 'OES_texture_float_linear' );
  43658. this.extensions.get( 'EXT_color_buffer_half_float' );
  43659. this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  43660. this.extensions.get( 'WEBGL_render_shared_exponent' );
  43661. this.extensions.get( 'WEBGL_multi_draw' );
  43662. this.extensions.get( 'OVR_multiview2' );
  43663. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  43664. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  43665. }
  43666. /**
  43667. * The coordinate system of the backend.
  43668. *
  43669. * @type {number}
  43670. * @readonly
  43671. */
  43672. get coordinateSystem() {
  43673. return WebGLCoordinateSystem;
  43674. }
  43675. /**
  43676. * This method performs a readback operation by moving buffer data from
  43677. * a storage buffer attribute from the GPU to the CPU.
  43678. *
  43679. * @async
  43680. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  43681. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  43682. */
  43683. async getArrayBufferAsync( attribute ) {
  43684. return await this.attributeUtils.getArrayBufferAsync( attribute );
  43685. }
  43686. /**
  43687. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  43688. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  43689. *
  43690. * @async
  43691. * @return {Promise} A Promise that resolves when synchronization has been finished.
  43692. */
  43693. async waitForGPU() {
  43694. await this.utils._clientWaitAsync();
  43695. }
  43696. /**
  43697. * Ensures the backend is XR compatible.
  43698. *
  43699. * @async
  43700. * @return {Promise} A Promise that resolve when the renderer is XR compatible.
  43701. */
  43702. async makeXRCompatible() {
  43703. const attributes = this.gl.getContextAttributes();
  43704. if ( attributes.xrCompatible !== true ) {
  43705. await this.gl.makeXRCompatible();
  43706. }
  43707. }
  43708. /**
  43709. * Sets the XR rendering destination.
  43710. *
  43711. * @param {WebGLFramebuffer} xrFramebuffer - The XR framebuffer.
  43712. */
  43713. setXRTarget( xrFramebuffer ) {
  43714. this._xrFramebuffer = xrFramebuffer;
  43715. }
  43716. /**
  43717. * Configures the given XR render target with external textures.
  43718. *
  43719. * This method is only relevant when using the WebXR Layers API.
  43720. *
  43721. * @param {XRRenderTarget} renderTarget - The XR render target.
  43722. * @param {WebGLTexture} colorTexture - A native color texture.
  43723. * @param {?WebGLTexture} [depthTexture=null] - A native depth texture.
  43724. */
  43725. setXRRenderTargetTextures( renderTarget, colorTexture, depthTexture = null ) {
  43726. const gl = this.gl;
  43727. this.set( renderTarget.texture, { textureGPU: colorTexture, glInternalFormat: gl.RGBA8 } ); // see #24698 why RGBA8 and not SRGB8_ALPHA8 is used
  43728. if ( depthTexture !== null ) {
  43729. const glInternalFormat = renderTarget.stencilBuffer ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  43730. this.set( renderTarget.depthTexture, { textureGPU: depthTexture, glInternalFormat: glInternalFormat } );
  43731. // The multisample_render_to_texture extension doesn't work properly if there
  43732. // are midframe flushes and an external depth texture.
  43733. if ( ( this.extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) && renderTarget.autoAllocateDepthBuffer === true && renderTarget.multiview === false ) {
  43734. console.warn( 'THREE.WebGLBackend: Render-to-texture extension was disabled because an external texture was provided' );
  43735. }
  43736. renderTarget.autoAllocateDepthBuffer = false;
  43737. }
  43738. }
  43739. /**
  43740. * Inits a time stamp query for the given render context.
  43741. *
  43742. * @param {RenderContext} renderContext - The render context.
  43743. */
  43744. initTimestampQuery( renderContext ) {
  43745. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  43746. const type = renderContext.isComputeNode ? 'compute' : 'render';
  43747. if ( ! this.timestampQueryPool[ type ] ) {
  43748. // TODO: Variable maxQueries?
  43749. this.timestampQueryPool[ type ] = new WebGLTimestampQueryPool( this.gl, type, 2048 );
  43750. }
  43751. const timestampQueryPool = this.timestampQueryPool[ type ];
  43752. const baseOffset = timestampQueryPool.allocateQueriesForContext( renderContext );
  43753. if ( baseOffset !== null ) {
  43754. timestampQueryPool.beginQuery( renderContext );
  43755. }
  43756. }
  43757. // timestamp utils
  43758. /**
  43759. * Prepares the timestamp buffer.
  43760. *
  43761. * @param {RenderContext} renderContext - The render context.
  43762. */
  43763. prepareTimestampBuffer( renderContext ) {
  43764. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  43765. const type = renderContext.isComputeNode ? 'compute' : 'render';
  43766. const timestampQueryPool = this.timestampQueryPool[ type ];
  43767. timestampQueryPool.endQuery( renderContext );
  43768. }
  43769. /**
  43770. * Returns the backend's rendering context.
  43771. *
  43772. * @return {WebGL2RenderingContext} The rendering context.
  43773. */
  43774. getContext() {
  43775. return this.gl;
  43776. }
  43777. /**
  43778. * This method is executed at the beginning of a render call and prepares
  43779. * the WebGL state for upcoming render calls
  43780. *
  43781. * @param {RenderContext} renderContext - The render context.
  43782. */
  43783. beginRender( renderContext ) {
  43784. const { state } = this;
  43785. const renderContextData = this.get( renderContext );
  43786. //
  43787. if ( renderContext.viewport ) {
  43788. this.updateViewport( renderContext );
  43789. } else {
  43790. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  43791. state.viewport( 0, 0, width, height );
  43792. }
  43793. if ( renderContext.scissor ) {
  43794. const { x, y, width, height } = renderContext.scissorValue;
  43795. state.scissor( x, renderContext.height - height - y, width, height );
  43796. }
  43797. //
  43798. this.initTimestampQuery( renderContext );
  43799. renderContextData.previousContext = this._currentContext;
  43800. this._currentContext = renderContext;
  43801. this._setFramebuffer( renderContext );
  43802. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  43803. const occlusionQueryCount = renderContext.occlusionQueryCount;
  43804. if ( occlusionQueryCount > 0 ) {
  43805. // Get a reference to the array of objects with queries. The renderContextData property
  43806. // can be changed by another render pass before the async reading of all previous queries complete
  43807. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  43808. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  43809. renderContextData.lastOcclusionObject = null;
  43810. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  43811. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  43812. renderContextData.occlusionQueryIndex = 0;
  43813. }
  43814. }
  43815. /**
  43816. * This method is executed at the end of a render call and finalizes work
  43817. * after draw calls.
  43818. *
  43819. * @param {RenderContext} renderContext - The render context.
  43820. */
  43821. finishRender( renderContext ) {
  43822. const { gl, state } = this;
  43823. const renderContextData = this.get( renderContext );
  43824. const previousContext = renderContextData.previousContext;
  43825. state.resetVertexState();
  43826. const occlusionQueryCount = renderContext.occlusionQueryCount;
  43827. if ( occlusionQueryCount > 0 ) {
  43828. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  43829. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  43830. }
  43831. this.resolveOccludedAsync( renderContext );
  43832. }
  43833. const textures = renderContext.textures;
  43834. if ( textures !== null ) {
  43835. for ( let i = 0; i < textures.length; i ++ ) {
  43836. const texture = textures[ i ];
  43837. if ( texture.generateMipmaps ) {
  43838. this.generateMipmaps( texture );
  43839. }
  43840. }
  43841. }
  43842. this._currentContext = previousContext;
  43843. if ( renderContext.textures !== null && renderContext.renderTarget ) {
  43844. const renderTargetContextData = this.get( renderContext.renderTarget );
  43845. const { resolveDepthBuffer, samples } = renderContext.renderTarget;
  43846. if ( samples > 0 && this._useMultisampledExtension( renderContext.renderTarget ) === false ) {
  43847. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  43848. const mask = gl.COLOR_BUFFER_BIT;
  43849. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  43850. const textures = renderContext.textures;
  43851. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  43852. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  43853. for ( let i = 0; i < textures.length; i ++ ) {
  43854. // TODO Add support for MRT
  43855. if ( renderContext.scissor ) {
  43856. const { x, y, width, height } = renderContext.scissorValue;
  43857. const viewY = renderContext.height - height - y;
  43858. gl.blitFramebuffer( x, viewY, x + width, viewY + height, x, viewY, x + width, viewY + height, mask, gl.NEAREST );
  43859. if ( this._supportsInvalidateFramebuffer === true ) {
  43860. gl.invalidateSubFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray, x, viewY, width, height );
  43861. }
  43862. } else {
  43863. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  43864. if ( this._supportsInvalidateFramebuffer === true ) {
  43865. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  43866. }
  43867. }
  43868. }
  43869. } else if ( resolveDepthBuffer === false && renderTargetContextData.framebuffers ) {
  43870. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  43871. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  43872. gl.invalidateFramebuffer( gl.DRAW_FRAMEBUFFER, renderTargetContextData.depthInvalidationArray );
  43873. }
  43874. }
  43875. if ( previousContext !== null ) {
  43876. this._setFramebuffer( previousContext );
  43877. if ( previousContext.viewport ) {
  43878. this.updateViewport( previousContext );
  43879. } else {
  43880. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  43881. state.viewport( 0, 0, width, height );
  43882. }
  43883. }
  43884. this.prepareTimestampBuffer( renderContext );
  43885. }
  43886. /**
  43887. * This method processes the result of occlusion queries and writes it
  43888. * into render context data.
  43889. *
  43890. * @async
  43891. * @param {RenderContext} renderContext - The render context.
  43892. */
  43893. resolveOccludedAsync( renderContext ) {
  43894. const renderContextData = this.get( renderContext );
  43895. // handle occlusion query results
  43896. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  43897. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  43898. const occluded = new WeakSet();
  43899. const { gl } = this;
  43900. renderContextData.currentOcclusionQueryObjects = null;
  43901. renderContextData.currentOcclusionQueries = null;
  43902. const check = () => {
  43903. let completed = 0;
  43904. // check all queries and requeue as appropriate
  43905. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  43906. const query = currentOcclusionQueries[ i ];
  43907. if ( query === null ) continue;
  43908. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  43909. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) === 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  43910. currentOcclusionQueries[ i ] = null;
  43911. gl.deleteQuery( query );
  43912. completed ++;
  43913. }
  43914. }
  43915. if ( completed < currentOcclusionQueries.length ) {
  43916. requestAnimationFrame( check );
  43917. } else {
  43918. renderContextData.occluded = occluded;
  43919. }
  43920. };
  43921. check();
  43922. }
  43923. }
  43924. /**
  43925. * Returns `true` if the given 3D object is fully occluded by other
  43926. * 3D objects in the scene.
  43927. *
  43928. * @param {RenderContext} renderContext - The render context.
  43929. * @param {Object3D} object - The 3D object to test.
  43930. * @return {boolean} Whether the 3D object is fully occluded or not.
  43931. */
  43932. isOccluded( renderContext, object ) {
  43933. const renderContextData = this.get( renderContext );
  43934. return renderContextData.occluded && renderContextData.occluded.has( object );
  43935. }
  43936. /**
  43937. * Updates the viewport with the values from the given render context.
  43938. *
  43939. * @param {RenderContext} renderContext - The render context.
  43940. */
  43941. updateViewport( renderContext ) {
  43942. const { state } = this;
  43943. const { x, y, width, height } = renderContext.viewportValue;
  43944. state.viewport( x, renderContext.height - height - y, width, height );
  43945. }
  43946. /**
  43947. * Defines the scissor test.
  43948. *
  43949. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  43950. */
  43951. setScissorTest( boolean ) {
  43952. const state = this.state;
  43953. state.setScissorTest( boolean );
  43954. }
  43955. /**
  43956. * Returns the clear color and alpha into a single
  43957. * color object.
  43958. *
  43959. * @return {Color4} The clear color.
  43960. */
  43961. getClearColor() {
  43962. const clearColor = super.getClearColor();
  43963. // Since the canvas is always created with alpha: true,
  43964. // WebGL must always premultiply the clear color.
  43965. clearColor.r *= clearColor.a;
  43966. clearColor.g *= clearColor.a;
  43967. clearColor.b *= clearColor.a;
  43968. return clearColor;
  43969. }
  43970. /**
  43971. * Performs a clear operation.
  43972. *
  43973. * @param {boolean} color - Whether the color buffer should be cleared or not.
  43974. * @param {boolean} depth - Whether the depth buffer should be cleared or not.
  43975. * @param {boolean} stencil - Whether the stencil buffer should be cleared or not.
  43976. * @param {?Object} [descriptor=null] - The render context of the current set render target.
  43977. * @param {boolean} [setFrameBuffer=true] - TODO.
  43978. */
  43979. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true ) {
  43980. const { gl, renderer } = this;
  43981. if ( descriptor === null ) {
  43982. const clearColor = this.getClearColor();
  43983. descriptor = {
  43984. textures: null,
  43985. clearColorValue: clearColor
  43986. };
  43987. }
  43988. //
  43989. let clear = 0;
  43990. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  43991. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  43992. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  43993. if ( clear !== 0 ) {
  43994. let clearColor;
  43995. if ( descriptor.clearColorValue ) {
  43996. clearColor = descriptor.clearColorValue;
  43997. } else {
  43998. clearColor = this.getClearColor();
  43999. }
  44000. const clearDepth = renderer.getClearDepth();
  44001. const clearStencil = renderer.getClearStencil();
  44002. if ( depth ) this.state.setDepthMask( true );
  44003. if ( descriptor.textures === null ) {
  44004. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  44005. gl.clear( clear );
  44006. } else {
  44007. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  44008. if ( color ) {
  44009. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  44010. if ( i === 0 ) {
  44011. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  44012. } else {
  44013. gl.clearBufferfv( gl.COLOR, i, [ 0, 0, 0, 1 ] );
  44014. }
  44015. }
  44016. }
  44017. if ( depth && stencil ) {
  44018. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, clearDepth, clearStencil );
  44019. } else if ( depth ) {
  44020. gl.clearBufferfv( gl.DEPTH, 0, [ clearDepth ] );
  44021. } else if ( stencil ) {
  44022. gl.clearBufferiv( gl.STENCIL, 0, [ clearStencil ] );
  44023. }
  44024. }
  44025. }
  44026. }
  44027. /**
  44028. * This method is executed at the beginning of a compute call and
  44029. * prepares the state for upcoming compute tasks.
  44030. *
  44031. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  44032. */
  44033. beginCompute( computeGroup ) {
  44034. const { state, gl } = this;
  44035. state.bindFramebuffer( gl.FRAMEBUFFER, null );
  44036. this.initTimestampQuery( computeGroup );
  44037. }
  44038. /**
  44039. * Executes a compute command for the given compute node.
  44040. *
  44041. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  44042. * @param {Node} computeNode - The compute node.
  44043. * @param {Array<BindGroup>} bindings - The bindings.
  44044. * @param {ComputePipeline} pipeline - The compute pipeline.
  44045. */
  44046. compute( computeGroup, computeNode, bindings, pipeline ) {
  44047. const { state, gl } = this;
  44048. if ( this.discard === false ) {
  44049. // required here to handle async behaviour of render.compute()
  44050. gl.enable( gl.RASTERIZER_DISCARD );
  44051. this.discard = true;
  44052. }
  44053. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  44054. const vaoKey = this._getVaoKey( attributes );
  44055. const vaoGPU = this.vaoCache[ vaoKey ];
  44056. if ( vaoGPU === undefined ) {
  44057. this._createVao( attributes );
  44058. } else {
  44059. state.setVertexState( vaoGPU );
  44060. }
  44061. state.useProgram( programGPU );
  44062. this._bindUniforms( bindings );
  44063. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  44064. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  44065. gl.beginTransformFeedback( gl.POINTS );
  44066. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  44067. gl.drawArraysInstanced( gl.POINTS, 0, 1, computeNode.count );
  44068. } else {
  44069. gl.drawArrays( gl.POINTS, 0, computeNode.count );
  44070. }
  44071. gl.endTransformFeedback();
  44072. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  44073. // switch active buffers
  44074. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  44075. const dualAttributeData = transformBuffers[ i ];
  44076. if ( dualAttributeData.pbo ) {
  44077. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  44078. }
  44079. dualAttributeData.switchBuffers();
  44080. }
  44081. }
  44082. /**
  44083. * This method is executed at the end of a compute call and
  44084. * finalizes work after compute tasks.
  44085. *
  44086. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  44087. */
  44088. finishCompute( computeGroup ) {
  44089. const gl = this.gl;
  44090. this.discard = false;
  44091. gl.disable( gl.RASTERIZER_DISCARD );
  44092. this.prepareTimestampBuffer( computeGroup );
  44093. if ( this._currentContext ) {
  44094. this._setFramebuffer( this._currentContext );
  44095. }
  44096. }
  44097. /**
  44098. * Internal to determine if the current render target is a render target array with depth 2D array texture.
  44099. *
  44100. * @param {RenderContext} renderContext - The render context.
  44101. * @return {boolean} Whether the render target is a render target array with depth 2D array texture.
  44102. *
  44103. * @private
  44104. */
  44105. _isRenderCameraDepthArray( renderContext ) {
  44106. return renderContext.depthTexture && renderContext.depthTexture.isArrayTexture && renderContext.camera.isArrayCamera;
  44107. }
  44108. /**
  44109. * Executes a draw command for the given render object.
  44110. *
  44111. * @param {RenderObject} renderObject - The render object to draw.
  44112. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  44113. */
  44114. draw( renderObject/*, info*/ ) {
  44115. const { object, pipeline, material, context, hardwareClippingPlanes } = renderObject;
  44116. const { programGPU } = this.get( pipeline );
  44117. const { gl, state } = this;
  44118. const contextData = this.get( context );
  44119. const drawParams = renderObject.getDrawParameters();
  44120. if ( drawParams === null ) return;
  44121. //
  44122. this._bindUniforms( renderObject.getBindings() );
  44123. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  44124. state.setMaterial( material, frontFaceCW, hardwareClippingPlanes );
  44125. state.useProgram( programGPU );
  44126. // vertex state
  44127. const renderObjectData = this.get( renderObject );
  44128. let vaoGPU = renderObjectData.staticVao;
  44129. if ( vaoGPU === undefined || renderObjectData.geometryId !== renderObject.geometry.id ) {
  44130. const vaoKey = this._getVaoKey( renderObject.getAttributes() );
  44131. vaoGPU = this.vaoCache[ vaoKey ];
  44132. if ( vaoGPU === undefined ) {
  44133. let staticVao;
  44134. ( { vaoGPU, staticVao } = this._createVao( renderObject.getAttributes() ) );
  44135. if ( staticVao ) {
  44136. renderObjectData.staticVao = vaoGPU;
  44137. renderObjectData.geometryId = renderObject.geometry.id;
  44138. }
  44139. }
  44140. }
  44141. const index = renderObject.getIndex();
  44142. const indexGPU = ( index !== null ) ? this.get( index ).bufferGPU : null;
  44143. state.setVertexState( vaoGPU, indexGPU );
  44144. //
  44145. const lastObject = contextData.lastOcclusionObject;
  44146. if ( lastObject !== object && lastObject !== undefined ) {
  44147. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  44148. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  44149. contextData.occlusionQueryIndex ++;
  44150. }
  44151. if ( object.occlusionTest === true ) {
  44152. const query = gl.createQuery();
  44153. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  44154. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  44155. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  44156. }
  44157. contextData.lastOcclusionObject = object;
  44158. }
  44159. //
  44160. const renderer = this.bufferRenderer;
  44161. if ( object.isPoints ) renderer.mode = gl.POINTS;
  44162. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  44163. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  44164. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  44165. else {
  44166. if ( material.wireframe === true ) {
  44167. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  44168. renderer.mode = gl.LINES;
  44169. } else {
  44170. renderer.mode = gl.TRIANGLES;
  44171. }
  44172. }
  44173. //
  44174. const { vertexCount, instanceCount } = drawParams;
  44175. let { firstVertex } = drawParams;
  44176. renderer.object = object;
  44177. if ( index !== null ) {
  44178. firstVertex *= index.array.BYTES_PER_ELEMENT;
  44179. const indexData = this.get( index );
  44180. renderer.index = index.count;
  44181. renderer.type = indexData.type;
  44182. } else {
  44183. renderer.index = 0;
  44184. }
  44185. const draw = () => {
  44186. if ( object.isBatchedMesh ) {
  44187. if ( object._multiDrawInstances !== null ) {
  44188. // @deprecated, r174
  44189. warnOnce( 'THREE.WebGLBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  44190. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  44191. } else if ( ! this.hasFeature( 'WEBGL_multi_draw' ) ) {
  44192. warnOnce( 'THREE.WebGLRenderer: WEBGL_multi_draw not supported.' );
  44193. } else {
  44194. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  44195. }
  44196. } else if ( instanceCount > 1 ) {
  44197. renderer.renderInstances( firstVertex, vertexCount, instanceCount );
  44198. } else {
  44199. renderer.render( firstVertex, vertexCount );
  44200. }
  44201. };
  44202. if ( renderObject.camera.isArrayCamera === true && renderObject.camera.cameras.length > 0 && renderObject.camera.isMultiViewCamera === false ) {
  44203. const cameraData = this.get( renderObject.camera );
  44204. const cameras = renderObject.camera.cameras;
  44205. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' ).bindings[ 0 ];
  44206. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  44207. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  44208. const indexesGPU = [];
  44209. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  44210. const bufferGPU = gl.createBuffer();
  44211. data[ 0 ] = i;
  44212. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  44213. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.STATIC_DRAW );
  44214. indexesGPU.push( bufferGPU );
  44215. }
  44216. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  44217. }
  44218. const cameraIndexData = this.get( cameraIndex );
  44219. const pixelRatio = this.renderer.getPixelRatio();
  44220. const renderTarget = this._currentContext.renderTarget;
  44221. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( this._currentContext );
  44222. const prevActiveCubeFace = this._currentContext.activeCubeFace;
  44223. if ( isRenderCameraDepthArray ) {
  44224. // Clear the depth texture
  44225. const textureData = this.get( renderTarget.depthTexture );
  44226. if ( textureData.clearedRenderId !== this.renderer._nodes.nodeFrame.renderId ) {
  44227. textureData.clearedRenderId = this.renderer._nodes.nodeFrame.renderId;
  44228. const { stencilBuffer } = renderTarget;
  44229. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  44230. this.renderer._activeCubeFace = i;
  44231. this._currentContext.activeCubeFace = i;
  44232. this._setFramebuffer( this._currentContext );
  44233. this.clear( false, true, stencilBuffer, this._currentContext, false );
  44234. }
  44235. this.renderer._activeCubeFace = prevActiveCubeFace;
  44236. this._currentContext.activeCubeFace = prevActiveCubeFace;
  44237. }
  44238. }
  44239. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  44240. const subCamera = cameras[ i ];
  44241. if ( object.layers.test( subCamera.layers ) ) {
  44242. if ( isRenderCameraDepthArray ) {
  44243. // Update the active layer
  44244. this.renderer._activeCubeFace = i;
  44245. this._currentContext.activeCubeFace = i;
  44246. this._setFramebuffer( this._currentContext );
  44247. }
  44248. const vp = subCamera.viewport;
  44249. if ( vp !== undefined ) {
  44250. const x = vp.x * pixelRatio;
  44251. const y = vp.y * pixelRatio;
  44252. const width = vp.width * pixelRatio;
  44253. const height = vp.height * pixelRatio;
  44254. state.viewport(
  44255. Math.floor( x ),
  44256. Math.floor( renderObject.context.height - height - y ),
  44257. Math.floor( width ),
  44258. Math.floor( height )
  44259. );
  44260. }
  44261. state.bindBufferBase( gl.UNIFORM_BUFFER, cameraIndexData.index, cameraData.indexesGPU[ i ] );
  44262. draw();
  44263. }
  44264. this._currentContext.activeCubeFace = prevActiveCubeFace;
  44265. this.renderer._activeCubeFace = prevActiveCubeFace;
  44266. }
  44267. } else {
  44268. draw();
  44269. }
  44270. }
  44271. /**
  44272. * Explain why always null is returned.
  44273. *
  44274. * @param {RenderObject} renderObject - The render object.
  44275. * @return {boolean} Whether the render pipeline requires an update or not.
  44276. */
  44277. needsRenderUpdate( /*renderObject*/ ) {
  44278. return false;
  44279. }
  44280. /**
  44281. * Explain why no cache key is computed.
  44282. *
  44283. * @param {RenderObject} renderObject - The render object.
  44284. * @return {string} The cache key.
  44285. */
  44286. getRenderCacheKey( /*renderObject*/ ) {
  44287. return '';
  44288. }
  44289. // textures
  44290. /**
  44291. * Creates a default texture for the given texture that can be used
  44292. * as a placeholder until the actual texture is ready for usage.
  44293. *
  44294. * @param {Texture} texture - The texture to create a default texture for.
  44295. */
  44296. createDefaultTexture( texture ) {
  44297. this.textureUtils.createDefaultTexture( texture );
  44298. }
  44299. /**
  44300. * Defines a texture on the GPU for the given texture object.
  44301. *
  44302. * @param {Texture} texture - The texture.
  44303. * @param {Object} [options={}] - Optional configuration parameter.
  44304. */
  44305. createTexture( texture, options ) {
  44306. this.textureUtils.createTexture( texture, options );
  44307. }
  44308. /**
  44309. * Uploads the updated texture data to the GPU.
  44310. *
  44311. * @param {Texture} texture - The texture.
  44312. * @param {Object} [options={}] - Optional configuration parameter.
  44313. */
  44314. updateTexture( texture, options ) {
  44315. this.textureUtils.updateTexture( texture, options );
  44316. }
  44317. /**
  44318. * Generates mipmaps for the given texture.
  44319. *
  44320. * @param {Texture} texture - The texture.
  44321. */
  44322. generateMipmaps( texture ) {
  44323. this.textureUtils.generateMipmaps( texture );
  44324. }
  44325. /**
  44326. * Destroys the GPU data for the given texture object.
  44327. *
  44328. * @param {Texture} texture - The texture.
  44329. */
  44330. destroyTexture( texture ) {
  44331. this.textureUtils.destroyTexture( texture );
  44332. }
  44333. /**
  44334. * Returns texture data as a typed array.
  44335. *
  44336. * @async
  44337. * @param {Texture} texture - The texture to copy.
  44338. * @param {number} x - The x coordinate of the copy origin.
  44339. * @param {number} y - The y coordinate of the copy origin.
  44340. * @param {number} width - The width of the copy.
  44341. * @param {number} height - The height of the copy.
  44342. * @param {number} faceIndex - The face index.
  44343. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  44344. */
  44345. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  44346. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  44347. }
  44348. /**
  44349. * This method does nothing since WebGL 2 has no concept of samplers.
  44350. *
  44351. * @param {Texture} texture - The texture to create the sampler for.
  44352. */
  44353. createSampler( /*texture*/ ) {
  44354. //console.warn( 'Abstract class.' );
  44355. }
  44356. /**
  44357. * This method does nothing since WebGL 2 has no concept of samplers.
  44358. *
  44359. * @param {Texture} texture - The texture to destroy the sampler for.
  44360. */
  44361. destroySampler( /*texture*/ ) {}
  44362. // node builder
  44363. /**
  44364. * Returns a node builder for the given render object.
  44365. *
  44366. * @param {RenderObject} object - The render object.
  44367. * @param {Renderer} renderer - The renderer.
  44368. * @return {GLSLNodeBuilder} The node builder.
  44369. */
  44370. createNodeBuilder( object, renderer ) {
  44371. return new GLSLNodeBuilder( object, renderer );
  44372. }
  44373. // program
  44374. /**
  44375. * Creates a shader program from the given programmable stage.
  44376. *
  44377. * @param {ProgrammableStage} program - The programmable stage.
  44378. */
  44379. createProgram( program ) {
  44380. const gl = this.gl;
  44381. const { stage, code } = program;
  44382. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  44383. gl.shaderSource( shader, code );
  44384. gl.compileShader( shader );
  44385. this.set( program, {
  44386. shaderGPU: shader
  44387. } );
  44388. }
  44389. /**
  44390. * Destroys the shader program of the given programmable stage.
  44391. *
  44392. * @param {ProgrammableStage} program - The programmable stage.
  44393. */
  44394. destroyProgram( program ) {
  44395. this.delete( program );
  44396. }
  44397. /**
  44398. * Creates a render pipeline for the given render object.
  44399. *
  44400. * @param {RenderObject} renderObject - The render object.
  44401. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  44402. */
  44403. createRenderPipeline( renderObject, promises ) {
  44404. const gl = this.gl;
  44405. const pipeline = renderObject.pipeline;
  44406. // Program
  44407. const { fragmentProgram, vertexProgram } = pipeline;
  44408. const programGPU = gl.createProgram();
  44409. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  44410. const vertexShader = this.get( vertexProgram ).shaderGPU;
  44411. gl.attachShader( programGPU, fragmentShader );
  44412. gl.attachShader( programGPU, vertexShader );
  44413. gl.linkProgram( programGPU );
  44414. this.set( pipeline, {
  44415. programGPU,
  44416. fragmentShader,
  44417. vertexShader
  44418. } );
  44419. if ( promises !== null && this.parallel ) {
  44420. const p = new Promise( ( resolve /*, reject*/ ) => {
  44421. const parallel = this.parallel;
  44422. const checkStatus = () => {
  44423. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  44424. this._completeCompile( renderObject, pipeline );
  44425. resolve();
  44426. } else {
  44427. requestAnimationFrame( checkStatus );
  44428. }
  44429. };
  44430. checkStatus();
  44431. } );
  44432. promises.push( p );
  44433. return;
  44434. }
  44435. this._completeCompile( renderObject, pipeline );
  44436. }
  44437. /**
  44438. * Formats the source code of error messages.
  44439. *
  44440. * @private
  44441. * @param {string} string - The code.
  44442. * @param {number} errorLine - The error line.
  44443. * @return {string} The formatted code.
  44444. */
  44445. _handleSource( string, errorLine ) {
  44446. const lines = string.split( '\n' );
  44447. const lines2 = [];
  44448. const from = Math.max( errorLine - 6, 0 );
  44449. const to = Math.min( errorLine + 6, lines.length );
  44450. for ( let i = from; i < to; i ++ ) {
  44451. const line = i + 1;
  44452. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  44453. }
  44454. return lines2.join( '\n' );
  44455. }
  44456. /**
  44457. * Gets the shader compilation errors from the info log.
  44458. *
  44459. * @private
  44460. * @param {WebGL2RenderingContext} gl - The rendering context.
  44461. * @param {WebGLShader} shader - The WebGL shader object.
  44462. * @param {string} type - The shader type.
  44463. * @return {string} The shader errors.
  44464. */
  44465. _getShaderErrors( gl, shader, type ) {
  44466. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  44467. const errors = gl.getShaderInfoLog( shader ).trim();
  44468. if ( status && errors === '' ) return '';
  44469. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  44470. if ( errorMatches ) {
  44471. const errorLine = parseInt( errorMatches[ 1 ] );
  44472. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  44473. } else {
  44474. return errors;
  44475. }
  44476. }
  44477. /**
  44478. * Logs shader compilation errors.
  44479. *
  44480. * @private
  44481. * @param {WebGLProgram} programGPU - The WebGL program.
  44482. * @param {WebGLShader} glFragmentShader - The fragment shader as a native WebGL shader object.
  44483. * @param {WebGLShader} glVertexShader - The vertex shader as a native WebGL shader object.
  44484. */
  44485. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  44486. if ( this.renderer.debug.checkShaderErrors ) {
  44487. const gl = this.gl;
  44488. const programLog = gl.getProgramInfoLog( programGPU ).trim();
  44489. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  44490. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  44491. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  44492. } else {
  44493. // default error reporting
  44494. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  44495. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  44496. console.error(
  44497. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  44498. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  44499. 'Program Info Log: ' + programLog + '\n' +
  44500. vertexErrors + '\n' +
  44501. fragmentErrors
  44502. );
  44503. }
  44504. } else if ( programLog !== '' ) {
  44505. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  44506. }
  44507. }
  44508. }
  44509. /**
  44510. * Completes the shader program setup for the given render object.
  44511. *
  44512. * @private
  44513. * @param {RenderObject} renderObject - The render object.
  44514. * @param {RenderPipeline} pipeline - The render pipeline.
  44515. */
  44516. _completeCompile( renderObject, pipeline ) {
  44517. const { state, gl } = this;
  44518. const pipelineData = this.get( pipeline );
  44519. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  44520. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  44521. this._logProgramError( programGPU, fragmentShader, vertexShader );
  44522. }
  44523. state.useProgram( programGPU );
  44524. // Bindings
  44525. const bindings = renderObject.getBindings();
  44526. this._setupBindings( bindings, programGPU );
  44527. //
  44528. this.set( pipeline, {
  44529. programGPU
  44530. } );
  44531. }
  44532. /**
  44533. * Creates a compute pipeline for the given compute node.
  44534. *
  44535. * @param {ComputePipeline} computePipeline - The compute pipeline.
  44536. * @param {Array<BindGroup>} bindings - The bindings.
  44537. */
  44538. createComputePipeline( computePipeline, bindings ) {
  44539. const { state, gl } = this;
  44540. // Program
  44541. const fragmentProgram = {
  44542. stage: 'fragment',
  44543. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  44544. };
  44545. this.createProgram( fragmentProgram );
  44546. const { computeProgram } = computePipeline;
  44547. const programGPU = gl.createProgram();
  44548. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  44549. const vertexShader = this.get( computeProgram ).shaderGPU;
  44550. const transforms = computeProgram.transforms;
  44551. const transformVaryingNames = [];
  44552. const transformAttributeNodes = [];
  44553. for ( let i = 0; i < transforms.length; i ++ ) {
  44554. const transform = transforms[ i ];
  44555. transformVaryingNames.push( transform.varyingName );
  44556. transformAttributeNodes.push( transform.attributeNode );
  44557. }
  44558. gl.attachShader( programGPU, fragmentShader );
  44559. gl.attachShader( programGPU, vertexShader );
  44560. gl.transformFeedbackVaryings(
  44561. programGPU,
  44562. transformVaryingNames,
  44563. gl.SEPARATE_ATTRIBS
  44564. );
  44565. gl.linkProgram( programGPU );
  44566. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  44567. this._logProgramError( programGPU, fragmentShader, vertexShader );
  44568. }
  44569. state.useProgram( programGPU );
  44570. // Bindings
  44571. this._setupBindings( bindings, programGPU );
  44572. const attributeNodes = computeProgram.attributes;
  44573. const attributes = [];
  44574. const transformBuffers = [];
  44575. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  44576. const attribute = attributeNodes[ i ].node.attribute;
  44577. attributes.push( attribute );
  44578. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  44579. }
  44580. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  44581. const attribute = transformAttributeNodes[ i ].attribute;
  44582. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  44583. const attributeData = this.get( attribute );
  44584. transformBuffers.push( attributeData );
  44585. }
  44586. //
  44587. this.set( computePipeline, {
  44588. programGPU,
  44589. transformBuffers,
  44590. attributes
  44591. } );
  44592. }
  44593. /**
  44594. * Creates bindings from the given bind group definition.
  44595. *
  44596. * @param {BindGroup} bindGroup - The bind group.
  44597. * @param {Array<BindGroup>} bindings - Array of bind groups.
  44598. * @param {number} cacheIndex - The cache index.
  44599. * @param {number} version - The version.
  44600. */
  44601. createBindings( bindGroup, bindings /*, cacheIndex, version*/ ) {
  44602. if ( this._knownBindings.has( bindings ) === false ) {
  44603. this._knownBindings.add( bindings );
  44604. let uniformBuffers = 0;
  44605. let textures = 0;
  44606. for ( const bindGroup of bindings ) {
  44607. this.set( bindGroup, {
  44608. textures: textures,
  44609. uniformBuffers: uniformBuffers
  44610. } );
  44611. for ( const binding of bindGroup.bindings ) {
  44612. if ( binding.isUniformBuffer ) uniformBuffers ++;
  44613. if ( binding.isSampledTexture ) textures ++;
  44614. }
  44615. }
  44616. }
  44617. this.updateBindings( bindGroup, bindings );
  44618. }
  44619. /**
  44620. * Updates the given bind group definition.
  44621. *
  44622. * @param {BindGroup} bindGroup - The bind group.
  44623. * @param {Array<BindGroup>} bindings - Array of bind groups.
  44624. * @param {number} cacheIndex - The cache index.
  44625. * @param {number} version - The version.
  44626. */
  44627. updateBindings( bindGroup /*, bindings, cacheIndex, version*/ ) {
  44628. const { gl } = this;
  44629. const bindGroupData = this.get( bindGroup );
  44630. let i = bindGroupData.uniformBuffers;
  44631. let t = bindGroupData.textures;
  44632. for ( const binding of bindGroup.bindings ) {
  44633. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  44634. const data = binding.buffer;
  44635. const bufferGPU = gl.createBuffer();
  44636. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  44637. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  44638. this.set( binding, {
  44639. index: i ++,
  44640. bufferGPU
  44641. } );
  44642. } else if ( binding.isSampledTexture ) {
  44643. const { textureGPU, glTextureType } = this.get( binding.texture );
  44644. this.set( binding, {
  44645. index: t ++,
  44646. textureGPU,
  44647. glTextureType
  44648. } );
  44649. }
  44650. }
  44651. }
  44652. /**
  44653. * Updates a buffer binding.
  44654. *
  44655. * @param {Buffer} binding - The buffer binding to update.
  44656. */
  44657. updateBinding( binding ) {
  44658. const gl = this.gl;
  44659. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  44660. const bindingData = this.get( binding );
  44661. const bufferGPU = bindingData.bufferGPU;
  44662. const data = binding.buffer;
  44663. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  44664. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  44665. }
  44666. }
  44667. // attributes
  44668. /**
  44669. * Creates the GPU buffer of an indexed shader attribute.
  44670. *
  44671. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  44672. */
  44673. createIndexAttribute( attribute ) {
  44674. const gl = this.gl;
  44675. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  44676. }
  44677. /**
  44678. * Creates the GPU buffer of a shader attribute.
  44679. *
  44680. * @param {BufferAttribute} attribute - The buffer attribute.
  44681. */
  44682. createAttribute( attribute ) {
  44683. if ( this.has( attribute ) ) return;
  44684. const gl = this.gl;
  44685. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  44686. }
  44687. /**
  44688. * Creates the GPU buffer of a storage attribute.
  44689. *
  44690. * @param {BufferAttribute} attribute - The buffer attribute.
  44691. */
  44692. createStorageAttribute( attribute ) {
  44693. if ( this.has( attribute ) ) return;
  44694. const gl = this.gl;
  44695. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  44696. }
  44697. /**
  44698. * Updates the GPU buffer of a shader attribute.
  44699. *
  44700. * @param {BufferAttribute} attribute - The buffer attribute to update.
  44701. */
  44702. updateAttribute( attribute ) {
  44703. this.attributeUtils.updateAttribute( attribute );
  44704. }
  44705. /**
  44706. * Destroys the GPU buffer of a shader attribute.
  44707. *
  44708. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  44709. */
  44710. destroyAttribute( attribute ) {
  44711. this.attributeUtils.destroyAttribute( attribute );
  44712. }
  44713. /**
  44714. * Checks if the given feature is supported by the backend.
  44715. *
  44716. * @param {string} name - The feature's name.
  44717. * @return {boolean} Whether the feature is supported or not.
  44718. */
  44719. hasFeature( name ) {
  44720. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  44721. const extensions = this.extensions;
  44722. for ( let i = 0; i < keysMatching.length; i ++ ) {
  44723. if ( extensions.has( keysMatching[ i ] ) ) return true;
  44724. }
  44725. return false;
  44726. }
  44727. /**
  44728. * Returns the maximum anisotropy texture filtering value.
  44729. *
  44730. * @return {number} The maximum anisotropy texture filtering value.
  44731. */
  44732. getMaxAnisotropy() {
  44733. return this.capabilities.getMaxAnisotropy();
  44734. }
  44735. /**
  44736. * Copies data of the given source texture to the given destination texture.
  44737. *
  44738. * @param {Texture} srcTexture - The source texture.
  44739. * @param {Texture} dstTexture - The destination texture.
  44740. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  44741. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  44742. * @param {number} [srcLevel=0] - The source mip level to copy from.
  44743. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  44744. */
  44745. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  44746. this.textureUtils.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, srcLevel, dstLevel );
  44747. }
  44748. /**
  44749. * Copies the current bound framebuffer to the given texture.
  44750. *
  44751. * @param {Texture} texture - The destination texture.
  44752. * @param {RenderContext} renderContext - The render context.
  44753. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  44754. */
  44755. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  44756. this.textureUtils.copyFramebufferToTexture( texture, renderContext, rectangle );
  44757. }
  44758. /**
  44759. * Configures the active framebuffer from the given render context.
  44760. *
  44761. * @private
  44762. * @param {RenderContext} descriptor - The render context.
  44763. */
  44764. _setFramebuffer( descriptor ) {
  44765. const { gl, state } = this;
  44766. let currentFrameBuffer = null;
  44767. if ( descriptor.textures !== null ) {
  44768. const renderTarget = descriptor.renderTarget;
  44769. const renderTargetContextData = this.get( renderTarget );
  44770. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  44771. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  44772. const isRenderTarget3D = renderTarget.isRenderTarget3D === true;
  44773. const isRenderTargetArray = renderTarget.depth > 1;
  44774. const isXRRenderTarget = renderTarget.isXRRenderTarget === true;
  44775. const hasExternalTextures = ( isXRRenderTarget === true && renderTarget.hasExternalTextures === true );
  44776. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  44777. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  44778. const multisampledRTTExt = this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  44779. const multiviewExt = this.extensions.get( 'OVR_multiview2' );
  44780. const useMultisampledRTT = this._useMultisampledExtension( renderTarget );
  44781. const cacheKey = getCacheKey( descriptor );
  44782. let fb;
  44783. if ( isCube ) {
  44784. renderTargetContextData.cubeFramebuffers || ( renderTargetContextData.cubeFramebuffers = {} );
  44785. fb = renderTargetContextData.cubeFramebuffers[ cacheKey ];
  44786. } else if ( isXRRenderTarget && hasExternalTextures === false ) {
  44787. fb = this._xrFramebuffer;
  44788. } else {
  44789. renderTargetContextData.framebuffers || ( renderTargetContextData.framebuffers = {} );
  44790. fb = renderTargetContextData.framebuffers[ cacheKey ];
  44791. }
  44792. if ( fb === undefined ) {
  44793. fb = gl.createFramebuffer();
  44794. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  44795. const textures = descriptor.textures;
  44796. const depthInvalidationArray = [];
  44797. if ( isCube ) {
  44798. renderTargetContextData.cubeFramebuffers[ cacheKey ] = fb;
  44799. const { textureGPU } = this.get( textures[ 0 ] );
  44800. const cubeFace = this.renderer._activeCubeFace;
  44801. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, 0 );
  44802. } else {
  44803. renderTargetContextData.framebuffers[ cacheKey ] = fb;
  44804. for ( let i = 0; i < textures.length; i ++ ) {
  44805. const texture = textures[ i ];
  44806. const textureData = this.get( texture );
  44807. textureData.renderTarget = descriptor.renderTarget;
  44808. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  44809. const attachment = gl.COLOR_ATTACHMENT0 + i;
  44810. if ( renderTarget.multiview ) {
  44811. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, attachment, textureData.textureGPU, 0, samples, 0, 2 );
  44812. } else if ( isRenderTarget3D || isRenderTargetArray ) {
  44813. const layer = this.renderer._activeCubeFace;
  44814. gl.framebufferTextureLayer( gl.FRAMEBUFFER, attachment, textureData.textureGPU, 0, layer );
  44815. } else {
  44816. if ( useMultisampledRTT ) {
  44817. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  44818. } else {
  44819. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  44820. }
  44821. }
  44822. }
  44823. state.drawBuffers( descriptor, fb );
  44824. }
  44825. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  44826. if ( renderTarget.autoAllocateDepthBuffer === true ) {
  44827. const renderbuffer = gl.createRenderbuffer();
  44828. this.textureUtils.setupRenderBufferStorage( renderbuffer, descriptor, 0, useMultisampledRTT );
  44829. renderTargetContextData.xrDepthRenderbuffer = renderbuffer;
  44830. depthInvalidationArray.push( stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT );
  44831. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  44832. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, depthStyle, gl.RENDERBUFFER, renderbuffer );
  44833. } else {
  44834. if ( descriptor.depthTexture !== null ) {
  44835. depthInvalidationArray.push( stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT );
  44836. const textureData = this.get( descriptor.depthTexture );
  44837. textureData.renderTarget = descriptor.renderTarget;
  44838. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  44839. if ( renderTarget.multiview ) {
  44840. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, samples, 0, 2 );
  44841. } else if ( hasExternalTextures && useMultisampledRTT ) {
  44842. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  44843. } else {
  44844. if ( descriptor.depthTexture.isArrayTexture ) {
  44845. const layer = this.renderer._activeCubeFace;
  44846. gl.framebufferTextureLayer( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, layer );
  44847. } else {
  44848. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  44849. }
  44850. }
  44851. }
  44852. }
  44853. renderTargetContextData.depthInvalidationArray = depthInvalidationArray;
  44854. } else {
  44855. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( descriptor );
  44856. if ( isRenderCameraDepthArray ) {
  44857. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  44858. const layer = this.renderer._activeCubeFace;
  44859. const depthData = this.get( descriptor.depthTexture );
  44860. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  44861. gl.framebufferTextureLayer(
  44862. gl.FRAMEBUFFER,
  44863. depthStyle,
  44864. depthData.textureGPU,
  44865. 0,
  44866. layer
  44867. );
  44868. }
  44869. // rebind external XR textures
  44870. if ( isXRRenderTarget || useMultisampledRTT || renderTarget.multiview ) {
  44871. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  44872. // rebind color
  44873. const textureData = this.get( descriptor.textures[ 0 ] );
  44874. if ( renderTarget.multiview ) {
  44875. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, textureData.textureGPU, 0, samples, 0, 2 );
  44876. } else if ( useMultisampledRTT ) {
  44877. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  44878. } else {
  44879. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  44880. }
  44881. // rebind depth
  44882. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  44883. if ( renderTarget.autoAllocateDepthBuffer === true ) {
  44884. const renderbuffer = renderTargetContextData.xrDepthRenderbuffer;
  44885. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  44886. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, depthStyle, gl.RENDERBUFFER, renderbuffer );
  44887. } else {
  44888. const textureData = this.get( descriptor.depthTexture );
  44889. if ( renderTarget.multiview ) {
  44890. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, samples, 0, 2 );
  44891. } else if ( useMultisampledRTT ) {
  44892. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  44893. } else {
  44894. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  44895. }
  44896. }
  44897. }
  44898. }
  44899. if ( samples > 0 && useMultisampledRTT === false && ! renderTarget.multiview ) {
  44900. if ( msaaFb === undefined ) {
  44901. const invalidationArray = [];
  44902. msaaFb = gl.createFramebuffer();
  44903. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  44904. const msaaRenderbuffers = [];
  44905. const textures = descriptor.textures;
  44906. for ( let i = 0; i < textures.length; i ++ ) {
  44907. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  44908. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  44909. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  44910. if ( depthBuffer ) {
  44911. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  44912. invalidationArray.push( depthStyle );
  44913. }
  44914. const texture = descriptor.textures[ i ];
  44915. const textureData = this.get( texture );
  44916. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, descriptor.width, descriptor.height );
  44917. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  44918. }
  44919. renderTargetContextData.msaaFrameBuffer = msaaFb;
  44920. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  44921. if ( depthRenderbuffer === undefined ) {
  44922. depthRenderbuffer = gl.createRenderbuffer();
  44923. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, descriptor, samples );
  44924. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  44925. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  44926. invalidationArray.push( depthStyle );
  44927. }
  44928. renderTargetContextData.invalidationArray = invalidationArray;
  44929. }
  44930. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  44931. } else {
  44932. currentFrameBuffer = fb;
  44933. }
  44934. }
  44935. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  44936. }
  44937. /**
  44938. * Computes the VAO key for the given index and attributes.
  44939. *
  44940. * @private
  44941. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  44942. * @return {string} The VAO key.
  44943. */
  44944. _getVaoKey( attributes ) {
  44945. let key = '';
  44946. for ( let i = 0; i < attributes.length; i ++ ) {
  44947. const attributeData = this.get( attributes[ i ] );
  44948. key += ':' + attributeData.id;
  44949. }
  44950. return key;
  44951. }
  44952. /**
  44953. * Creates a VAO from the index and attributes.
  44954. *
  44955. * @private
  44956. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  44957. * @return {Object} The VAO data.
  44958. */
  44959. _createVao( attributes ) {
  44960. const { gl } = this;
  44961. const vaoGPU = gl.createVertexArray();
  44962. let key = '';
  44963. let staticVao = true;
  44964. gl.bindVertexArray( vaoGPU );
  44965. for ( let i = 0; i < attributes.length; i ++ ) {
  44966. const attribute = attributes[ i ];
  44967. const attributeData = this.get( attribute );
  44968. key += ':' + attributeData.id;
  44969. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  44970. gl.enableVertexAttribArray( i );
  44971. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) staticVao = false;
  44972. let stride, offset;
  44973. if ( attribute.isInterleavedBufferAttribute === true ) {
  44974. stride = attribute.data.stride * attributeData.bytesPerElement;
  44975. offset = attribute.offset * attributeData.bytesPerElement;
  44976. } else {
  44977. stride = 0;
  44978. offset = 0;
  44979. }
  44980. if ( attributeData.isInteger ) {
  44981. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  44982. } else {
  44983. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  44984. }
  44985. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  44986. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  44987. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  44988. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  44989. }
  44990. }
  44991. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  44992. this.vaoCache[ key ] = vaoGPU;
  44993. return { vaoGPU, staticVao };
  44994. }
  44995. /**
  44996. * Creates a transform feedback from the given transform buffers.
  44997. *
  44998. * @private
  44999. * @param {Array<DualAttributeData>} transformBuffers - The transform buffers.
  45000. * @return {WebGLTransformFeedback} The transform feedback.
  45001. */
  45002. _getTransformFeedback( transformBuffers ) {
  45003. let key = '';
  45004. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  45005. key += ':' + transformBuffers[ i ].id;
  45006. }
  45007. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  45008. if ( transformFeedbackGPU !== undefined ) {
  45009. return transformFeedbackGPU;
  45010. }
  45011. const { gl } = this;
  45012. transformFeedbackGPU = gl.createTransformFeedback();
  45013. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  45014. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  45015. const attributeData = transformBuffers[ i ];
  45016. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  45017. }
  45018. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  45019. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  45020. return transformFeedbackGPU;
  45021. }
  45022. /**
  45023. * Setups the given bindings.
  45024. *
  45025. * @private
  45026. * @param {Array<BindGroup>} bindings - The bindings.
  45027. * @param {WebGLProgram} programGPU - The WebGL program.
  45028. */
  45029. _setupBindings( bindings, programGPU ) {
  45030. const gl = this.gl;
  45031. for ( const bindGroup of bindings ) {
  45032. for ( const binding of bindGroup.bindings ) {
  45033. const bindingData = this.get( binding );
  45034. const index = bindingData.index;
  45035. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  45036. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  45037. gl.uniformBlockBinding( programGPU, location, index );
  45038. } else if ( binding.isSampledTexture ) {
  45039. const location = gl.getUniformLocation( programGPU, binding.name );
  45040. gl.uniform1i( location, index );
  45041. }
  45042. }
  45043. }
  45044. }
  45045. /**
  45046. * Binds the given uniforms.
  45047. *
  45048. * @private
  45049. * @param {Array<BindGroup>} bindings - The bindings.
  45050. */
  45051. _bindUniforms( bindings ) {
  45052. const { gl, state } = this;
  45053. for ( const bindGroup of bindings ) {
  45054. for ( const binding of bindGroup.bindings ) {
  45055. const bindingData = this.get( binding );
  45056. const index = bindingData.index;
  45057. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  45058. // TODO USE bindBufferRange to group multiple uniform buffers
  45059. state.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  45060. } else if ( binding.isSampledTexture ) {
  45061. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  45062. }
  45063. }
  45064. }
  45065. }
  45066. /**
  45067. * Returns `true` if the `WEBGL_multisampled_render_to_texture` extension
  45068. * should be used when MSAA is enabled.
  45069. *
  45070. * @private
  45071. * @param {RenderTarget} renderTarget - The render target that should be multisampled.
  45072. * @return {boolean} Whether to use the `WEBGL_multisampled_render_to_texture` extension for MSAA or not.
  45073. */
  45074. _useMultisampledExtension( renderTarget ) {
  45075. if ( renderTarget.multiview === true ) {
  45076. return true;
  45077. }
  45078. return renderTarget.samples > 0 && this.extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTarget.autoAllocateDepthBuffer !== false;
  45079. }
  45080. /**
  45081. * Frees internal resources.
  45082. */
  45083. dispose() {
  45084. const extension = this.extensions.get( 'WEBGL_lose_context' );
  45085. if ( extension ) extension.loseContext();
  45086. this.renderer.domElement.removeEventListener( 'webglcontextlost', this._onContextLost );
  45087. }
  45088. }
  45089. const GPUPrimitiveTopology = {
  45090. PointList: 'point-list',
  45091. LineList: 'line-list',
  45092. LineStrip: 'line-strip',
  45093. TriangleList: 'triangle-list',
  45094. TriangleStrip: 'triangle-strip',
  45095. };
  45096. const GPUCompareFunction = {
  45097. Never: 'never',
  45098. Less: 'less',
  45099. Equal: 'equal',
  45100. LessEqual: 'less-equal',
  45101. Greater: 'greater',
  45102. NotEqual: 'not-equal',
  45103. GreaterEqual: 'greater-equal',
  45104. Always: 'always'
  45105. };
  45106. const GPUStoreOp = {
  45107. Store: 'store'};
  45108. const GPULoadOp = {
  45109. Load: 'load',
  45110. Clear: 'clear'
  45111. };
  45112. const GPUFrontFace = {
  45113. CCW: 'ccw'};
  45114. const GPUCullMode = {
  45115. None: 'none',
  45116. Front: 'front',
  45117. Back: 'back'
  45118. };
  45119. const GPUIndexFormat = {
  45120. Uint16: 'uint16',
  45121. Uint32: 'uint32'
  45122. };
  45123. const GPUTextureFormat = {
  45124. // 8-bit formats
  45125. R8Unorm: 'r8unorm',
  45126. R8Snorm: 'r8snorm',
  45127. R8Uint: 'r8uint',
  45128. R8Sint: 'r8sint',
  45129. // 16-bit formats
  45130. R16Uint: 'r16uint',
  45131. R16Sint: 'r16sint',
  45132. R16Float: 'r16float',
  45133. RG8Unorm: 'rg8unorm',
  45134. RG8Snorm: 'rg8snorm',
  45135. RG8Uint: 'rg8uint',
  45136. RG8Sint: 'rg8sint',
  45137. // 32-bit formats
  45138. R32Uint: 'r32uint',
  45139. R32Sint: 'r32sint',
  45140. R32Float: 'r32float',
  45141. RG16Uint: 'rg16uint',
  45142. RG16Sint: 'rg16sint',
  45143. RG16Float: 'rg16float',
  45144. RGBA8Unorm: 'rgba8unorm',
  45145. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  45146. RGBA8Snorm: 'rgba8snorm',
  45147. RGBA8Uint: 'rgba8uint',
  45148. RGBA8Sint: 'rgba8sint',
  45149. BGRA8Unorm: 'bgra8unorm',
  45150. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  45151. // Packed 32-bit formats
  45152. RGB9E5UFloat: 'rgb9e5ufloat',
  45153. RGB10A2Unorm: 'rgb10a2unorm',
  45154. RG11B10UFloat: 'rgb10a2unorm',
  45155. // 64-bit formats
  45156. RG32Uint: 'rg32uint',
  45157. RG32Sint: 'rg32sint',
  45158. RG32Float: 'rg32float',
  45159. RGBA16Uint: 'rgba16uint',
  45160. RGBA16Sint: 'rgba16sint',
  45161. RGBA16Float: 'rgba16float',
  45162. // 128-bit formats
  45163. RGBA32Uint: 'rgba32uint',
  45164. RGBA32Sint: 'rgba32sint',
  45165. RGBA32Float: 'rgba32float',
  45166. Depth16Unorm: 'depth16unorm',
  45167. Depth24Plus: 'depth24plus',
  45168. Depth24PlusStencil8: 'depth24plus-stencil8',
  45169. Depth32Float: 'depth32float',
  45170. // 'depth32float-stencil8' extension
  45171. Depth32FloatStencil8: 'depth32float-stencil8',
  45172. // BC compressed formats usable if 'texture-compression-bc' is both
  45173. // supported by the device/user agent and enabled in requestDevice.
  45174. BC1RGBAUnorm: 'bc1-rgba-unorm',
  45175. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  45176. BC2RGBAUnorm: 'bc2-rgba-unorm',
  45177. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  45178. BC3RGBAUnorm: 'bc3-rgba-unorm',
  45179. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  45180. BC4RUnorm: 'bc4-r-unorm',
  45181. BC4RSnorm: 'bc4-r-snorm',
  45182. BC5RGUnorm: 'bc5-rg-unorm',
  45183. BC5RGSnorm: 'bc5-rg-snorm',
  45184. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  45185. BC6HRGBFloat: 'bc6h-rgb-float',
  45186. BC7RGBAUnorm: 'bc7-rgba-unorm',
  45187. BC7RGBAUnormSRGB: 'bc7-rgba-srgb',
  45188. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  45189. // supported by the device/user agent and enabled in requestDevice.
  45190. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  45191. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  45192. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  45193. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  45194. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  45195. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  45196. EACR11Unorm: 'eac-r11unorm',
  45197. EACR11Snorm: 'eac-r11snorm',
  45198. EACRG11Unorm: 'eac-rg11unorm',
  45199. EACRG11Snorm: 'eac-rg11snorm',
  45200. // ASTC compressed formats usable if 'texture-compression-astc' is both
  45201. // supported by the device/user agent and enabled in requestDevice.
  45202. ASTC4x4Unorm: 'astc-4x4-unorm',
  45203. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  45204. ASTC5x4Unorm: 'astc-5x4-unorm',
  45205. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  45206. ASTC5x5Unorm: 'astc-5x5-unorm',
  45207. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  45208. ASTC6x5Unorm: 'astc-6x5-unorm',
  45209. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  45210. ASTC6x6Unorm: 'astc-6x6-unorm',
  45211. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  45212. ASTC8x5Unorm: 'astc-8x5-unorm',
  45213. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  45214. ASTC8x6Unorm: 'astc-8x6-unorm',
  45215. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  45216. ASTC8x8Unorm: 'astc-8x8-unorm',
  45217. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  45218. ASTC10x5Unorm: 'astc-10x5-unorm',
  45219. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  45220. ASTC10x6Unorm: 'astc-10x6-unorm',
  45221. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  45222. ASTC10x8Unorm: 'astc-10x8-unorm',
  45223. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  45224. ASTC10x10Unorm: 'astc-10x10-unorm',
  45225. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  45226. ASTC12x10Unorm: 'astc-12x10-unorm',
  45227. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  45228. ASTC12x12Unorm: 'astc-12x12-unorm',
  45229. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  45230. };
  45231. const GPUAddressMode = {
  45232. ClampToEdge: 'clamp-to-edge',
  45233. Repeat: 'repeat',
  45234. MirrorRepeat: 'mirror-repeat'
  45235. };
  45236. const GPUFilterMode = {
  45237. Linear: 'linear',
  45238. Nearest: 'nearest'
  45239. };
  45240. const GPUBlendFactor = {
  45241. Zero: 'zero',
  45242. One: 'one',
  45243. Src: 'src',
  45244. OneMinusSrc: 'one-minus-src',
  45245. SrcAlpha: 'src-alpha',
  45246. OneMinusSrcAlpha: 'one-minus-src-alpha',
  45247. Dst: 'dst',
  45248. OneMinusDst: 'one-minus-dst',
  45249. DstAlpha: 'dst-alpha',
  45250. OneMinusDstAlpha: 'one-minus-dst-alpha',
  45251. SrcAlphaSaturated: 'src-alpha-saturated',
  45252. Constant: 'constant',
  45253. OneMinusConstant: 'one-minus-constant'
  45254. };
  45255. const GPUBlendOperation = {
  45256. Add: 'add',
  45257. Subtract: 'subtract',
  45258. ReverseSubtract: 'reverse-subtract',
  45259. Min: 'min',
  45260. Max: 'max'
  45261. };
  45262. const GPUColorWriteFlags = {
  45263. None: 0,
  45264. All: 0xF
  45265. };
  45266. const GPUStencilOperation = {
  45267. Keep: 'keep',
  45268. Zero: 'zero',
  45269. Replace: 'replace',
  45270. Invert: 'invert',
  45271. IncrementClamp: 'increment-clamp',
  45272. DecrementClamp: 'decrement-clamp',
  45273. IncrementWrap: 'increment-wrap',
  45274. DecrementWrap: 'decrement-wrap'
  45275. };
  45276. const GPUBufferBindingType = {
  45277. Storage: 'storage',
  45278. ReadOnlyStorage: 'read-only-storage'
  45279. };
  45280. const GPUStorageTextureAccess = {
  45281. WriteOnly: 'write-only',
  45282. ReadOnly: 'read-only',
  45283. ReadWrite: 'read-write',
  45284. };
  45285. const GPUSamplerBindingType = {
  45286. NonFiltering: 'non-filtering',
  45287. Comparison: 'comparison'
  45288. };
  45289. const GPUTextureSampleType = {
  45290. Float: 'float',
  45291. UnfilterableFloat: 'unfilterable-float',
  45292. Depth: 'depth',
  45293. SInt: 'sint',
  45294. UInt: 'uint'
  45295. };
  45296. const GPUTextureDimension = {
  45297. TwoD: '2d',
  45298. ThreeD: '3d'
  45299. };
  45300. const GPUTextureViewDimension = {
  45301. TwoD: '2d',
  45302. TwoDArray: '2d-array',
  45303. Cube: 'cube',
  45304. ThreeD: '3d'
  45305. };
  45306. const GPUTextureAspect = {
  45307. All: 'all'};
  45308. const GPUInputStepMode = {
  45309. Vertex: 'vertex',
  45310. Instance: 'instance'
  45311. };
  45312. const GPUFeatureName = {
  45313. DepthClipControl: 'depth-clip-control',
  45314. Depth32FloatStencil8: 'depth32float-stencil8',
  45315. TextureCompressionBC: 'texture-compression-bc',
  45316. TextureCompressionETC2: 'texture-compression-etc2',
  45317. TextureCompressionASTC: 'texture-compression-astc',
  45318. TimestampQuery: 'timestamp-query',
  45319. IndirectFirstInstance: 'indirect-first-instance',
  45320. ShaderF16: 'shader-f16',
  45321. RG11B10UFloat: 'rg11b10ufloat-renderable',
  45322. BGRA8UNormStorage: 'bgra8unorm-storage',
  45323. Float32Filterable: 'float32-filterable',
  45324. ClipDistances: 'clip-distances',
  45325. DualSourceBlending: 'dual-source-blending',
  45326. Subgroups: 'subgroups'
  45327. };
  45328. /**
  45329. * Represents a sampler binding type.
  45330. *
  45331. * @private
  45332. * @augments Binding
  45333. */
  45334. class Sampler extends Binding {
  45335. /**
  45336. * Constructs a new sampler.
  45337. *
  45338. * @param {string} name - The samplers's name.
  45339. * @param {?Texture} texture - The texture this binding is referring to.
  45340. */
  45341. constructor( name, texture ) {
  45342. super( name );
  45343. /**
  45344. * The texture the sampler is referring to.
  45345. *
  45346. * @type {?Texture}
  45347. */
  45348. this.texture = texture;
  45349. /**
  45350. * The binding's version.
  45351. *
  45352. * @type {number}
  45353. */
  45354. this.version = texture ? texture.version : 0;
  45355. /**
  45356. * This flag can be used for type testing.
  45357. *
  45358. * @type {boolean}
  45359. * @readonly
  45360. * @default true
  45361. */
  45362. this.isSampler = true;
  45363. }
  45364. }
  45365. /**
  45366. * A special form of sampler binding type.
  45367. * It's texture value is managed by a node object.
  45368. *
  45369. * @private
  45370. * @augments Sampler
  45371. */
  45372. class NodeSampler extends Sampler {
  45373. /**
  45374. * Constructs a new node-based sampler.
  45375. *
  45376. * @param {string} name - The samplers's name.
  45377. * @param {TextureNode} textureNode - The texture node.
  45378. * @param {UniformGroupNode} groupNode - The uniform group node.
  45379. */
  45380. constructor( name, textureNode, groupNode ) {
  45381. super( name, textureNode ? textureNode.value : null );
  45382. /**
  45383. * The texture node.
  45384. *
  45385. * @type {TextureNode}
  45386. */
  45387. this.textureNode = textureNode;
  45388. /**
  45389. * The uniform group node.
  45390. *
  45391. * @type {UniformGroupNode}
  45392. */
  45393. this.groupNode = groupNode;
  45394. }
  45395. /**
  45396. * Updates the texture value of this sampler.
  45397. */
  45398. update() {
  45399. this.texture = this.textureNode.value;
  45400. }
  45401. }
  45402. /**
  45403. * Represents a storage buffer binding type.
  45404. *
  45405. * @private
  45406. * @augments Buffer
  45407. */
  45408. class StorageBuffer extends Buffer {
  45409. /**
  45410. * Constructs a new uniform buffer.
  45411. *
  45412. * @param {string} name - The buffer's name.
  45413. * @param {BufferAttribute} attribute - The buffer attribute.
  45414. */
  45415. constructor( name, attribute ) {
  45416. super( name, attribute ? attribute.array : null );
  45417. /**
  45418. * This flag can be used for type testing.
  45419. *
  45420. * @type {BufferAttribute}
  45421. */
  45422. this.attribute = attribute;
  45423. /**
  45424. * This flag can be used for type testing.
  45425. *
  45426. * @type {boolean}
  45427. * @readonly
  45428. * @default true
  45429. */
  45430. this.isStorageBuffer = true;
  45431. }
  45432. }
  45433. let _id = 0;
  45434. /**
  45435. * A special form of storage buffer binding type.
  45436. * It's buffer value is managed by a node object.
  45437. *
  45438. * @private
  45439. * @augments StorageBuffer
  45440. */
  45441. class NodeStorageBuffer extends StorageBuffer {
  45442. /**
  45443. * Constructs a new node-based storage buffer.
  45444. *
  45445. * @param {StorageBufferNode} nodeUniform - The storage buffer node.
  45446. * @param {UniformGroupNode} groupNode - The uniform group node.
  45447. */
  45448. constructor( nodeUniform, groupNode ) {
  45449. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  45450. /**
  45451. * The node uniform.
  45452. *
  45453. * @type {StorageBufferNode}
  45454. */
  45455. this.nodeUniform = nodeUniform;
  45456. /**
  45457. * The access type.
  45458. *
  45459. * @type {string}
  45460. */
  45461. this.access = nodeUniform ? nodeUniform.access : NodeAccess.READ_WRITE;
  45462. /**
  45463. * The uniform group node.
  45464. *
  45465. * @type {UniformGroupNode}
  45466. */
  45467. this.groupNode = groupNode;
  45468. }
  45469. /**
  45470. * The storage buffer.
  45471. *
  45472. * @type {BufferAttribute}
  45473. */
  45474. get buffer() {
  45475. return this.nodeUniform.value;
  45476. }
  45477. }
  45478. /**
  45479. * A WebGPU backend utility module used by {@link WebGPUTextureUtils}.
  45480. *
  45481. * @private
  45482. */
  45483. class WebGPUTexturePassUtils extends DataMap {
  45484. /**
  45485. * Constructs a new utility object.
  45486. *
  45487. * @param {GPUDevice} device - The WebGPU device.
  45488. */
  45489. constructor( device ) {
  45490. super();
  45491. /**
  45492. * The WebGPU device.
  45493. *
  45494. * @type {GPUDevice}
  45495. */
  45496. this.device = device;
  45497. const mipmapVertexSource = `
  45498. struct VarysStruct {
  45499. @builtin( position ) Position: vec4<f32>,
  45500. @location( 0 ) vTex : vec2<f32>
  45501. };
  45502. @vertex
  45503. fn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {
  45504. var Varys : VarysStruct;
  45505. var pos = array< vec2<f32>, 4 >(
  45506. vec2<f32>( -1.0, 1.0 ),
  45507. vec2<f32>( 1.0, 1.0 ),
  45508. vec2<f32>( -1.0, -1.0 ),
  45509. vec2<f32>( 1.0, -1.0 )
  45510. );
  45511. var tex = array< vec2<f32>, 4 >(
  45512. vec2<f32>( 0.0, 0.0 ),
  45513. vec2<f32>( 1.0, 0.0 ),
  45514. vec2<f32>( 0.0, 1.0 ),
  45515. vec2<f32>( 1.0, 1.0 )
  45516. );
  45517. Varys.vTex = tex[ vertexIndex ];
  45518. Varys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );
  45519. return Varys;
  45520. }
  45521. `;
  45522. const mipmapFragmentSource = `
  45523. @group( 0 ) @binding( 0 )
  45524. var imgSampler : sampler;
  45525. @group( 0 ) @binding( 1 )
  45526. var img : texture_2d<f32>;
  45527. @fragment
  45528. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  45529. return textureSample( img, imgSampler, vTex );
  45530. }
  45531. `;
  45532. const flipYFragmentSource = `
  45533. @group( 0 ) @binding( 0 )
  45534. var imgSampler : sampler;
  45535. @group( 0 ) @binding( 1 )
  45536. var img : texture_2d<f32>;
  45537. @fragment
  45538. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  45539. return textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );
  45540. }
  45541. `;
  45542. /**
  45543. * The mipmap GPU sampler.
  45544. *
  45545. * @type {GPUSampler}
  45546. */
  45547. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  45548. /**
  45549. * The flipY GPU sampler.
  45550. *
  45551. * @type {GPUSampler}
  45552. */
  45553. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  45554. /**
  45555. * A cache for GPU render pipelines used for copy/transfer passes.
  45556. * Every texture format requires a unique pipeline.
  45557. *
  45558. * @type {Object<string,GPURenderPipeline>}
  45559. */
  45560. this.transferPipelines = {};
  45561. /**
  45562. * A cache for GPU render pipelines used for flipY passes.
  45563. * Every texture format requires a unique pipeline.
  45564. *
  45565. * @type {Object<string,GPURenderPipeline>}
  45566. */
  45567. this.flipYPipelines = {};
  45568. /**
  45569. * The mipmap vertex shader module.
  45570. *
  45571. * @type {GPUShaderModule}
  45572. */
  45573. this.mipmapVertexShaderModule = device.createShaderModule( {
  45574. label: 'mipmapVertex',
  45575. code: mipmapVertexSource
  45576. } );
  45577. /**
  45578. * The mipmap fragment shader module.
  45579. *
  45580. * @type {GPUShaderModule}
  45581. */
  45582. this.mipmapFragmentShaderModule = device.createShaderModule( {
  45583. label: 'mipmapFragment',
  45584. code: mipmapFragmentSource
  45585. } );
  45586. /**
  45587. * The flipY fragment shader module.
  45588. *
  45589. * @type {GPUShaderModule}
  45590. */
  45591. this.flipYFragmentShaderModule = device.createShaderModule( {
  45592. label: 'flipYFragment',
  45593. code: flipYFragmentSource
  45594. } );
  45595. }
  45596. /**
  45597. * Returns a render pipeline for the internal copy render pass. The pass
  45598. * requires a unique render pipeline for each texture format.
  45599. *
  45600. * @param {string} format - The GPU texture format
  45601. * @return {GPURenderPipeline} The GPU render pipeline.
  45602. */
  45603. getTransferPipeline( format ) {
  45604. let pipeline = this.transferPipelines[ format ];
  45605. if ( pipeline === undefined ) {
  45606. pipeline = this.device.createRenderPipeline( {
  45607. label: `mipmap-${ format }`,
  45608. vertex: {
  45609. module: this.mipmapVertexShaderModule,
  45610. entryPoint: 'main'
  45611. },
  45612. fragment: {
  45613. module: this.mipmapFragmentShaderModule,
  45614. entryPoint: 'main',
  45615. targets: [ { format } ]
  45616. },
  45617. primitive: {
  45618. topology: GPUPrimitiveTopology.TriangleStrip,
  45619. stripIndexFormat: GPUIndexFormat.Uint32
  45620. },
  45621. layout: 'auto'
  45622. } );
  45623. this.transferPipelines[ format ] = pipeline;
  45624. }
  45625. return pipeline;
  45626. }
  45627. /**
  45628. * Returns a render pipeline for the flipY render pass. The pass
  45629. * requires a unique render pipeline for each texture format.
  45630. *
  45631. * @param {string} format - The GPU texture format
  45632. * @return {GPURenderPipeline} The GPU render pipeline.
  45633. */
  45634. getFlipYPipeline( format ) {
  45635. let pipeline = this.flipYPipelines[ format ];
  45636. if ( pipeline === undefined ) {
  45637. pipeline = this.device.createRenderPipeline( {
  45638. label: `flipY-${ format }`,
  45639. vertex: {
  45640. module: this.mipmapVertexShaderModule,
  45641. entryPoint: 'main'
  45642. },
  45643. fragment: {
  45644. module: this.flipYFragmentShaderModule,
  45645. entryPoint: 'main',
  45646. targets: [ { format } ]
  45647. },
  45648. primitive: {
  45649. topology: GPUPrimitiveTopology.TriangleStrip,
  45650. stripIndexFormat: GPUIndexFormat.Uint32
  45651. },
  45652. layout: 'auto'
  45653. } );
  45654. this.flipYPipelines[ format ] = pipeline;
  45655. }
  45656. return pipeline;
  45657. }
  45658. /**
  45659. * Flip the contents of the given GPU texture along its vertical axis.
  45660. *
  45661. * @param {GPUTexture} textureGPU - The GPU texture object.
  45662. * @param {Object} textureGPUDescriptor - The texture descriptor.
  45663. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  45664. */
  45665. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  45666. const format = textureGPUDescriptor.format;
  45667. const { width, height } = textureGPUDescriptor.size;
  45668. const transferPipeline = this.getTransferPipeline( format );
  45669. const flipYPipeline = this.getFlipYPipeline( format );
  45670. const tempTexture = this.device.createTexture( {
  45671. size: { width, height, depthOrArrayLayers: 1 },
  45672. format,
  45673. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
  45674. } );
  45675. const srcView = textureGPU.createView( {
  45676. baseMipLevel: 0,
  45677. mipLevelCount: 1,
  45678. dimension: GPUTextureViewDimension.TwoD,
  45679. baseArrayLayer
  45680. } );
  45681. const dstView = tempTexture.createView( {
  45682. baseMipLevel: 0,
  45683. mipLevelCount: 1,
  45684. dimension: GPUTextureViewDimension.TwoD,
  45685. baseArrayLayer: 0
  45686. } );
  45687. const commandEncoder = this.device.createCommandEncoder( {} );
  45688. const pass = ( pipeline, sourceView, destinationView ) => {
  45689. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  45690. const bindGroup = this.device.createBindGroup( {
  45691. layout: bindGroupLayout,
  45692. entries: [ {
  45693. binding: 0,
  45694. resource: this.flipYSampler
  45695. }, {
  45696. binding: 1,
  45697. resource: sourceView
  45698. } ]
  45699. } );
  45700. const passEncoder = commandEncoder.beginRenderPass( {
  45701. colorAttachments: [ {
  45702. view: destinationView,
  45703. loadOp: GPULoadOp.Clear,
  45704. storeOp: GPUStoreOp.Store,
  45705. clearValue: [ 0, 0, 0, 0 ]
  45706. } ]
  45707. } );
  45708. passEncoder.setPipeline( pipeline );
  45709. passEncoder.setBindGroup( 0, bindGroup );
  45710. passEncoder.draw( 4, 1, 0, 0 );
  45711. passEncoder.end();
  45712. };
  45713. pass( transferPipeline, srcView, dstView );
  45714. pass( flipYPipeline, dstView, srcView );
  45715. this.device.queue.submit( [ commandEncoder.finish() ] );
  45716. tempTexture.destroy();
  45717. }
  45718. /**
  45719. * Generates mipmaps for the given GPU texture.
  45720. *
  45721. * @param {GPUTexture} textureGPU - The GPU texture object.
  45722. * @param {Object} textureGPUDescriptor - The texture descriptor.
  45723. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  45724. */
  45725. generateMipmaps( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  45726. const textureData = this.get( textureGPU );
  45727. if ( textureData.useCount === undefined ) {
  45728. textureData.useCount = 0;
  45729. textureData.layers = [];
  45730. }
  45731. const passes = textureData.layers[ baseArrayLayer ] || this._mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer );
  45732. const commandEncoder = this.device.createCommandEncoder( {} );
  45733. this._mipmapRunBundles( commandEncoder, passes );
  45734. this.device.queue.submit( [ commandEncoder.finish() ] );
  45735. if ( textureData.useCount !== 0 ) textureData.layers[ baseArrayLayer ] = passes;
  45736. textureData.useCount ++;
  45737. }
  45738. /**
  45739. * Since multiple copy render passes are required to generate mipmaps, the passes
  45740. * are managed as render bundles to improve performance.
  45741. *
  45742. * @param {GPUTexture} textureGPU - The GPU texture object.
  45743. * @param {Object} textureGPUDescriptor - The texture descriptor.
  45744. * @param {number} baseArrayLayer - The index of the first array layer accessible to the texture view.
  45745. * @return {Array<Object>} An array of render bundles.
  45746. */
  45747. _mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer ) {
  45748. const pipeline = this.getTransferPipeline( textureGPUDescriptor.format );
  45749. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  45750. let srcView = textureGPU.createView( {
  45751. baseMipLevel: 0,
  45752. mipLevelCount: 1,
  45753. dimension: GPUTextureViewDimension.TwoD,
  45754. baseArrayLayer
  45755. } );
  45756. const passes = [];
  45757. for ( let i = 1; i < textureGPUDescriptor.mipLevelCount; i ++ ) {
  45758. const bindGroup = this.device.createBindGroup( {
  45759. layout: bindGroupLayout,
  45760. entries: [ {
  45761. binding: 0,
  45762. resource: this.mipmapSampler
  45763. }, {
  45764. binding: 1,
  45765. resource: srcView
  45766. } ]
  45767. } );
  45768. const dstView = textureGPU.createView( {
  45769. baseMipLevel: i,
  45770. mipLevelCount: 1,
  45771. dimension: GPUTextureViewDimension.TwoD,
  45772. baseArrayLayer
  45773. } );
  45774. const passDescriptor = {
  45775. colorAttachments: [ {
  45776. view: dstView,
  45777. loadOp: GPULoadOp.Clear,
  45778. storeOp: GPUStoreOp.Store,
  45779. clearValue: [ 0, 0, 0, 0 ]
  45780. } ]
  45781. };
  45782. const passEncoder = this.device.createRenderBundleEncoder( {
  45783. colorFormats: [ textureGPUDescriptor.format ]
  45784. } );
  45785. passEncoder.setPipeline( pipeline );
  45786. passEncoder.setBindGroup( 0, bindGroup );
  45787. passEncoder.draw( 4, 1, 0, 0 );
  45788. passes.push( {
  45789. renderBundles: [ passEncoder.finish() ],
  45790. passDescriptor
  45791. } );
  45792. srcView = dstView;
  45793. }
  45794. return passes;
  45795. }
  45796. /**
  45797. * Executes the render bundles.
  45798. *
  45799. * @param {GPUCommandEncoder} commandEncoder - The GPU command encoder.
  45800. * @param {Array<Object>} passes - An array of render bundles.
  45801. */
  45802. _mipmapRunBundles( commandEncoder, passes ) {
  45803. const levels = passes.length;
  45804. for ( let i = 0; i < levels; i ++ ) {
  45805. const pass = passes[ i ];
  45806. const passEncoder = commandEncoder.beginRenderPass( pass.passDescriptor );
  45807. passEncoder.executeBundles( pass.renderBundles );
  45808. passEncoder.end();
  45809. }
  45810. }
  45811. }
  45812. const _compareToWebGPU = {
  45813. [ NeverCompare ]: 'never',
  45814. [ LessCompare ]: 'less',
  45815. [ EqualCompare ]: 'equal',
  45816. [ LessEqualCompare ]: 'less-equal',
  45817. [ GreaterCompare ]: 'greater',
  45818. [ GreaterEqualCompare ]: 'greater-equal',
  45819. [ AlwaysCompare ]: 'always',
  45820. [ NotEqualCompare ]: 'not-equal'
  45821. };
  45822. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  45823. /**
  45824. * A WebGPU backend utility module for managing textures.
  45825. *
  45826. * @private
  45827. */
  45828. class WebGPUTextureUtils {
  45829. /**
  45830. * Constructs a new utility object.
  45831. *
  45832. * @param {WebGPUBackend} backend - The WebGPU backend.
  45833. */
  45834. constructor( backend ) {
  45835. /**
  45836. * A reference to the WebGPU backend.
  45837. *
  45838. * @type {WebGPUBackend}
  45839. */
  45840. this.backend = backend;
  45841. /**
  45842. * A reference to the pass utils.
  45843. *
  45844. * @type {?WebGPUTexturePassUtils}
  45845. * @default null
  45846. */
  45847. this._passUtils = null;
  45848. /**
  45849. * A dictionary for managing default textures. The key
  45850. * is the texture format, the value the texture object.
  45851. *
  45852. * @type {Object<string,Texture>}
  45853. */
  45854. this.defaultTexture = {};
  45855. /**
  45856. * A dictionary for managing default cube textures. The key
  45857. * is the texture format, the value the texture object.
  45858. *
  45859. * @type {Object<string,CubeTexture>}
  45860. */
  45861. this.defaultCubeTexture = {};
  45862. /**
  45863. * A default video frame.
  45864. *
  45865. * @type {?VideoFrame}
  45866. * @default null
  45867. */
  45868. this.defaultVideoFrame = null;
  45869. /**
  45870. * Represents the color attachment of the default framebuffer.
  45871. *
  45872. * @type {?GPUTexture}
  45873. * @default null
  45874. */
  45875. this.colorBuffer = null;
  45876. /**
  45877. * Represents the depth attachment of the default framebuffer.
  45878. *
  45879. * @type {DepthTexture}
  45880. */
  45881. this.depthTexture = new DepthTexture();
  45882. this.depthTexture.name = 'depthBuffer';
  45883. }
  45884. /**
  45885. * Creates a GPU sampler for the given texture.
  45886. *
  45887. * @param {Texture} texture - The texture to create the sampler for.
  45888. */
  45889. createSampler( texture ) {
  45890. const backend = this.backend;
  45891. const device = backend.device;
  45892. const textureGPU = backend.get( texture );
  45893. const samplerDescriptorGPU = {
  45894. addressModeU: this._convertAddressMode( texture.wrapS ),
  45895. addressModeV: this._convertAddressMode( texture.wrapT ),
  45896. addressModeW: this._convertAddressMode( texture.wrapR ),
  45897. magFilter: this._convertFilterMode( texture.magFilter ),
  45898. minFilter: this._convertFilterMode( texture.minFilter ),
  45899. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  45900. maxAnisotropy: 1
  45901. };
  45902. // anisotropy can only be used when all filter modes are set to linear.
  45903. if ( samplerDescriptorGPU.magFilter === GPUFilterMode.Linear && samplerDescriptorGPU.minFilter === GPUFilterMode.Linear && samplerDescriptorGPU.mipmapFilter === GPUFilterMode.Linear ) {
  45904. samplerDescriptorGPU.maxAnisotropy = texture.anisotropy;
  45905. }
  45906. if ( texture.isDepthTexture && texture.compareFunction !== null ) {
  45907. samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ];
  45908. }
  45909. textureGPU.sampler = device.createSampler( samplerDescriptorGPU );
  45910. }
  45911. /**
  45912. * Creates a default texture for the given texture that can be used
  45913. * as a placeholder until the actual texture is ready for usage.
  45914. *
  45915. * @param {Texture} texture - The texture to create a default texture for.
  45916. */
  45917. createDefaultTexture( texture ) {
  45918. let textureGPU;
  45919. const format = getFormat( texture );
  45920. if ( texture.isCubeTexture ) {
  45921. textureGPU = this._getDefaultCubeTextureGPU( format );
  45922. } else if ( texture.isVideoTexture ) {
  45923. this.backend.get( texture ).externalTexture = this._getDefaultVideoFrame();
  45924. } else {
  45925. textureGPU = this._getDefaultTextureGPU( format );
  45926. }
  45927. this.backend.get( texture ).texture = textureGPU;
  45928. }
  45929. /**
  45930. * Defines a texture on the GPU for the given texture object.
  45931. *
  45932. * @param {Texture} texture - The texture.
  45933. * @param {Object} [options={}] - Optional configuration parameter.
  45934. */
  45935. createTexture( texture, options = {} ) {
  45936. const backend = this.backend;
  45937. const textureData = backend.get( texture );
  45938. if ( textureData.initialized ) {
  45939. throw new Error( 'WebGPUTextureUtils: Texture already initialized.' );
  45940. }
  45941. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  45942. if ( options.levels === undefined ) options.levels = 1;
  45943. if ( options.depth === undefined ) options.depth = 1;
  45944. const { width, height, depth, levels } = options;
  45945. if ( texture.isFramebufferTexture ) {
  45946. if ( options.renderTarget ) {
  45947. options.format = this.backend.utils.getCurrentColorFormat( options.renderTarget );
  45948. } else {
  45949. options.format = this.backend.utils.getPreferredCanvasFormat();
  45950. }
  45951. }
  45952. const dimension = this._getDimension( texture );
  45953. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  45954. textureData.format = format;
  45955. const { samples, primarySamples, isMSAA } = backend.utils.getTextureSampleData( texture );
  45956. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  45957. if ( texture.isStorageTexture === true ) {
  45958. usage |= GPUTextureUsage.STORAGE_BINDING;
  45959. }
  45960. if ( texture.isCompressedTexture !== true && texture.isCompressedArrayTexture !== true ) {
  45961. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  45962. }
  45963. const textureDescriptorGPU = {
  45964. label: texture.name,
  45965. size: {
  45966. width: width,
  45967. height: height,
  45968. depthOrArrayLayers: depth,
  45969. },
  45970. mipLevelCount: levels,
  45971. sampleCount: primarySamples,
  45972. dimension: dimension,
  45973. format: format,
  45974. usage: usage
  45975. };
  45976. // texture creation
  45977. if ( texture.isVideoTexture ) {
  45978. const video = texture.source.data;
  45979. const videoFrame = new VideoFrame( video );
  45980. textureDescriptorGPU.size.width = videoFrame.displayWidth;
  45981. textureDescriptorGPU.size.height = videoFrame.displayHeight;
  45982. videoFrame.close();
  45983. textureData.externalTexture = video;
  45984. } else {
  45985. if ( format === undefined ) {
  45986. console.warn( 'WebGPURenderer: Texture format not supported.' );
  45987. this.createDefaultTexture( texture );
  45988. return;
  45989. }
  45990. if ( texture.isCubeTexture ) {
  45991. textureDescriptorGPU.textureBindingViewDimension = GPUTextureViewDimension.Cube;
  45992. }
  45993. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  45994. }
  45995. if ( isMSAA ) {
  45996. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  45997. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  45998. msaaTextureDescriptorGPU.sampleCount = samples;
  45999. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  46000. }
  46001. textureData.initialized = true;
  46002. textureData.textureDescriptorGPU = textureDescriptorGPU;
  46003. }
  46004. /**
  46005. * Destroys the GPU data for the given texture object.
  46006. *
  46007. * @param {Texture} texture - The texture.
  46008. */
  46009. destroyTexture( texture ) {
  46010. const backend = this.backend;
  46011. const textureData = backend.get( texture );
  46012. if ( textureData.texture !== undefined ) textureData.texture.destroy();
  46013. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  46014. backend.delete( texture );
  46015. }
  46016. /**
  46017. * Destroys the GPU sampler for the given texture.
  46018. *
  46019. * @param {Texture} texture - The texture to destroy the sampler for.
  46020. */
  46021. destroySampler( texture ) {
  46022. const backend = this.backend;
  46023. const textureData = backend.get( texture );
  46024. delete textureData.sampler;
  46025. }
  46026. /**
  46027. * Generates mipmaps for the given texture.
  46028. *
  46029. * @param {Texture} texture - The texture.
  46030. */
  46031. generateMipmaps( texture ) {
  46032. const textureData = this.backend.get( texture );
  46033. if ( texture.isCubeTexture ) {
  46034. for ( let i = 0; i < 6; i ++ ) {
  46035. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  46036. }
  46037. } else {
  46038. const depth = texture.image.depth || 1;
  46039. for ( let i = 0; i < depth; i ++ ) {
  46040. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  46041. }
  46042. }
  46043. }
  46044. /**
  46045. * Returns the color buffer representing the color
  46046. * attachment of the default framebuffer.
  46047. *
  46048. * @return {GPUTexture} The color buffer.
  46049. */
  46050. getColorBuffer() {
  46051. if ( this.colorBuffer ) this.colorBuffer.destroy();
  46052. const backend = this.backend;
  46053. const { width, height } = backend.getDrawingBufferSize();
  46054. this.colorBuffer = backend.device.createTexture( {
  46055. label: 'colorBuffer',
  46056. size: {
  46057. width: width,
  46058. height: height,
  46059. depthOrArrayLayers: 1
  46060. },
  46061. sampleCount: backend.utils.getSampleCount( backend.renderer.samples ),
  46062. format: backend.utils.getPreferredCanvasFormat(),
  46063. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  46064. } );
  46065. return this.colorBuffer;
  46066. }
  46067. /**
  46068. * Returns the depth buffer representing the depth
  46069. * attachment of the default framebuffer.
  46070. *
  46071. * @param {boolean} [depth=true] - Whether depth is enabled or not.
  46072. * @param {boolean} [stencil=false] - Whether stencil is enabled or not.
  46073. * @return {GPUTexture} The depth buffer.
  46074. */
  46075. getDepthBuffer( depth = true, stencil = false ) {
  46076. const backend = this.backend;
  46077. const { width, height } = backend.getDrawingBufferSize();
  46078. const depthTexture = this.depthTexture;
  46079. const depthTextureGPU = backend.get( depthTexture ).texture;
  46080. let format, type;
  46081. if ( stencil ) {
  46082. format = DepthStencilFormat;
  46083. type = UnsignedInt248Type;
  46084. } else if ( depth ) {
  46085. format = DepthFormat;
  46086. type = UnsignedIntType;
  46087. }
  46088. if ( depthTextureGPU !== undefined ) {
  46089. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type ) {
  46090. return depthTextureGPU;
  46091. }
  46092. this.destroyTexture( depthTexture );
  46093. }
  46094. depthTexture.name = 'depthBuffer';
  46095. depthTexture.format = format;
  46096. depthTexture.type = type;
  46097. depthTexture.image.width = width;
  46098. depthTexture.image.height = height;
  46099. this.createTexture( depthTexture, { width, height } );
  46100. return backend.get( depthTexture ).texture;
  46101. }
  46102. /**
  46103. * Uploads the updated texture data to the GPU.
  46104. *
  46105. * @param {Texture} texture - The texture.
  46106. * @param {Object} [options={}] - Optional configuration parameter.
  46107. */
  46108. updateTexture( texture, options ) {
  46109. const textureData = this.backend.get( texture );
  46110. const { textureDescriptorGPU } = textureData;
  46111. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  46112. return;
  46113. // transfer texture data
  46114. if ( texture.isDataTexture ) {
  46115. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  46116. } else if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isData3DTexture ) {
  46117. for ( let i = 0; i < options.image.depth; i ++ ) {
  46118. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  46119. }
  46120. } else if ( texture.isCompressedTexture || texture.isCompressedArrayTexture ) {
  46121. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  46122. } else if ( texture.isCubeTexture ) {
  46123. this._copyCubeMapToTexture( options.images, textureData.texture, textureDescriptorGPU, texture.flipY, texture.premultiplyAlpha );
  46124. } else if ( texture.isVideoTexture ) {
  46125. const video = texture.source.data;
  46126. textureData.externalTexture = video;
  46127. } else {
  46128. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY, texture.premultiplyAlpha );
  46129. }
  46130. //
  46131. textureData.version = texture.version;
  46132. if ( texture.onUpdate ) texture.onUpdate( texture );
  46133. }
  46134. /**
  46135. * Returns texture data as a typed array.
  46136. *
  46137. * @async
  46138. * @param {Texture} texture - The texture to copy.
  46139. * @param {number} x - The x coordinate of the copy origin.
  46140. * @param {number} y - The y coordinate of the copy origin.
  46141. * @param {number} width - The width of the copy.
  46142. * @param {number} height - The height of the copy.
  46143. * @param {number} faceIndex - The face index.
  46144. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  46145. */
  46146. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  46147. const device = this.backend.device;
  46148. const textureData = this.backend.get( texture );
  46149. const textureGPU = textureData.texture;
  46150. const format = textureData.textureDescriptorGPU.format;
  46151. const bytesPerTexel = this._getBytesPerTexel( format );
  46152. let bytesPerRow = width * bytesPerTexel;
  46153. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  46154. const readBuffer = device.createBuffer(
  46155. {
  46156. size: width * height * bytesPerTexel,
  46157. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  46158. }
  46159. );
  46160. const encoder = device.createCommandEncoder();
  46161. encoder.copyTextureToBuffer(
  46162. {
  46163. texture: textureGPU,
  46164. origin: { x, y, z: faceIndex },
  46165. },
  46166. {
  46167. buffer: readBuffer,
  46168. bytesPerRow: bytesPerRow
  46169. },
  46170. {
  46171. width: width,
  46172. height: height
  46173. }
  46174. );
  46175. const typedArrayType = this._getTypedArrayType( format );
  46176. device.queue.submit( [ encoder.finish() ] );
  46177. await readBuffer.mapAsync( GPUMapMode.READ );
  46178. const buffer = readBuffer.getMappedRange();
  46179. return new typedArrayType( buffer );
  46180. }
  46181. /**
  46182. * Returns the default GPU texture for the given format.
  46183. *
  46184. * @private
  46185. * @param {string} format - The GPU format.
  46186. * @return {GPUTexture} The GPU texture.
  46187. */
  46188. _getDefaultTextureGPU( format ) {
  46189. let defaultTexture = this.defaultTexture[ format ];
  46190. if ( defaultTexture === undefined ) {
  46191. const texture = new Texture();
  46192. texture.minFilter = NearestFilter;
  46193. texture.magFilter = NearestFilter;
  46194. this.createTexture( texture, { width: 1, height: 1, format } );
  46195. this.defaultTexture[ format ] = defaultTexture = texture;
  46196. }
  46197. return this.backend.get( defaultTexture ).texture;
  46198. }
  46199. /**
  46200. * Returns the default GPU cube texture for the given format.
  46201. *
  46202. * @private
  46203. * @param {string} format - The GPU format.
  46204. * @return {GPUTexture} The GPU texture.
  46205. */
  46206. _getDefaultCubeTextureGPU( format ) {
  46207. let defaultCubeTexture = this.defaultTexture[ format ];
  46208. if ( defaultCubeTexture === undefined ) {
  46209. const texture = new CubeTexture();
  46210. texture.minFilter = NearestFilter;
  46211. texture.magFilter = NearestFilter;
  46212. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  46213. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  46214. }
  46215. return this.backend.get( defaultCubeTexture ).texture;
  46216. }
  46217. /**
  46218. * Returns the default video frame used as default data in context of video textures.
  46219. *
  46220. * @private
  46221. * @return {VideoFrame} The video frame.
  46222. */
  46223. _getDefaultVideoFrame() {
  46224. let defaultVideoFrame = this.defaultVideoFrame;
  46225. if ( defaultVideoFrame === null ) {
  46226. const init = {
  46227. timestamp: 0,
  46228. codedWidth: 1,
  46229. codedHeight: 1,
  46230. format: 'RGBA',
  46231. };
  46232. this.defaultVideoFrame = defaultVideoFrame = new VideoFrame( new Uint8Array( [ 0, 0, 0, 0xff ] ), init );
  46233. }
  46234. return defaultVideoFrame;
  46235. }
  46236. /**
  46237. * Uploads cube texture image data to the GPU memory.
  46238. *
  46239. * @private
  46240. * @param {Array} images - The cube image data.
  46241. * @param {GPUTexture} textureGPU - The GPU texture.
  46242. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  46243. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  46244. * @param {boolean} premultiplyAlpha - Whether the texture should have its RGB channels premultiplied by the alpha channel or not.
  46245. */
  46246. _copyCubeMapToTexture( images, textureGPU, textureDescriptorGPU, flipY, premultiplyAlpha ) {
  46247. for ( let i = 0; i < 6; i ++ ) {
  46248. const image = images[ i ];
  46249. const flipIndex = flipY === true ? _flipMap[ i ] : i;
  46250. if ( image.isDataTexture ) {
  46251. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  46252. } else {
  46253. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, flipY, premultiplyAlpha );
  46254. }
  46255. }
  46256. }
  46257. /**
  46258. * Uploads texture image data to the GPU memory.
  46259. *
  46260. * @private
  46261. * @param {HTMLImageElement|ImageBitmap|HTMLCanvasElement} image - The image data.
  46262. * @param {GPUTexture} textureGPU - The GPU texture.
  46263. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  46264. * @param {number} originDepth - The origin depth.
  46265. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  46266. * @param {boolean} premultiplyAlpha - Whether the texture should have its RGB channels premultiplied by the alpha channel or not.
  46267. */
  46268. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, premultiplyAlpha ) {
  46269. const device = this.backend.device;
  46270. device.queue.copyExternalImageToTexture(
  46271. {
  46272. source: image,
  46273. flipY: flipY
  46274. }, {
  46275. texture: textureGPU,
  46276. mipLevel: 0,
  46277. origin: { x: 0, y: 0, z: originDepth },
  46278. premultipliedAlpha: premultiplyAlpha
  46279. }, {
  46280. width: image.width,
  46281. height: image.height,
  46282. depthOrArrayLayers: 1
  46283. }
  46284. );
  46285. }
  46286. /**
  46287. * Returns the pass utils singleton.
  46288. *
  46289. * @private
  46290. * @return {WebGPUTexturePassUtils} The utils instance.
  46291. */
  46292. _getPassUtils() {
  46293. let passUtils = this._passUtils;
  46294. if ( passUtils === null ) {
  46295. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  46296. }
  46297. return passUtils;
  46298. }
  46299. /**
  46300. * Generates mipmaps for the given GPU texture.
  46301. *
  46302. * @private
  46303. * @param {GPUTexture} textureGPU - The GPU texture object.
  46304. * @param {Object} textureDescriptorGPU - The texture descriptor.
  46305. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  46306. */
  46307. _generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer = 0 ) {
  46308. this._getPassUtils().generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer );
  46309. }
  46310. /**
  46311. * Flip the contents of the given GPU texture along its vertical axis.
  46312. *
  46313. * @private
  46314. * @param {GPUTexture} textureGPU - The GPU texture object.
  46315. * @param {Object} textureDescriptorGPU - The texture descriptor.
  46316. * @param {number} [originDepth=0] - The origin depth.
  46317. */
  46318. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  46319. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  46320. }
  46321. /**
  46322. * Uploads texture buffer data to the GPU memory.
  46323. *
  46324. * @private
  46325. * @param {Object} image - An object defining the image buffer data.
  46326. * @param {GPUTexture} textureGPU - The GPU texture.
  46327. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  46328. * @param {number} originDepth - The origin depth.
  46329. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  46330. * @param {number} [depth=0] - TODO.
  46331. */
  46332. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0 ) {
  46333. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  46334. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  46335. const device = this.backend.device;
  46336. const data = image.data;
  46337. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  46338. const bytesPerRow = image.width * bytesPerTexel;
  46339. device.queue.writeTexture(
  46340. {
  46341. texture: textureGPU,
  46342. mipLevel: 0,
  46343. origin: { x: 0, y: 0, z: originDepth }
  46344. },
  46345. data,
  46346. {
  46347. offset: image.width * image.height * bytesPerTexel * depth,
  46348. bytesPerRow
  46349. },
  46350. {
  46351. width: image.width,
  46352. height: image.height,
  46353. depthOrArrayLayers: 1
  46354. } );
  46355. if ( flipY === true ) {
  46356. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  46357. }
  46358. }
  46359. /**
  46360. * Uploads compressed texture data to the GPU memory.
  46361. *
  46362. * @private
  46363. * @param {Array<Object>} mipmaps - An array with mipmap data.
  46364. * @param {GPUTexture} textureGPU - The GPU texture.
  46365. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  46366. */
  46367. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU ) {
  46368. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  46369. const device = this.backend.device;
  46370. const blockData = this._getBlockData( textureDescriptorGPU.format );
  46371. const isArrayTexture = textureDescriptorGPU.size.depthOrArrayLayers > 1;
  46372. for ( let i = 0; i < mipmaps.length; i ++ ) {
  46373. const mipmap = mipmaps[ i ];
  46374. const width = mipmap.width;
  46375. const height = mipmap.height;
  46376. const depth = isArrayTexture ? textureDescriptorGPU.size.depthOrArrayLayers : 1;
  46377. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  46378. const bytesPerImage = bytesPerRow * Math.ceil( height / blockData.height );
  46379. for ( let j = 0; j < depth; j ++ ) {
  46380. device.queue.writeTexture(
  46381. {
  46382. texture: textureGPU,
  46383. mipLevel: i,
  46384. origin: { x: 0, y: 0, z: j }
  46385. },
  46386. mipmap.data,
  46387. {
  46388. offset: j * bytesPerImage,
  46389. bytesPerRow,
  46390. rowsPerImage: Math.ceil( height / blockData.height )
  46391. },
  46392. {
  46393. width: Math.ceil( width / blockData.width ) * blockData.width,
  46394. height: Math.ceil( height / blockData.height ) * blockData.height,
  46395. depthOrArrayLayers: 1
  46396. }
  46397. );
  46398. }
  46399. }
  46400. }
  46401. /**
  46402. * This method is only relevant for compressed texture formats. It returns a block
  46403. * data descriptor for the given GPU compressed texture format.
  46404. *
  46405. * @private
  46406. * @param {string} format - The GPU compressed texture format.
  46407. * @return {Object} The block data descriptor.
  46408. */
  46409. _getBlockData( format ) {
  46410. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  46411. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  46412. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  46413. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSnorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  46414. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  46415. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  46416. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  46417. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  46418. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  46419. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  46420. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  46421. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  46422. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  46423. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  46424. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  46425. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  46426. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  46427. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  46428. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  46429. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  46430. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  46431. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  46432. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  46433. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  46434. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  46435. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  46436. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  46437. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  46438. }
  46439. /**
  46440. * Converts the three.js uv wrapping constants to GPU address mode constants.
  46441. *
  46442. * @private
  46443. * @param {number} value - The three.js constant defining a uv wrapping mode.
  46444. * @return {string} The GPU address mode.
  46445. */
  46446. _convertAddressMode( value ) {
  46447. let addressMode = GPUAddressMode.ClampToEdge;
  46448. if ( value === RepeatWrapping ) {
  46449. addressMode = GPUAddressMode.Repeat;
  46450. } else if ( value === MirroredRepeatWrapping ) {
  46451. addressMode = GPUAddressMode.MirrorRepeat;
  46452. }
  46453. return addressMode;
  46454. }
  46455. /**
  46456. * Converts the three.js filter constants to GPU filter constants.
  46457. *
  46458. * @private
  46459. * @param {number} value - The three.js constant defining a filter mode.
  46460. * @return {string} The GPU filter mode.
  46461. */
  46462. _convertFilterMode( value ) {
  46463. let filterMode = GPUFilterMode.Linear;
  46464. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  46465. filterMode = GPUFilterMode.Nearest;
  46466. }
  46467. return filterMode;
  46468. }
  46469. /**
  46470. * Returns the bytes-per-texel value for the given GPU texture format.
  46471. *
  46472. * @private
  46473. * @param {string} format - The GPU texture format.
  46474. * @return {number} The bytes-per-texel.
  46475. */
  46476. _getBytesPerTexel( format ) {
  46477. // 8-bit formats
  46478. if ( format === GPUTextureFormat.R8Unorm ||
  46479. format === GPUTextureFormat.R8Snorm ||
  46480. format === GPUTextureFormat.R8Uint ||
  46481. format === GPUTextureFormat.R8Sint ) return 1;
  46482. // 16-bit formats
  46483. if ( format === GPUTextureFormat.R16Uint ||
  46484. format === GPUTextureFormat.R16Sint ||
  46485. format === GPUTextureFormat.R16Float ||
  46486. format === GPUTextureFormat.RG8Unorm ||
  46487. format === GPUTextureFormat.RG8Snorm ||
  46488. format === GPUTextureFormat.RG8Uint ||
  46489. format === GPUTextureFormat.RG8Sint ) return 2;
  46490. // 32-bit formats
  46491. if ( format === GPUTextureFormat.R32Uint ||
  46492. format === GPUTextureFormat.R32Sint ||
  46493. format === GPUTextureFormat.R32Float ||
  46494. format === GPUTextureFormat.RG16Uint ||
  46495. format === GPUTextureFormat.RG16Sint ||
  46496. format === GPUTextureFormat.RG16Float ||
  46497. format === GPUTextureFormat.RGBA8Unorm ||
  46498. format === GPUTextureFormat.RGBA8UnormSRGB ||
  46499. format === GPUTextureFormat.RGBA8Snorm ||
  46500. format === GPUTextureFormat.RGBA8Uint ||
  46501. format === GPUTextureFormat.RGBA8Sint ||
  46502. format === GPUTextureFormat.BGRA8Unorm ||
  46503. format === GPUTextureFormat.BGRA8UnormSRGB ||
  46504. // Packed 32-bit formats
  46505. format === GPUTextureFormat.RGB9E5UFloat ||
  46506. format === GPUTextureFormat.RGB10A2Unorm ||
  46507. format === GPUTextureFormat.RG11B10UFloat ||
  46508. format === GPUTextureFormat.Depth32Float ||
  46509. format === GPUTextureFormat.Depth24Plus ||
  46510. format === GPUTextureFormat.Depth24PlusStencil8 ||
  46511. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  46512. // 64-bit formats
  46513. if ( format === GPUTextureFormat.RG32Uint ||
  46514. format === GPUTextureFormat.RG32Sint ||
  46515. format === GPUTextureFormat.RG32Float ||
  46516. format === GPUTextureFormat.RGBA16Uint ||
  46517. format === GPUTextureFormat.RGBA16Sint ||
  46518. format === GPUTextureFormat.RGBA16Float ) return 8;
  46519. // 128-bit formats
  46520. if ( format === GPUTextureFormat.RGBA32Uint ||
  46521. format === GPUTextureFormat.RGBA32Sint ||
  46522. format === GPUTextureFormat.RGBA32Float ) return 16;
  46523. }
  46524. /**
  46525. * Returns the corresponding typed array type for the given GPU texture format.
  46526. *
  46527. * @private
  46528. * @param {string} format - The GPU texture format.
  46529. * @return {TypedArray.constructor} The typed array type.
  46530. */
  46531. _getTypedArrayType( format ) {
  46532. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  46533. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  46534. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  46535. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  46536. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  46537. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  46538. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  46539. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  46540. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  46541. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  46542. if ( format === GPUTextureFormat.RGBA8Unorm ) return Uint8Array;
  46543. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  46544. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  46545. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  46546. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  46547. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  46548. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  46549. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  46550. if ( format === GPUTextureFormat.R16Float ) return Uint16Array;
  46551. if ( format === GPUTextureFormat.RG16Float ) return Uint16Array;
  46552. if ( format === GPUTextureFormat.RGBA16Float ) return Uint16Array;
  46553. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  46554. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  46555. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  46556. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  46557. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  46558. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  46559. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  46560. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  46561. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  46562. if ( format === GPUTextureFormat.BGRA8Unorm ) return Uint8Array;
  46563. if ( format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  46564. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  46565. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  46566. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  46567. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  46568. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  46569. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  46570. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  46571. }
  46572. /**
  46573. * Returns the GPU dimensions for the given texture.
  46574. *
  46575. * @private
  46576. * @param {Texture} texture - The texture.
  46577. * @return {string} The GPU dimension.
  46578. */
  46579. _getDimension( texture ) {
  46580. let dimension;
  46581. if ( texture.isData3DTexture ) {
  46582. dimension = GPUTextureDimension.ThreeD;
  46583. } else {
  46584. dimension = GPUTextureDimension.TwoD;
  46585. }
  46586. return dimension;
  46587. }
  46588. }
  46589. /**
  46590. * Returns the GPU format for the given texture.
  46591. *
  46592. * @param {Texture} texture - The texture.
  46593. * @param {?GPUDevice} [device=null] - The GPU device which is used for feature detection.
  46594. * It is not necessary to apply the device for most formats.
  46595. * @return {string} The GPU format.
  46596. */
  46597. function getFormat( texture, device = null ) {
  46598. const format = texture.format;
  46599. const type = texture.type;
  46600. const colorSpace = texture.colorSpace;
  46601. const transfer = ColorManagement.getTransfer( colorSpace );
  46602. let formatGPU;
  46603. if ( texture.isCompressedTexture === true || texture.isCompressedArrayTexture === true ) {
  46604. switch ( format ) {
  46605. case RGBA_S3TC_DXT1_Format:
  46606. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  46607. break;
  46608. case RGBA_S3TC_DXT3_Format:
  46609. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  46610. break;
  46611. case RGBA_S3TC_DXT5_Format:
  46612. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  46613. break;
  46614. case RGB_ETC2_Format:
  46615. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  46616. break;
  46617. case RGBA_ETC2_EAC_Format:
  46618. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  46619. break;
  46620. case RGBA_ASTC_4x4_Format:
  46621. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  46622. break;
  46623. case RGBA_ASTC_5x4_Format:
  46624. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  46625. break;
  46626. case RGBA_ASTC_5x5_Format:
  46627. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  46628. break;
  46629. case RGBA_ASTC_6x5_Format:
  46630. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  46631. break;
  46632. case RGBA_ASTC_6x6_Format:
  46633. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  46634. break;
  46635. case RGBA_ASTC_8x5_Format:
  46636. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  46637. break;
  46638. case RGBA_ASTC_8x6_Format:
  46639. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  46640. break;
  46641. case RGBA_ASTC_8x8_Format:
  46642. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  46643. break;
  46644. case RGBA_ASTC_10x5_Format:
  46645. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  46646. break;
  46647. case RGBA_ASTC_10x6_Format:
  46648. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  46649. break;
  46650. case RGBA_ASTC_10x8_Format:
  46651. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  46652. break;
  46653. case RGBA_ASTC_10x10_Format:
  46654. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  46655. break;
  46656. case RGBA_ASTC_12x10_Format:
  46657. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  46658. break;
  46659. case RGBA_ASTC_12x12_Format:
  46660. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  46661. break;
  46662. case RGBAFormat:
  46663. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  46664. break;
  46665. default:
  46666. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  46667. }
  46668. } else {
  46669. switch ( format ) {
  46670. case RGBAFormat:
  46671. switch ( type ) {
  46672. case ByteType:
  46673. formatGPU = GPUTextureFormat.RGBA8Snorm;
  46674. break;
  46675. case ShortType:
  46676. formatGPU = GPUTextureFormat.RGBA16Sint;
  46677. break;
  46678. case UnsignedShortType:
  46679. formatGPU = GPUTextureFormat.RGBA16Uint;
  46680. break;
  46681. case UnsignedIntType:
  46682. formatGPU = GPUTextureFormat.RGBA32Uint;
  46683. break;
  46684. case IntType:
  46685. formatGPU = GPUTextureFormat.RGBA32Sint;
  46686. break;
  46687. case UnsignedByteType:
  46688. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  46689. break;
  46690. case HalfFloatType:
  46691. formatGPU = GPUTextureFormat.RGBA16Float;
  46692. break;
  46693. case FloatType:
  46694. formatGPU = GPUTextureFormat.RGBA32Float;
  46695. break;
  46696. default:
  46697. console.error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  46698. }
  46699. break;
  46700. case RGBFormat:
  46701. switch ( type ) {
  46702. case UnsignedInt5999Type:
  46703. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  46704. break;
  46705. default:
  46706. console.error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  46707. }
  46708. break;
  46709. case RedFormat:
  46710. switch ( type ) {
  46711. case ByteType:
  46712. formatGPU = GPUTextureFormat.R8Snorm;
  46713. break;
  46714. case ShortType:
  46715. formatGPU = GPUTextureFormat.R16Sint;
  46716. break;
  46717. case UnsignedShortType:
  46718. formatGPU = GPUTextureFormat.R16Uint;
  46719. break;
  46720. case UnsignedIntType:
  46721. formatGPU = GPUTextureFormat.R32Uint;
  46722. break;
  46723. case IntType:
  46724. formatGPU = GPUTextureFormat.R32Sint;
  46725. break;
  46726. case UnsignedByteType:
  46727. formatGPU = GPUTextureFormat.R8Unorm;
  46728. break;
  46729. case HalfFloatType:
  46730. formatGPU = GPUTextureFormat.R16Float;
  46731. break;
  46732. case FloatType:
  46733. formatGPU = GPUTextureFormat.R32Float;
  46734. break;
  46735. default:
  46736. console.error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  46737. }
  46738. break;
  46739. case RGFormat:
  46740. switch ( type ) {
  46741. case ByteType:
  46742. formatGPU = GPUTextureFormat.RG8Snorm;
  46743. break;
  46744. case ShortType:
  46745. formatGPU = GPUTextureFormat.RG16Sint;
  46746. break;
  46747. case UnsignedShortType:
  46748. formatGPU = GPUTextureFormat.RG16Uint;
  46749. break;
  46750. case UnsignedIntType:
  46751. formatGPU = GPUTextureFormat.RG32Uint;
  46752. break;
  46753. case IntType:
  46754. formatGPU = GPUTextureFormat.RG32Sint;
  46755. break;
  46756. case UnsignedByteType:
  46757. formatGPU = GPUTextureFormat.RG8Unorm;
  46758. break;
  46759. case HalfFloatType:
  46760. formatGPU = GPUTextureFormat.RG16Float;
  46761. break;
  46762. case FloatType:
  46763. formatGPU = GPUTextureFormat.RG32Float;
  46764. break;
  46765. default:
  46766. console.error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  46767. }
  46768. break;
  46769. case DepthFormat:
  46770. switch ( type ) {
  46771. case UnsignedShortType:
  46772. formatGPU = GPUTextureFormat.Depth16Unorm;
  46773. break;
  46774. case UnsignedIntType:
  46775. formatGPU = GPUTextureFormat.Depth24Plus;
  46776. break;
  46777. case FloatType:
  46778. formatGPU = GPUTextureFormat.Depth32Float;
  46779. break;
  46780. default:
  46781. console.error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  46782. }
  46783. break;
  46784. case DepthStencilFormat:
  46785. switch ( type ) {
  46786. case UnsignedInt248Type:
  46787. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  46788. break;
  46789. case FloatType:
  46790. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  46791. console.error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  46792. }
  46793. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  46794. break;
  46795. default:
  46796. console.error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  46797. }
  46798. break;
  46799. case RedIntegerFormat:
  46800. switch ( type ) {
  46801. case IntType:
  46802. formatGPU = GPUTextureFormat.R32Sint;
  46803. break;
  46804. case UnsignedIntType:
  46805. formatGPU = GPUTextureFormat.R32Uint;
  46806. break;
  46807. default:
  46808. console.error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  46809. }
  46810. break;
  46811. case RGIntegerFormat:
  46812. switch ( type ) {
  46813. case IntType:
  46814. formatGPU = GPUTextureFormat.RG32Sint;
  46815. break;
  46816. case UnsignedIntType:
  46817. formatGPU = GPUTextureFormat.RG32Uint;
  46818. break;
  46819. default:
  46820. console.error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  46821. }
  46822. break;
  46823. case RGBAIntegerFormat:
  46824. switch ( type ) {
  46825. case IntType:
  46826. formatGPU = GPUTextureFormat.RGBA32Sint;
  46827. break;
  46828. case UnsignedIntType:
  46829. formatGPU = GPUTextureFormat.RGBA32Uint;
  46830. break;
  46831. default:
  46832. console.error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  46833. }
  46834. break;
  46835. default:
  46836. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  46837. }
  46838. }
  46839. return formatGPU;
  46840. }
  46841. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  46842. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  46843. const wgslTypeLib$1 = {
  46844. 'f32': 'float',
  46845. 'i32': 'int',
  46846. 'u32': 'uint',
  46847. 'bool': 'bool',
  46848. 'vec2<f32>': 'vec2',
  46849. 'vec2<i32>': 'ivec2',
  46850. 'vec2<u32>': 'uvec2',
  46851. 'vec2<bool>': 'bvec2',
  46852. 'vec2f': 'vec2',
  46853. 'vec2i': 'ivec2',
  46854. 'vec2u': 'uvec2',
  46855. 'vec2b': 'bvec2',
  46856. 'vec3<f32>': 'vec3',
  46857. 'vec3<i32>': 'ivec3',
  46858. 'vec3<u32>': 'uvec3',
  46859. 'vec3<bool>': 'bvec3',
  46860. 'vec3f': 'vec3',
  46861. 'vec3i': 'ivec3',
  46862. 'vec3u': 'uvec3',
  46863. 'vec3b': 'bvec3',
  46864. 'vec4<f32>': 'vec4',
  46865. 'vec4<i32>': 'ivec4',
  46866. 'vec4<u32>': 'uvec4',
  46867. 'vec4<bool>': 'bvec4',
  46868. 'vec4f': 'vec4',
  46869. 'vec4i': 'ivec4',
  46870. 'vec4u': 'uvec4',
  46871. 'vec4b': 'bvec4',
  46872. 'mat2x2<f32>': 'mat2',
  46873. 'mat2x2f': 'mat2',
  46874. 'mat3x3<f32>': 'mat3',
  46875. 'mat3x3f': 'mat3',
  46876. 'mat4x4<f32>': 'mat4',
  46877. 'mat4x4f': 'mat4',
  46878. 'sampler': 'sampler',
  46879. 'texture_1d': 'texture',
  46880. 'texture_2d': 'texture',
  46881. 'texture_2d_array': 'texture',
  46882. 'texture_multisampled_2d': 'cubeTexture',
  46883. 'texture_depth_2d': 'depthTexture',
  46884. 'texture_depth_2d_array': 'depthTexture',
  46885. 'texture_depth_multisampled_2d': 'depthTexture',
  46886. 'texture_depth_cube': 'depthTexture',
  46887. 'texture_depth_cube_array': 'depthTexture',
  46888. 'texture_3d': 'texture3D',
  46889. 'texture_cube': 'cubeTexture',
  46890. 'texture_cube_array': 'cubeTexture',
  46891. 'texture_storage_1d': 'storageTexture',
  46892. 'texture_storage_2d': 'storageTexture',
  46893. 'texture_storage_2d_array': 'storageTexture',
  46894. 'texture_storage_3d': 'storageTexture'
  46895. };
  46896. const parse = ( source ) => {
  46897. source = source.trim();
  46898. const declaration = source.match( declarationRegexp );
  46899. if ( declaration !== null && declaration.length === 4 ) {
  46900. const inputsCode = declaration[ 2 ];
  46901. const propsMatches = [];
  46902. let match = null;
  46903. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  46904. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  46905. }
  46906. // Process matches to correctly pair names and types
  46907. const inputs = [];
  46908. for ( let i = 0; i < propsMatches.length; i ++ ) {
  46909. const { name, type } = propsMatches[ i ];
  46910. let resolvedType = type;
  46911. if ( resolvedType.startsWith( 'ptr' ) ) {
  46912. resolvedType = 'pointer';
  46913. } else {
  46914. if ( resolvedType.startsWith( 'texture' ) ) {
  46915. resolvedType = type.split( '<' )[ 0 ];
  46916. }
  46917. resolvedType = wgslTypeLib$1[ resolvedType ];
  46918. }
  46919. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  46920. }
  46921. const blockCode = source.substring( declaration[ 0 ].length );
  46922. const outputType = declaration[ 3 ] || 'void';
  46923. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  46924. const type = wgslTypeLib$1[ outputType ] || outputType;
  46925. return {
  46926. type,
  46927. inputs,
  46928. name,
  46929. inputsCode,
  46930. blockCode,
  46931. outputType
  46932. };
  46933. } else {
  46934. throw new Error( 'FunctionNode: Function is not a WGSL code.' );
  46935. }
  46936. };
  46937. /**
  46938. * This class represents a WSL node function.
  46939. *
  46940. * @augments NodeFunction
  46941. */
  46942. class WGSLNodeFunction extends NodeFunction {
  46943. /**
  46944. * Constructs a new WGSL node function.
  46945. *
  46946. * @param {string} source - The WGSL source.
  46947. */
  46948. constructor( source ) {
  46949. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  46950. super( type, inputs, name );
  46951. this.inputsCode = inputsCode;
  46952. this.blockCode = blockCode;
  46953. this.outputType = outputType;
  46954. }
  46955. /**
  46956. * This method returns the WGSL code of the node function.
  46957. *
  46958. * @param {string} [name=this.name] - The function's name.
  46959. * @return {string} The shader code.
  46960. */
  46961. getCode( name = this.name ) {
  46962. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  46963. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  46964. }
  46965. }
  46966. /**
  46967. * A WGSL node parser.
  46968. *
  46969. * @augments NodeParser
  46970. */
  46971. class WGSLNodeParser extends NodeParser {
  46972. /**
  46973. * The method parses the given WGSL code an returns a node function.
  46974. *
  46975. * @param {string} source - The WGSL code.
  46976. * @return {WGSLNodeFunction} A node function.
  46977. */
  46978. parseFunction( source ) {
  46979. return new WGSLNodeFunction( source );
  46980. }
  46981. }
  46982. // GPUShaderStage is not defined in browsers not supporting WebGPU
  46983. const GPUShaderStage = ( typeof self !== 'undefined' ) ? self.GPUShaderStage : { VERTEX: 1, FRAGMENT: 2, COMPUTE: 4 };
  46984. const accessNames = {
  46985. [ NodeAccess.READ_ONLY ]: 'read',
  46986. [ NodeAccess.WRITE_ONLY ]: 'write',
  46987. [ NodeAccess.READ_WRITE ]: 'read_write'
  46988. };
  46989. const wrapNames = {
  46990. [ RepeatWrapping ]: 'repeat',
  46991. [ ClampToEdgeWrapping ]: 'clamp',
  46992. [ MirroredRepeatWrapping ]: 'mirror'
  46993. };
  46994. const gpuShaderStageLib = {
  46995. 'vertex': GPUShaderStage ? GPUShaderStage.VERTEX : 1,
  46996. 'fragment': GPUShaderStage ? GPUShaderStage.FRAGMENT : 2,
  46997. 'compute': GPUShaderStage ? GPUShaderStage.COMPUTE : 4
  46998. };
  46999. const supports = {
  47000. instance: true,
  47001. swizzleAssign: false,
  47002. storageBuffer: true
  47003. };
  47004. const wgslFnOpLib = {
  47005. '^^': 'tsl_xor'
  47006. };
  47007. const wgslTypeLib = {
  47008. float: 'f32',
  47009. int: 'i32',
  47010. uint: 'u32',
  47011. bool: 'bool',
  47012. color: 'vec3<f32>',
  47013. vec2: 'vec2<f32>',
  47014. ivec2: 'vec2<i32>',
  47015. uvec2: 'vec2<u32>',
  47016. bvec2: 'vec2<bool>',
  47017. vec3: 'vec3<f32>',
  47018. ivec3: 'vec3<i32>',
  47019. uvec3: 'vec3<u32>',
  47020. bvec3: 'vec3<bool>',
  47021. vec4: 'vec4<f32>',
  47022. ivec4: 'vec4<i32>',
  47023. uvec4: 'vec4<u32>',
  47024. bvec4: 'vec4<bool>',
  47025. mat2: 'mat2x2<f32>',
  47026. mat3: 'mat3x3<f32>',
  47027. mat4: 'mat4x4<f32>'
  47028. };
  47029. const wgslCodeCache = {};
  47030. const wgslPolyfill = {
  47031. tsl_xor: new CodeNode( 'fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }' ),
  47032. mod_float: new CodeNode( 'fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  47033. mod_vec2: new CodeNode( 'fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  47034. mod_vec3: new CodeNode( 'fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  47035. mod_vec4: new CodeNode( 'fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  47036. equals_bool: new CodeNode( 'fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  47037. 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 ); }' ),
  47038. 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 ); }' ),
  47039. 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 ); }' ),
  47040. repeatWrapping_float: new CodeNode( 'fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }' ),
  47041. 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 ); }' ),
  47042. clampWrapping_float: new CodeNode( 'fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }' ),
  47043. biquadraticTexture: new CodeNode( /* wgsl */`
  47044. fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {
  47045. let res = vec2f( iRes );
  47046. let uvScaled = coord * res;
  47047. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  47048. // https://www.shadertoy.com/view/WtyXRy
  47049. let uv = uvWrapping - 0.5;
  47050. let iuv = floor( uv );
  47051. let f = fract( uv );
  47052. let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );
  47053. let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );
  47054. let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );
  47055. let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );
  47056. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  47057. }
  47058. ` )
  47059. };
  47060. const wgslMethods = {
  47061. dFdx: 'dpdx',
  47062. dFdy: '- dpdy',
  47063. mod_float: 'tsl_mod_float',
  47064. mod_vec2: 'tsl_mod_vec2',
  47065. mod_vec3: 'tsl_mod_vec3',
  47066. mod_vec4: 'tsl_mod_vec4',
  47067. equals_bool: 'tsl_equals_bool',
  47068. equals_bvec2: 'tsl_equals_bvec2',
  47069. equals_bvec3: 'tsl_equals_bvec3',
  47070. equals_bvec4: 'tsl_equals_bvec4',
  47071. inversesqrt: 'inverseSqrt',
  47072. bitcast: 'bitcast<f32>'
  47073. };
  47074. // WebGPU issue: does not support pow() with negative base on Windows
  47075. if ( typeof navigator !== 'undefined' && /Windows/g.test( navigator.userAgent ) ) {
  47076. wgslPolyfill.pow_float = new CodeNode( 'fn tsl_pow_float( a : f32, b : f32 ) -> f32 { return select( -pow( -a, b ), pow( a, b ), a > 0.0 ); }' );
  47077. wgslPolyfill.pow_vec2 = new CodeNode( 'fn tsl_pow_vec2( a : vec2f, b : vec2f ) -> vec2f { return vec2f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ) ); }', [ wgslPolyfill.pow_float ] );
  47078. wgslPolyfill.pow_vec3 = new CodeNode( 'fn tsl_pow_vec3( a : vec3f, b : vec3f ) -> vec3f { return vec3f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ), tsl_pow_float( a.z, b.z ) ); }', [ wgslPolyfill.pow_float ] );
  47079. wgslPolyfill.pow_vec4 = new CodeNode( 'fn tsl_pow_vec4( a : vec4f, b : vec4f ) -> vec4f { return vec4f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ), tsl_pow_float( a.z, b.z ), tsl_pow_float( a.w, b.w ) ); }', [ wgslPolyfill.pow_float ] );
  47080. wgslMethods.pow_float = 'tsl_pow_float';
  47081. wgslMethods.pow_vec2 = 'tsl_pow_vec2';
  47082. wgslMethods.pow_vec3 = 'tsl_pow_vec3';
  47083. wgslMethods.pow_vec4 = 'tsl_pow_vec4';
  47084. }
  47085. //
  47086. let diagnostics = '';
  47087. if ( ( typeof navigator !== 'undefined' && /Firefox|Deno/g.test( navigator.userAgent ) ) !== true ) {
  47088. diagnostics += 'diagnostic( off, derivative_uniformity );\n';
  47089. }
  47090. /**
  47091. * A node builder targeting WGSL.
  47092. *
  47093. * This module generates WGSL shader code from node materials and also
  47094. * generates the respective bindings and vertex buffer definitions. These
  47095. * data are later used by the renderer to create render and compute pipelines
  47096. * for render objects.
  47097. *
  47098. * @augments NodeBuilder
  47099. */
  47100. class WGSLNodeBuilder extends NodeBuilder {
  47101. /**
  47102. * Constructs a new WGSL node builder renderer.
  47103. *
  47104. * @param {Object3D} object - The 3D object.
  47105. * @param {Renderer} renderer - The renderer.
  47106. */
  47107. constructor( object, renderer ) {
  47108. super( object, renderer, new WGSLNodeParser() );
  47109. /**
  47110. * A dictionary that holds for each shader stage ('vertex', 'fragment', 'compute')
  47111. * another dictionary which manages UBOs per group ('render','frame','object').
  47112. *
  47113. * @type {Object<string,Object<string,NodeUniformsGroup>>}
  47114. */
  47115. this.uniformGroups = {};
  47116. /**
  47117. * A dictionary that holds for each shader stage a Map of builtins.
  47118. *
  47119. * @type {Object<string,Map<string,Object>>}
  47120. */
  47121. this.builtins = {};
  47122. /**
  47123. * A dictionary that holds for each shader stage a Set of directives.
  47124. *
  47125. * @type {Object<string,Set<string>>}
  47126. */
  47127. this.directives = {};
  47128. /**
  47129. * A map for managing scope arrays. Only relevant for when using
  47130. * {@link WorkgroupInfoNode} in context of compute shaders.
  47131. *
  47132. * @type {Map<string,Object>}
  47133. */
  47134. this.scopedArrays = new Map();
  47135. }
  47136. /**
  47137. * Checks if the given texture requires a manual conversion to the working color space.
  47138. *
  47139. * @param {Texture} texture - The texture to check.
  47140. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  47141. */
  47142. needsToWorkingColorSpace( texture ) {
  47143. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  47144. }
  47145. /**
  47146. * Generates the WGSL snippet for sampled textures.
  47147. *
  47148. * @private
  47149. * @param {Texture} texture - The texture.
  47150. * @param {string} textureProperty - The name of the texture uniform in the shader.
  47151. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  47152. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  47153. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  47154. * @return {string} The WGSL snippet.
  47155. */
  47156. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  47157. if ( shaderStage === 'fragment' ) {
  47158. if ( depthSnippet ) {
  47159. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  47160. } else {
  47161. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  47162. }
  47163. } else {
  47164. return this._generateTextureSampleLevel( texture, textureProperty, uvSnippet, '0', depthSnippet );
  47165. }
  47166. }
  47167. /**
  47168. * Generates the WGSL snippet when sampling video textures.
  47169. *
  47170. * @private
  47171. * @param {string} textureProperty - The name of the video texture uniform in the shader.
  47172. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  47173. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  47174. * @return {string} The WGSL snippet.
  47175. */
  47176. _generateVideoSample( textureProperty, uvSnippet, shaderStage = this.shaderStage ) {
  47177. if ( shaderStage === 'fragment' ) {
  47178. return `textureSampleBaseClampToEdge( ${ textureProperty }, ${ textureProperty }_sampler, vec2<f32>( ${ uvSnippet }.x, 1.0 - ${ uvSnippet }.y ) )`;
  47179. } else {
  47180. console.error( `WebGPURenderer: THREE.VideoTexture does not support ${ shaderStage } shader.` );
  47181. }
  47182. }
  47183. /**
  47184. * Generates the WGSL snippet when sampling textures with explicit mip level.
  47185. *
  47186. * @private
  47187. * @param {Texture} texture - The texture.
  47188. * @param {string} textureProperty - The name of the texture uniform in the shader.
  47189. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  47190. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  47191. * @param {string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  47192. * @return {string} The WGSL snippet.
  47193. */
  47194. _generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet ) {
  47195. if ( this.isUnfilterable( texture ) === false ) {
  47196. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  47197. } else if ( this.isFilteredTexture( texture ) ) {
  47198. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet );
  47199. } else {
  47200. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet );
  47201. }
  47202. }
  47203. /**
  47204. * Generates a wrap function used in context of textures.
  47205. *
  47206. * @param {Texture} texture - The texture to generate the function for.
  47207. * @return {string} The name of the generated function.
  47208. */
  47209. generateWrapFunction( texture ) {
  47210. const functionName = `tsl_coord_${ wrapNames[ texture.wrapS ] }S_${ wrapNames[ texture.wrapT ] }_${ texture.isData3DTexture ? '3d' : '2d' }T`;
  47211. let nodeCode = wgslCodeCache[ functionName ];
  47212. if ( nodeCode === undefined ) {
  47213. const includes = [];
  47214. // For 3D textures, use vec3f; for texture arrays, keep vec2f since array index is separate
  47215. const coordType = texture.isData3DTexture ? 'vec3f' : 'vec2f';
  47216. let code = `fn ${ functionName }( coord : ${ coordType } ) -> ${ coordType } {\n\n\treturn ${ coordType }(\n`;
  47217. const addWrapSnippet = ( wrap, axis ) => {
  47218. if ( wrap === RepeatWrapping ) {
  47219. includes.push( wgslPolyfill.repeatWrapping_float );
  47220. code += `\t\ttsl_repeatWrapping_float( coord.${ axis } )`;
  47221. } else if ( wrap === ClampToEdgeWrapping ) {
  47222. includes.push( wgslPolyfill.clampWrapping_float );
  47223. code += `\t\ttsl_clampWrapping_float( coord.${ axis } )`;
  47224. } else if ( wrap === MirroredRepeatWrapping ) {
  47225. includes.push( wgslPolyfill.mirrorWrapping_float );
  47226. code += `\t\ttsl_mirrorWrapping_float( coord.${ axis } )`;
  47227. } else {
  47228. code += `\t\tcoord.${ axis }`;
  47229. console.warn( `WebGPURenderer: Unsupported texture wrap type "${ wrap }" for vertex shader.` );
  47230. }
  47231. };
  47232. addWrapSnippet( texture.wrapS, 'x' );
  47233. code += ',\n';
  47234. addWrapSnippet( texture.wrapT, 'y' );
  47235. if ( texture.isData3DTexture ) {
  47236. code += ',\n';
  47237. addWrapSnippet( texture.wrapR, 'z' );
  47238. }
  47239. code += '\n\t);\n\n}\n';
  47240. wgslCodeCache[ functionName ] = nodeCode = new CodeNode( code, includes );
  47241. }
  47242. nodeCode.build( this );
  47243. return functionName;
  47244. }
  47245. /**
  47246. * Generates the array declaration string.
  47247. *
  47248. * @param {string} type - The type.
  47249. * @param {?number} [count] - The count.
  47250. * @return {string} The generated value as a shader string.
  47251. */
  47252. generateArrayDeclaration( type, count ) {
  47253. return `array< ${ this.getType( type ) }, ${ count } >`;
  47254. }
  47255. /**
  47256. * Generates a WGSL variable that holds the texture dimension of the given texture.
  47257. * It also returns information about the number of layers (elements) of an arrayed
  47258. * texture as well as the cube face count of cube textures.
  47259. *
  47260. * @param {Texture} texture - The texture to generate the function for.
  47261. * @param {string} textureProperty - The name of the video texture uniform in the shader.
  47262. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  47263. * @return {string} The name of the dimension variable.
  47264. */
  47265. generateTextureDimension( texture, textureProperty, levelSnippet ) {
  47266. const textureData = this.getDataFromNode( texture, this.shaderStage, this.globalCache );
  47267. if ( textureData.dimensionsSnippet === undefined ) textureData.dimensionsSnippet = {};
  47268. let textureDimensionNode = textureData.dimensionsSnippet[ levelSnippet ];
  47269. if ( textureData.dimensionsSnippet[ levelSnippet ] === undefined ) {
  47270. let textureDimensionsParams;
  47271. let dimensionType;
  47272. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  47273. const isMultisampled = primarySamples > 1;
  47274. if ( texture.isData3DTexture ) {
  47275. dimensionType = 'vec3<u32>';
  47276. } else {
  47277. // Regular 2D textures, depth textures, etc.
  47278. dimensionType = 'vec2<u32>';
  47279. }
  47280. // Build parameters string based on texture type and multisampling
  47281. if ( isMultisampled || texture.isVideoTexture || texture.isStorageTexture ) {
  47282. textureDimensionsParams = textureProperty;
  47283. } else {
  47284. textureDimensionsParams = `${textureProperty}${levelSnippet ? `, u32( ${ levelSnippet } )` : ''}`;
  47285. }
  47286. textureDimensionNode = new VarNode( new ExpressionNode( `textureDimensions( ${ textureDimensionsParams } )`, dimensionType ) );
  47287. textureData.dimensionsSnippet[ levelSnippet ] = textureDimensionNode;
  47288. if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isData3DTexture ) {
  47289. textureData.arrayLayerCount = new VarNode(
  47290. new ExpressionNode(
  47291. `textureNumLayers(${textureProperty})`,
  47292. 'u32'
  47293. )
  47294. );
  47295. }
  47296. // For cube textures, we know it's always 6 faces
  47297. if ( texture.isTextureCube ) {
  47298. textureData.cubeFaceCount = new VarNode(
  47299. new ExpressionNode( '6u', 'u32' )
  47300. );
  47301. }
  47302. }
  47303. return textureDimensionNode.build( this );
  47304. }
  47305. /**
  47306. * Generates the WGSL snippet for a manual filtered texture.
  47307. *
  47308. * @param {Texture} texture - The texture.
  47309. * @param {string} textureProperty - The name of the texture uniform in the shader.
  47310. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  47311. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  47312. * @return {string} The WGSL snippet.
  47313. */
  47314. generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet = '0u' ) {
  47315. this._include( 'biquadraticTexture' );
  47316. const wrapFunction = this.generateWrapFunction( texture );
  47317. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  47318. return `tsl_biquadraticTexture( ${ textureProperty }, ${ wrapFunction }( ${ uvSnippet } ), ${ textureDimension }, u32( ${ levelSnippet } ) )`;
  47319. }
  47320. /**
  47321. * Generates the WGSL snippet for a texture lookup with explicit level-of-detail.
  47322. * Since it's a lookup, no sampling or filtering is applied.
  47323. *
  47324. * @param {Texture} texture - The texture.
  47325. * @param {string} textureProperty - The name of the texture uniform in the shader.
  47326. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  47327. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  47328. * @param {string} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  47329. * @return {string} The WGSL snippet.
  47330. */
  47331. generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet = '0u' ) {
  47332. const wrapFunction = this.generateWrapFunction( texture );
  47333. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  47334. const vecType = texture.isData3DTexture ? 'vec3' : 'vec2';
  47335. const coordSnippet = `${ vecType }<u32>( ${ wrapFunction }( ${ uvSnippet } ) * ${ vecType }<f32>( ${ textureDimension } ) )`;
  47336. return this.generateTextureLoad( texture, textureProperty, coordSnippet, depthSnippet, levelSnippet );
  47337. }
  47338. /**
  47339. * Generates the WGSL snippet that reads a single texel from a texture without sampling or filtering.
  47340. *
  47341. * @param {Texture} texture - The texture.
  47342. * @param {string} textureProperty - The name of the texture uniform in the shader.
  47343. * @param {string} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  47344. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  47345. * @param {string} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  47346. * @return {string} The WGSL snippet.
  47347. */
  47348. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0u' ) {
  47349. let snippet;
  47350. if ( texture.isVideoTexture === true ) {
  47351. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet } )`;
  47352. } else if ( depthSnippet ) {
  47353. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, u32( ${ levelSnippet } ) )`;
  47354. } else {
  47355. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, u32( ${ levelSnippet } ) )`;
  47356. if ( this.renderer.backend.compatibilityMode && texture.isDepthTexture ) {
  47357. snippet += '.x';
  47358. }
  47359. }
  47360. return snippet;
  47361. }
  47362. /**
  47363. * Generates the WGSL snippet that writes a single texel to a texture.
  47364. *
  47365. * @param {Texture} texture - The texture.
  47366. * @param {string} textureProperty - The name of the texture uniform in the shader.
  47367. * @param {string} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  47368. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  47369. * @param {string} valueSnippet - A WGSL snippet that represent the new texel value.
  47370. * @return {string} The WGSL snippet.
  47371. */
  47372. generateTextureStore( texture, textureProperty, uvIndexSnippet, depthSnippet, valueSnippet ) {
  47373. let snippet;
  47374. if ( depthSnippet ) {
  47375. snippet = `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, ${ valueSnippet } )`;
  47376. } else {
  47377. snippet = `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  47378. }
  47379. return snippet;
  47380. }
  47381. /**
  47382. * Returns `true` if the sampled values of the given texture should be compared against a reference value.
  47383. *
  47384. * @param {Texture} texture - The texture.
  47385. * @return {boolean} Whether the sampled values of the given texture should be compared against a reference value or not.
  47386. */
  47387. isSampleCompare( texture ) {
  47388. return texture.isDepthTexture === true && texture.compareFunction !== null;
  47389. }
  47390. /**
  47391. * Returns `true` if the given texture is unfilterable.
  47392. *
  47393. * @param {Texture} texture - The texture.
  47394. * @return {boolean} Whether the given texture is unfilterable or not.
  47395. */
  47396. isUnfilterable( texture ) {
  47397. return this.getComponentTypeFromTexture( texture ) !== 'float' ||
  47398. ( ! this.isAvailable( 'float32Filterable' ) && texture.isDataTexture === true && texture.type === FloatType ) ||
  47399. ( this.isSampleCompare( texture ) === false && texture.minFilter === NearestFilter && texture.magFilter === NearestFilter ) ||
  47400. this.renderer.backend.utils.getTextureSampleData( texture ).primarySamples > 1;
  47401. }
  47402. /**
  47403. * Generates the WGSL snippet for sampling/loading the given texture.
  47404. *
  47405. * @param {Texture} texture - The texture.
  47406. * @param {string} textureProperty - The name of the texture uniform in the shader.
  47407. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  47408. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  47409. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  47410. * @return {string} The WGSL snippet.
  47411. */
  47412. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  47413. let snippet = null;
  47414. if ( texture.isVideoTexture === true ) {
  47415. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  47416. } else if ( this.isUnfilterable( texture ) ) {
  47417. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, '0', shaderStage );
  47418. } else {
  47419. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage );
  47420. }
  47421. return snippet;
  47422. }
  47423. /**
  47424. * Generates the WGSL snippet for sampling/loading the given texture using explicit gradients.
  47425. *
  47426. * @param {Texture} texture - The texture.
  47427. * @param {string} textureProperty - The name of the texture uniform in the shader.
  47428. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  47429. * @param {Array<string>} gradSnippet - An array holding both gradient WGSL snippets.
  47430. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  47431. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  47432. * @return {string} The WGSL snippet.
  47433. */
  47434. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  47435. if ( shaderStage === 'fragment' ) {
  47436. // TODO handle i32 or u32 --> uvSnippet, array_index: A, ddx, ddy
  47437. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  47438. } else {
  47439. console.error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  47440. }
  47441. }
  47442. /**
  47443. * Generates the WGSL snippet for sampling a depth texture and comparing the sampled depth values
  47444. * against a reference value.
  47445. *
  47446. * @param {Texture} texture - The texture.
  47447. * @param {string} textureProperty - The name of the texture uniform in the shader.
  47448. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  47449. * @param {string} compareSnippet - A WGSL snippet that represents the reference value.
  47450. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  47451. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  47452. * @return {string} The WGSL snippet.
  47453. */
  47454. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  47455. if ( shaderStage === 'fragment' ) {
  47456. if ( texture.isDepthTexture === true && texture.isArrayTexture === true ) {
  47457. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } )`;
  47458. }
  47459. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  47460. } else {
  47461. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  47462. }
  47463. }
  47464. /**
  47465. * Generates the WGSL snippet when sampling textures with explicit mip level.
  47466. *
  47467. * @param {Texture} texture - The texture.
  47468. * @param {string} textureProperty - The name of the texture uniform in the shader.
  47469. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  47470. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  47471. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  47472. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  47473. * @return {string} The WGSL snippet.
  47474. */
  47475. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  47476. let snippet = null;
  47477. if ( texture.isVideoTexture === true ) {
  47478. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  47479. } else {
  47480. snippet = this._generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet );
  47481. }
  47482. return snippet;
  47483. }
  47484. /**
  47485. * Generates the WGSL snippet when sampling textures with a bias to the mip level.
  47486. *
  47487. * @param {Texture} texture - The texture.
  47488. * @param {string} textureProperty - The name of the texture uniform in the shader.
  47489. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  47490. * @param {string} biasSnippet - A WGSL snippet that represents the bias to apply to the mip level before sampling.
  47491. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  47492. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  47493. * @return {string} The WGSL snippet.
  47494. */
  47495. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  47496. if ( shaderStage === 'fragment' ) {
  47497. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  47498. } else {
  47499. console.error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  47500. }
  47501. }
  47502. /**
  47503. * Returns a WGSL snippet that represents the property name of the given node.
  47504. *
  47505. * @param {Node} node - The node.
  47506. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  47507. * @return {string} The property name.
  47508. */
  47509. getPropertyName( node, shaderStage = this.shaderStage ) {
  47510. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  47511. if ( shaderStage === 'vertex' ) {
  47512. return `varyings.${ node.name }`;
  47513. }
  47514. } else if ( node.isNodeUniform === true ) {
  47515. const name = node.name;
  47516. const type = node.type;
  47517. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  47518. return name;
  47519. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  47520. if ( this.isCustomStruct( node ) ) {
  47521. return name;
  47522. }
  47523. return name + '.value';
  47524. } else {
  47525. return node.groupNode.name + '.' + name;
  47526. }
  47527. }
  47528. return super.getPropertyName( node );
  47529. }
  47530. /**
  47531. * Returns the output struct name.
  47532. *
  47533. * @return {string} The name of the output struct.
  47534. */
  47535. getOutputStructName() {
  47536. return 'output';
  47537. }
  47538. /**
  47539. * Returns the native shader operator name for a given generic name.
  47540. *
  47541. * @param {string} op - The operator name to resolve.
  47542. * @return {?string} The resolved operator name.
  47543. */
  47544. getFunctionOperator( op ) {
  47545. const fnOp = wgslFnOpLib[ op ];
  47546. if ( fnOp !== undefined ) {
  47547. this._include( fnOp );
  47548. return fnOp;
  47549. }
  47550. return null;
  47551. }
  47552. /**
  47553. * Returns the node access for the given node and shader stage.
  47554. *
  47555. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  47556. * @param {string} shaderStage - The shader stage.
  47557. * @return {string} The node access.
  47558. */
  47559. getNodeAccess( node, shaderStage ) {
  47560. if ( shaderStage !== 'compute' )
  47561. return NodeAccess.READ_ONLY;
  47562. return node.access;
  47563. }
  47564. /**
  47565. * Returns A WGSL snippet representing the storage access.
  47566. *
  47567. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  47568. * @param {string} shaderStage - The shader stage.
  47569. * @return {string} The WGSL snippet representing the storage access.
  47570. */
  47571. getStorageAccess( node, shaderStage ) {
  47572. return accessNames[ this.getNodeAccess( node, shaderStage ) ];
  47573. }
  47574. /**
  47575. * This method is one of the more important ones since it's responsible
  47576. * for generating a matching binding instance for the given uniform node.
  47577. *
  47578. * These bindings are later used in the renderer to create bind groups
  47579. * and layouts.
  47580. *
  47581. * @param {UniformNode} node - The uniform node.
  47582. * @param {string} type - The node data type.
  47583. * @param {string} shaderStage - The shader stage.
  47584. * @param {?string} [name=null] - An optional uniform name.
  47585. * @return {NodeUniform} The node uniform object.
  47586. */
  47587. getUniformFromNode( node, type, shaderStage, name = null ) {
  47588. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  47589. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  47590. if ( nodeData.uniformGPU === undefined ) {
  47591. let uniformGPU;
  47592. const group = node.groupNode;
  47593. const groupName = group.name;
  47594. const bindings = this.getBindGroupArray( groupName, shaderStage );
  47595. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  47596. let texture = null;
  47597. const access = this.getNodeAccess( node, shaderStage );
  47598. if ( type === 'texture' || type === 'storageTexture' ) {
  47599. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, access );
  47600. } else if ( type === 'cubeTexture' ) {
  47601. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, access );
  47602. } else if ( type === 'texture3D' ) {
  47603. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  47604. }
  47605. texture.store = node.isStorageTextureNode === true;
  47606. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  47607. if ( this.isUnfilterable( node.value ) === false && texture.store === false ) {
  47608. const sampler = new NodeSampler( `${ uniformNode.name }_sampler`, uniformNode.node, group );
  47609. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  47610. bindings.push( sampler, texture );
  47611. uniformGPU = [ sampler, texture ];
  47612. } else {
  47613. bindings.push( texture );
  47614. uniformGPU = [ texture ];
  47615. }
  47616. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  47617. const bufferClass = type === 'buffer' ? NodeUniformBuffer : NodeStorageBuffer;
  47618. const buffer = new bufferClass( node, group );
  47619. buffer.setVisibility( gpuShaderStageLib[ shaderStage ] );
  47620. bindings.push( buffer );
  47621. uniformGPU = buffer;
  47622. uniformNode.name = name ? name : 'NodeBuffer_' + uniformNode.id;
  47623. } else {
  47624. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  47625. let uniformsGroup = uniformsStage[ groupName ];
  47626. if ( uniformsGroup === undefined ) {
  47627. uniformsGroup = new NodeUniformsGroup( groupName, group );
  47628. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  47629. uniformsStage[ groupName ] = uniformsGroup;
  47630. bindings.push( uniformsGroup );
  47631. }
  47632. uniformGPU = this.getNodeUniform( uniformNode, type );
  47633. uniformsGroup.addUniform( uniformGPU );
  47634. }
  47635. nodeData.uniformGPU = uniformGPU;
  47636. }
  47637. return uniformNode;
  47638. }
  47639. /**
  47640. * This method should be used whenever builtins are required in nodes.
  47641. * The internal builtins data structure will make sure builtins are
  47642. * defined in the WGSL source.
  47643. *
  47644. * @param {string} name - The builtin name.
  47645. * @param {string} property - The property name.
  47646. * @param {string} type - The node data type.
  47647. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  47648. * @return {string} The property name.
  47649. */
  47650. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  47651. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  47652. if ( map.has( name ) === false ) {
  47653. map.set( name, {
  47654. name,
  47655. property,
  47656. type
  47657. } );
  47658. }
  47659. return property;
  47660. }
  47661. /**
  47662. * Returns `true` if the given builtin is defined in the given shader stage.
  47663. *
  47664. * @param {string} name - The builtin name.
  47665. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  47666. * @return {boolean} Whether the given builtin is defined in the given shader stage or not.
  47667. */
  47668. hasBuiltin( name, shaderStage = this.shaderStage ) {
  47669. return ( this.builtins[ shaderStage ] !== undefined && this.builtins[ shaderStage ].has( name ) );
  47670. }
  47671. /**
  47672. * Returns the vertex index builtin.
  47673. *
  47674. * @return {string} The vertex index.
  47675. */
  47676. getVertexIndex() {
  47677. if ( this.shaderStage === 'vertex' ) {
  47678. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  47679. }
  47680. return 'vertexIndex';
  47681. }
  47682. /**
  47683. * Builds the given shader node.
  47684. *
  47685. * @param {ShaderNodeInternal} shaderNode - The shader node.
  47686. * @return {string} The WGSL function code.
  47687. */
  47688. buildFunctionCode( shaderNode ) {
  47689. const layout = shaderNode.layout;
  47690. const flowData = this.flowShaderNode( shaderNode );
  47691. const parameters = [];
  47692. for ( const input of layout.inputs ) {
  47693. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  47694. }
  47695. //
  47696. let code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  47697. ${ flowData.vars }
  47698. ${ flowData.code }
  47699. `;
  47700. if ( flowData.result ) {
  47701. code += `\treturn ${ flowData.result };\n`;
  47702. }
  47703. code += '\n}\n';
  47704. //
  47705. return code;
  47706. }
  47707. /**
  47708. * Returns the instance index builtin.
  47709. *
  47710. * @return {string} The instance index.
  47711. */
  47712. getInstanceIndex() {
  47713. if ( this.shaderStage === 'vertex' ) {
  47714. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  47715. }
  47716. return 'instanceIndex';
  47717. }
  47718. /**
  47719. * Returns the invocation local index builtin.
  47720. *
  47721. * @return {string} The invocation local index.
  47722. */
  47723. getInvocationLocalIndex() {
  47724. return this.getBuiltin( 'local_invocation_index', 'invocationLocalIndex', 'u32', 'attribute' );
  47725. }
  47726. /**
  47727. * Returns the subgroup size builtin.
  47728. *
  47729. * @return {string} The subgroup size.
  47730. */
  47731. getSubgroupSize() {
  47732. this.enableSubGroups();
  47733. return this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  47734. }
  47735. /**
  47736. * Returns the invocation subgroup index builtin.
  47737. *
  47738. * @return {string} The invocation subgroup index.
  47739. */
  47740. getInvocationSubgroupIndex() {
  47741. this.enableSubGroups();
  47742. return this.getBuiltin( 'subgroup_invocation_id', 'invocationSubgroupIndex', 'u32', 'attribute' );
  47743. }
  47744. /**
  47745. * Returns the subgroup index builtin.
  47746. *
  47747. * @return {string} The subgroup index.
  47748. */
  47749. getSubgroupIndex() {
  47750. this.enableSubGroups();
  47751. return this.getBuiltin( 'subgroup_id', 'subgroupIndex', 'u32', 'attribute' );
  47752. }
  47753. /**
  47754. * Overwritten as a NOP since this method is intended for the WebGL 2 backend.
  47755. *
  47756. * @return {null} Null.
  47757. */
  47758. getDrawIndex() {
  47759. return null;
  47760. }
  47761. /**
  47762. * Returns the front facing builtin.
  47763. *
  47764. * @return {string} The front facing builtin.
  47765. */
  47766. getFrontFacing() {
  47767. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  47768. }
  47769. /**
  47770. * Returns the frag coord builtin.
  47771. *
  47772. * @return {string} The frag coord builtin.
  47773. */
  47774. getFragCoord() {
  47775. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xy';
  47776. }
  47777. /**
  47778. * Returns the frag depth builtin.
  47779. *
  47780. * @return {string} The frag depth builtin.
  47781. */
  47782. getFragDepth() {
  47783. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  47784. }
  47785. /**
  47786. * Returns the clip distances builtin.
  47787. *
  47788. * @return {string} The clip distances builtin.
  47789. */
  47790. getClipDistance() {
  47791. return 'varyings.hw_clip_distances';
  47792. }
  47793. /**
  47794. * Whether to flip texture data along its vertical axis or not.
  47795. *
  47796. * @return {boolean} Returns always `false` in context of WGSL.
  47797. */
  47798. isFlipY() {
  47799. return false;
  47800. }
  47801. /**
  47802. * Enables the given directive for the given shader stage.
  47803. *
  47804. * @param {string} name - The directive name.
  47805. * @param {string} [shaderStage=this.shaderStage] - The shader stage to enable the directive for.
  47806. */
  47807. enableDirective( name, shaderStage = this.shaderStage ) {
  47808. const stage = this.directives[ shaderStage ] || ( this.directives[ shaderStage ] = new Set() );
  47809. stage.add( name );
  47810. }
  47811. /**
  47812. * Returns the directives of the given shader stage as a WGSL string.
  47813. *
  47814. * @param {string} shaderStage - The shader stage.
  47815. * @return {string} A WGSL snippet that enables the directives of the given stage.
  47816. */
  47817. getDirectives( shaderStage ) {
  47818. const snippets = [];
  47819. const directives = this.directives[ shaderStage ];
  47820. if ( directives !== undefined ) {
  47821. for ( const directive of directives ) {
  47822. snippets.push( `enable ${directive};` );
  47823. }
  47824. }
  47825. return snippets.join( '\n' );
  47826. }
  47827. /**
  47828. * Enables the 'subgroups' directive.
  47829. */
  47830. enableSubGroups() {
  47831. this.enableDirective( 'subgroups' );
  47832. }
  47833. /**
  47834. * Enables the 'subgroups-f16' directive.
  47835. */
  47836. enableSubgroupsF16() {
  47837. this.enableDirective( 'subgroups-f16' );
  47838. }
  47839. /**
  47840. * Enables the 'clip_distances' directive.
  47841. */
  47842. enableClipDistances() {
  47843. this.enableDirective( 'clip_distances' );
  47844. }
  47845. /**
  47846. * Enables the 'f16' directive.
  47847. */
  47848. enableShaderF16() {
  47849. this.enableDirective( 'f16' );
  47850. }
  47851. /**
  47852. * Enables the 'dual_source_blending' directive.
  47853. */
  47854. enableDualSourceBlending() {
  47855. this.enableDirective( 'dual_source_blending' );
  47856. }
  47857. /**
  47858. * Enables hardware clipping.
  47859. *
  47860. * @param {string} planeCount - The clipping plane count.
  47861. */
  47862. enableHardwareClipping( planeCount ) {
  47863. this.enableClipDistances();
  47864. this.getBuiltin( 'clip_distances', 'hw_clip_distances', `array<f32, ${ planeCount } >`, 'vertex' );
  47865. }
  47866. /**
  47867. * Returns the builtins of the given shader stage as a WGSL string.
  47868. *
  47869. * @param {string} shaderStage - The shader stage.
  47870. * @return {string} A WGSL snippet that represents the builtins of the given stage.
  47871. */
  47872. getBuiltins( shaderStage ) {
  47873. const snippets = [];
  47874. const builtins = this.builtins[ shaderStage ];
  47875. if ( builtins !== undefined ) {
  47876. for ( const { name, property, type } of builtins.values() ) {
  47877. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  47878. }
  47879. }
  47880. return snippets.join( ',\n\t' );
  47881. }
  47882. /**
  47883. * This method should be used when a new scoped buffer is used in context of
  47884. * compute shaders. It adds the array to the internal data structure which is
  47885. * later used to generate the respective WGSL.
  47886. *
  47887. * @param {string} name - The array name.
  47888. * @param {string} scope - The scope.
  47889. * @param {string} bufferType - The buffer type.
  47890. * @param {string} bufferCount - The buffer count.
  47891. * @return {string} The array name.
  47892. */
  47893. getScopedArray( name, scope, bufferType, bufferCount ) {
  47894. if ( this.scopedArrays.has( name ) === false ) {
  47895. this.scopedArrays.set( name, {
  47896. name,
  47897. scope,
  47898. bufferType,
  47899. bufferCount
  47900. } );
  47901. }
  47902. return name;
  47903. }
  47904. /**
  47905. * Returns the scoped arrays of the given shader stage as a WGSL string.
  47906. *
  47907. * @param {string} shaderStage - The shader stage.
  47908. * @return {string|undefined} The WGSL snippet that defines the scoped arrays.
  47909. * Returns `undefined` when used in the vertex or fragment stage.
  47910. */
  47911. getScopedArrays( shaderStage ) {
  47912. if ( shaderStage !== 'compute' ) {
  47913. return;
  47914. }
  47915. const snippets = [];
  47916. for ( const { name, scope, bufferType, bufferCount } of this.scopedArrays.values() ) {
  47917. const type = this.getType( bufferType );
  47918. snippets.push( `var<${scope}> ${name}: array< ${type}, ${bufferCount} >;` );
  47919. }
  47920. return snippets.join( '\n' );
  47921. }
  47922. /**
  47923. * Returns the shader attributes of the given shader stage as a WGSL string.
  47924. *
  47925. * @param {string} shaderStage - The shader stage.
  47926. * @return {string} The WGSL snippet that defines the shader attributes.
  47927. */
  47928. getAttributes( shaderStage ) {
  47929. const snippets = [];
  47930. if ( shaderStage === 'compute' ) {
  47931. this.getBuiltin( 'global_invocation_id', 'globalId', 'vec3<u32>', 'attribute' );
  47932. this.getBuiltin( 'workgroup_id', 'workgroupId', 'vec3<u32>', 'attribute' );
  47933. this.getBuiltin( 'local_invocation_id', 'localId', 'vec3<u32>', 'attribute' );
  47934. this.getBuiltin( 'num_workgroups', 'numWorkgroups', 'vec3<u32>', 'attribute' );
  47935. if ( this.renderer.hasFeature( 'subgroups' ) ) {
  47936. this.enableDirective( 'subgroups', shaderStage );
  47937. this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  47938. }
  47939. }
  47940. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  47941. const builtins = this.getBuiltins( 'attribute' );
  47942. if ( builtins ) snippets.push( builtins );
  47943. const attributes = this.getAttributesArray();
  47944. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  47945. const attribute = attributes[ index ];
  47946. const name = attribute.name;
  47947. const type = this.getType( attribute.type );
  47948. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  47949. }
  47950. }
  47951. return snippets.join( ',\n\t' );
  47952. }
  47953. /**
  47954. * Returns the members of the given struct type node as a WGSL string.
  47955. *
  47956. * @param {StructTypeNode} struct - The struct type node.
  47957. * @return {string} The WGSL snippet that defines the struct members.
  47958. */
  47959. getStructMembers( struct ) {
  47960. const snippets = [];
  47961. for ( const member of struct.members ) {
  47962. const prefix = struct.output ? '@location( ' + member.index + ' ) ' : '';
  47963. let type = this.getType( member.type );
  47964. if ( member.atomic ) {
  47965. type = 'atomic< ' + type + ' >';
  47966. }
  47967. snippets.push( `\t${ prefix + member.name } : ${ type }` );
  47968. }
  47969. if ( struct.output ) {
  47970. snippets.push( `\t${ this.getBuiltins( 'output' ) }` );
  47971. }
  47972. return snippets.join( ',\n' );
  47973. }
  47974. /**
  47975. * Returns the structs of the given shader stage as a WGSL string.
  47976. *
  47977. * @param {string} shaderStage - The shader stage.
  47978. * @return {string} The WGSL snippet that defines the structs.
  47979. */
  47980. getStructs( shaderStage ) {
  47981. let result = '';
  47982. const structs = this.structs[ shaderStage ];
  47983. if ( structs.length > 0 ) {
  47984. const snippets = [];
  47985. for ( const struct of structs ) {
  47986. let snippet = `struct ${ struct.name } {\n`;
  47987. snippet += this.getStructMembers( struct );
  47988. snippet += '\n};';
  47989. snippets.push( snippet );
  47990. }
  47991. result = '\n' + snippets.join( '\n\n' ) + '\n';
  47992. }
  47993. return result;
  47994. }
  47995. /**
  47996. * Returns a WGSL string representing a variable.
  47997. *
  47998. * @param {string} type - The variable's type.
  47999. * @param {string} name - The variable's name.
  48000. * @param {?number} [count=null] - The array length.
  48001. * @return {string} The WGSL snippet that defines a variable.
  48002. */
  48003. getVar( type, name, count = null ) {
  48004. let snippet = `var ${ name } : `;
  48005. if ( count !== null ) {
  48006. snippet += this.generateArrayDeclaration( type, count );
  48007. } else {
  48008. snippet += this.getType( type );
  48009. }
  48010. return snippet;
  48011. }
  48012. /**
  48013. * Returns the variables of the given shader stage as a WGSL string.
  48014. *
  48015. * @param {string} shaderStage - The shader stage.
  48016. * @return {string} The WGSL snippet that defines the variables.
  48017. */
  48018. getVars( shaderStage ) {
  48019. const snippets = [];
  48020. const vars = this.vars[ shaderStage ];
  48021. if ( vars !== undefined ) {
  48022. for ( const variable of vars ) {
  48023. snippets.push( `\t${ this.getVar( variable.type, variable.name, variable.count ) };` );
  48024. }
  48025. }
  48026. return `\n${ snippets.join( '\n' ) }\n`;
  48027. }
  48028. /**
  48029. * Returns the varyings of the given shader stage as a WGSL string.
  48030. *
  48031. * @param {string} shaderStage - The shader stage.
  48032. * @return {string} The WGSL snippet that defines the varyings.
  48033. */
  48034. getVaryings( shaderStage ) {
  48035. const snippets = [];
  48036. if ( shaderStage === 'vertex' ) {
  48037. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  48038. }
  48039. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  48040. const varyings = this.varyings;
  48041. const vars = this.vars[ shaderStage ];
  48042. for ( let index = 0; index < varyings.length; index ++ ) {
  48043. const varying = varyings[ index ];
  48044. if ( varying.needsInterpolation ) {
  48045. let attributesSnippet = `@location( ${index} )`;
  48046. if ( varying.interpolationType ) {
  48047. const samplingSnippet = varying.interpolationSampling !== null ? `, ${ varying.interpolationSampling } )` : ' )';
  48048. attributesSnippet += ` @interpolate( ${ varying.interpolationType }${ samplingSnippet }`;
  48049. // Otherwise, optimize interpolation when sensible
  48050. } else if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  48051. attributesSnippet += ` @interpolate( ${ this.renderer.backend.compatibilityMode ? 'flat, either' : 'flat' } )`;
  48052. }
  48053. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  48054. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  48055. vars.push( varying );
  48056. }
  48057. }
  48058. }
  48059. const builtins = this.getBuiltins( shaderStage );
  48060. if ( builtins ) snippets.push( builtins );
  48061. const code = snippets.join( ',\n\t' );
  48062. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  48063. }
  48064. isCustomStruct( nodeUniform ) {
  48065. const attribute = nodeUniform.value;
  48066. const bufferNode = nodeUniform.node;
  48067. const isAttributeStructType = ( attribute.isBufferAttribute || attribute.isInstancedBufferAttribute ) && bufferNode.structTypeNode !== null;
  48068. const isStructArray =
  48069. ( bufferNode.value && bufferNode.value.array ) &&
  48070. ( typeof bufferNode.value.itemSize === 'number' && bufferNode.value.array.length > bufferNode.value.itemSize );
  48071. return isAttributeStructType && ! isStructArray;
  48072. }
  48073. /**
  48074. * Returns the uniforms of the given shader stage as a WGSL string.
  48075. *
  48076. * @param {string} shaderStage - The shader stage.
  48077. * @return {string} The WGSL snippet that defines the uniforms.
  48078. */
  48079. getUniforms( shaderStage ) {
  48080. const uniforms = this.uniforms[ shaderStage ];
  48081. const bindingSnippets = [];
  48082. const bufferSnippets = [];
  48083. const structSnippets = [];
  48084. const uniformGroups = {};
  48085. for ( const uniform of uniforms ) {
  48086. const groupName = uniform.groupNode.name;
  48087. const uniformIndexes = this.bindingsIndexes[ groupName ];
  48088. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  48089. const texture = uniform.node.value;
  48090. if ( this.isUnfilterable( texture ) === false && uniform.node.isStorageTextureNode !== true ) {
  48091. if ( this.isSampleCompare( texture ) ) {
  48092. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  48093. } else {
  48094. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  48095. }
  48096. }
  48097. let textureType;
  48098. let multisampled = '';
  48099. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  48100. if ( primarySamples > 1 ) {
  48101. multisampled = '_multisampled';
  48102. }
  48103. if ( texture.isCubeTexture === true ) {
  48104. textureType = 'texture_cube<f32>';
  48105. } else if ( texture.isDepthTexture === true ) {
  48106. if ( this.renderer.backend.compatibilityMode && texture.compareFunction === null ) {
  48107. textureType = `texture${ multisampled }_2d<f32>`;
  48108. } else {
  48109. textureType = `texture_depth${ multisampled }_2d${ texture.isArrayTexture === true ? '_array' : '' }`;
  48110. }
  48111. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  48112. textureType = 'texture_2d_array<f32>';
  48113. } else if ( texture.isVideoTexture === true ) {
  48114. textureType = 'texture_external';
  48115. } else if ( texture.isData3DTexture === true ) {
  48116. textureType = 'texture_3d<f32>';
  48117. } else if ( uniform.node.isStorageTextureNode === true ) {
  48118. const format = getFormat( texture );
  48119. const access = this.getStorageAccess( uniform.node, shaderStage );
  48120. textureType = `texture_storage_2d<${ format }, ${ access }>`;
  48121. } else {
  48122. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  48123. textureType = `texture${ multisampled }_2d<${ componentPrefix }32>`;
  48124. }
  48125. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  48126. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' || uniform.type === 'indirectStorageBuffer' ) {
  48127. const bufferNode = uniform.node;
  48128. const bufferType = this.getType( bufferNode.getNodeType( this ) );
  48129. const bufferCount = bufferNode.bufferCount;
  48130. const bufferCountSnippet = bufferCount > 0 && uniform.type === 'buffer' ? ', ' + bufferCount : '';
  48131. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode, shaderStage ) }` : 'uniform';
  48132. if ( this.isCustomStruct( uniform ) ) {
  48133. bufferSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var<${ bufferAccessMode }> ${ uniform.name } : ${ bufferType };` );
  48134. } else {
  48135. const bufferTypeSnippet = bufferNode.isAtomic ? `atomic<${ bufferType }>` : `${ bufferType }`;
  48136. const bufferSnippet = `\tvalue : array< ${ bufferTypeSnippet }${ bufferCountSnippet } >`;
  48137. bufferSnippets.push( this._getWGSLStructBinding( uniform.name, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  48138. }
  48139. } else {
  48140. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  48141. const groupName = uniform.groupNode.name;
  48142. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  48143. index: uniformIndexes.binding ++,
  48144. id: uniformIndexes.group,
  48145. snippets: []
  48146. } );
  48147. group.snippets.push( `\t${ uniform.name } : ${ vectorType }` );
  48148. }
  48149. }
  48150. for ( const name in uniformGroups ) {
  48151. const group = uniformGroups[ name ];
  48152. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  48153. }
  48154. let code = bindingSnippets.join( '\n' );
  48155. code += bufferSnippets.join( '\n' );
  48156. code += structSnippets.join( '\n' );
  48157. return code;
  48158. }
  48159. /**
  48160. * Controls the code build of the shader stages.
  48161. */
  48162. buildCode() {
  48163. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  48164. this.sortBindingGroups();
  48165. for ( const shaderStage in shadersData ) {
  48166. this.shaderStage = shaderStage;
  48167. const stageData = shadersData[ shaderStage ];
  48168. stageData.uniforms = this.getUniforms( shaderStage );
  48169. stageData.attributes = this.getAttributes( shaderStage );
  48170. stageData.varyings = this.getVaryings( shaderStage );
  48171. stageData.structs = this.getStructs( shaderStage );
  48172. stageData.vars = this.getVars( shaderStage );
  48173. stageData.codes = this.getCodes( shaderStage );
  48174. stageData.directives = this.getDirectives( shaderStage );
  48175. stageData.scopedArrays = this.getScopedArrays( shaderStage );
  48176. //
  48177. let flow = '// code\n\n';
  48178. flow += this.flowCode[ shaderStage ];
  48179. const flowNodes = this.flowNodes[ shaderStage ];
  48180. const mainNode = flowNodes[ flowNodes.length - 1 ];
  48181. const outputNode = mainNode.outputNode;
  48182. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  48183. for ( const node of flowNodes ) {
  48184. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  48185. const slotName = node.name;
  48186. if ( slotName ) {
  48187. if ( flow.length > 0 ) flow += '\n';
  48188. flow += `\t// flow -> ${ slotName }\n`;
  48189. }
  48190. flow += `${ flowSlotData.code }\n\t`;
  48191. if ( node === mainNode && shaderStage !== 'compute' ) {
  48192. flow += '// result\n\n\t';
  48193. if ( shaderStage === 'vertex' ) {
  48194. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  48195. } else if ( shaderStage === 'fragment' ) {
  48196. if ( isOutputStruct ) {
  48197. stageData.returnType = outputNode.getNodeType( this );
  48198. stageData.structs += 'var<private> output : ' + stageData.returnType + ';';
  48199. flow += `return ${ flowSlotData.result };`;
  48200. } else {
  48201. let structSnippet = '\t@location(0) color: vec4<f32>';
  48202. const builtins = this.getBuiltins( 'output' );
  48203. if ( builtins ) structSnippet += ',\n\t' + builtins;
  48204. stageData.returnType = 'OutputStruct';
  48205. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  48206. stageData.structs += '\nvar<private> output : OutputStruct;';
  48207. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  48208. }
  48209. }
  48210. }
  48211. }
  48212. stageData.flow = flow;
  48213. }
  48214. this.shaderStage = null;
  48215. if ( this.material !== null ) {
  48216. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  48217. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  48218. } else {
  48219. this.computeShader = this._getWGSLComputeCode( shadersData.compute, ( this.object.workgroupSize || [ 64 ] ).join( ', ' ) );
  48220. }
  48221. }
  48222. /**
  48223. * Returns the native shader method name for a given generic name.
  48224. *
  48225. * @param {string} method - The method name to resolve.
  48226. * @param {?string} [output=null] - An optional output.
  48227. * @return {string} The resolved WGSL method name.
  48228. */
  48229. getMethod( method, output = null ) {
  48230. let wgslMethod;
  48231. if ( output !== null ) {
  48232. wgslMethod = this._getWGSLMethod( method + '_' + output );
  48233. }
  48234. if ( wgslMethod === undefined ) {
  48235. wgslMethod = this._getWGSLMethod( method );
  48236. }
  48237. return wgslMethod || method;
  48238. }
  48239. /**
  48240. * Returns the WGSL type of the given node data type.
  48241. *
  48242. * @param {string} type - The node data type.
  48243. * @return {string} The WGSL type.
  48244. */
  48245. getType( type ) {
  48246. return wgslTypeLib[ type ] || type;
  48247. }
  48248. /**
  48249. * Whether the requested feature is available or not.
  48250. *
  48251. * @param {string} name - The requested feature.
  48252. * @return {boolean} Whether the requested feature is supported or not.
  48253. */
  48254. isAvailable( name ) {
  48255. let result = supports[ name ];
  48256. if ( result === undefined ) {
  48257. if ( name === 'float32Filterable' ) {
  48258. result = this.renderer.hasFeature( 'float32-filterable' );
  48259. } else if ( name === 'clipDistance' ) {
  48260. result = this.renderer.hasFeature( 'clip-distances' );
  48261. }
  48262. supports[ name ] = result;
  48263. }
  48264. return result;
  48265. }
  48266. /**
  48267. * Returns the native shader method name for a given generic name.
  48268. *
  48269. * @private
  48270. * @param {string} method - The method name to resolve.
  48271. * @return {string} The resolved WGSL method name.
  48272. */
  48273. _getWGSLMethod( method ) {
  48274. if ( wgslPolyfill[ method ] !== undefined ) {
  48275. this._include( method );
  48276. }
  48277. return wgslMethods[ method ];
  48278. }
  48279. /**
  48280. * Includes the given method name into the current
  48281. * function node.
  48282. *
  48283. * @private
  48284. * @param {string} name - The method name to include.
  48285. * @return {CodeNode} The respective code node.
  48286. */
  48287. _include( name ) {
  48288. const codeNode = wgslPolyfill[ name ];
  48289. codeNode.build( this );
  48290. if ( this.currentFunctionNode !== null ) {
  48291. this.currentFunctionNode.includes.push( codeNode );
  48292. }
  48293. return codeNode;
  48294. }
  48295. /**
  48296. * Returns a WGSL vertex shader based on the given shader data.
  48297. *
  48298. * @private
  48299. * @param {Object} shaderData - The shader data.
  48300. * @return {string} The vertex shader.
  48301. */
  48302. _getWGSLVertexCode( shaderData ) {
  48303. return `${ this.getSignature() }
  48304. // directives
  48305. ${shaderData.directives}
  48306. // structs
  48307. ${shaderData.structs}
  48308. // uniforms
  48309. ${shaderData.uniforms}
  48310. // varyings
  48311. ${shaderData.varyings}
  48312. var<private> varyings : VaryingsStruct;
  48313. // codes
  48314. ${shaderData.codes}
  48315. @vertex
  48316. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  48317. // vars
  48318. ${shaderData.vars}
  48319. // flow
  48320. ${shaderData.flow}
  48321. return varyings;
  48322. }
  48323. `;
  48324. }
  48325. /**
  48326. * Returns a WGSL fragment shader based on the given shader data.
  48327. *
  48328. * @private
  48329. * @param {Object} shaderData - The shader data.
  48330. * @return {string} The vertex shader.
  48331. */
  48332. _getWGSLFragmentCode( shaderData ) {
  48333. return `${ this.getSignature() }
  48334. // global
  48335. ${ diagnostics }
  48336. // structs
  48337. ${shaderData.structs}
  48338. // uniforms
  48339. ${shaderData.uniforms}
  48340. // codes
  48341. ${shaderData.codes}
  48342. @fragment
  48343. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  48344. // vars
  48345. ${shaderData.vars}
  48346. // flow
  48347. ${shaderData.flow}
  48348. }
  48349. `;
  48350. }
  48351. /**
  48352. * Returns a WGSL compute shader based on the given shader data.
  48353. *
  48354. * @private
  48355. * @param {Object} shaderData - The shader data.
  48356. * @param {string} workgroupSize - The workgroup size.
  48357. * @return {string} The vertex shader.
  48358. */
  48359. _getWGSLComputeCode( shaderData, workgroupSize ) {
  48360. return `${ this.getSignature() }
  48361. // directives
  48362. ${shaderData.directives}
  48363. // system
  48364. var<private> instanceIndex : u32;
  48365. // locals
  48366. ${shaderData.scopedArrays}
  48367. // structs
  48368. ${shaderData.structs}
  48369. // uniforms
  48370. ${shaderData.uniforms}
  48371. // codes
  48372. ${shaderData.codes}
  48373. @compute @workgroup_size( ${workgroupSize} )
  48374. fn main( ${shaderData.attributes} ) {
  48375. // system
  48376. instanceIndex = globalId.x + globalId.y * numWorkgroups.x * u32(${workgroupSize}) + globalId.z * numWorkgroups.x * numWorkgroups.y * u32(${workgroupSize});
  48377. // vars
  48378. ${shaderData.vars}
  48379. // flow
  48380. ${shaderData.flow}
  48381. }
  48382. `;
  48383. }
  48384. /**
  48385. * Returns a WGSL struct based on the given name and variables.
  48386. *
  48387. * @private
  48388. * @param {string} name - The struct name.
  48389. * @param {string} vars - The struct variables.
  48390. * @return {string} The WGSL snippet representing a struct.
  48391. */
  48392. _getWGSLStruct( name, vars ) {
  48393. return `
  48394. struct ${name} {
  48395. ${vars}
  48396. };`;
  48397. }
  48398. /**
  48399. * Returns a WGSL struct binding.
  48400. *
  48401. * @private
  48402. * @param {string} name - The struct name.
  48403. * @param {string} vars - The struct variables.
  48404. * @param {string} access - The access.
  48405. * @param {number} [binding=0] - The binding index.
  48406. * @param {number} [group=0] - The group index.
  48407. * @return {string} The WGSL snippet representing a struct binding.
  48408. */
  48409. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  48410. const structName = name + 'Struct';
  48411. const structSnippet = this._getWGSLStruct( structName, vars );
  48412. return `${structSnippet}
  48413. @binding( ${ binding } ) @group( ${ group } )
  48414. var<${access}> ${ name } : ${ structName };`;
  48415. }
  48416. }
  48417. /**
  48418. * A WebGPU backend utility module with common helpers.
  48419. *
  48420. * @private
  48421. */
  48422. class WebGPUUtils {
  48423. /**
  48424. * Constructs a new utility object.
  48425. *
  48426. * @param {WebGPUBackend} backend - The WebGPU backend.
  48427. */
  48428. constructor( backend ) {
  48429. /**
  48430. * A reference to the WebGPU backend.
  48431. *
  48432. * @type {WebGPUBackend}
  48433. */
  48434. this.backend = backend;
  48435. }
  48436. /**
  48437. * Returns the depth/stencil GPU format for the given render context.
  48438. *
  48439. * @param {RenderContext} renderContext - The render context.
  48440. * @return {string} The depth/stencil GPU texture format.
  48441. */
  48442. getCurrentDepthStencilFormat( renderContext ) {
  48443. let format;
  48444. if ( renderContext.depthTexture !== null ) {
  48445. format = this.getTextureFormatGPU( renderContext.depthTexture );
  48446. } else if ( renderContext.depth && renderContext.stencil ) {
  48447. format = GPUTextureFormat.Depth24PlusStencil8;
  48448. } else if ( renderContext.depth ) {
  48449. format = GPUTextureFormat.Depth24Plus;
  48450. }
  48451. return format;
  48452. }
  48453. /**
  48454. * Returns the GPU format for the given texture.
  48455. *
  48456. * @param {Texture} texture - The texture.
  48457. * @return {string} The GPU texture format.
  48458. */
  48459. getTextureFormatGPU( texture ) {
  48460. return this.backend.get( texture ).format;
  48461. }
  48462. /**
  48463. * Returns an object that defines the multi-sampling state of the given texture.
  48464. *
  48465. * @param {Texture} texture - The texture.
  48466. * @return {Object} The multi-sampling state.
  48467. */
  48468. getTextureSampleData( texture ) {
  48469. let samples;
  48470. if ( texture.isFramebufferTexture ) {
  48471. samples = 1;
  48472. } else if ( texture.isDepthTexture && ! texture.renderTarget ) {
  48473. const renderer = this.backend.renderer;
  48474. const renderTarget = renderer.getRenderTarget();
  48475. samples = renderTarget ? renderTarget.samples : renderer.samples;
  48476. } else if ( texture.renderTarget ) {
  48477. samples = texture.renderTarget.samples;
  48478. }
  48479. samples = samples || 1;
  48480. const isMSAA = samples > 1 && texture.renderTarget !== null && ( texture.isDepthTexture !== true && texture.isFramebufferTexture !== true );
  48481. const primarySamples = isMSAA ? 1 : samples;
  48482. return { samples, primarySamples, isMSAA };
  48483. }
  48484. /**
  48485. * Returns the default color attachment's GPU format of the current render context.
  48486. *
  48487. * @param {RenderContext} renderContext - The render context.
  48488. * @return {string} The GPU texture format of the default color attachment.
  48489. */
  48490. getCurrentColorFormat( renderContext ) {
  48491. let format;
  48492. if ( renderContext.textures !== null ) {
  48493. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  48494. } else {
  48495. format = this.getPreferredCanvasFormat(); // default context format
  48496. }
  48497. return format;
  48498. }
  48499. /**
  48500. * Returns the output color space of the current render context.
  48501. *
  48502. * @param {RenderContext} renderContext - The render context.
  48503. * @return {string} The output color space.
  48504. */
  48505. getCurrentColorSpace( renderContext ) {
  48506. if ( renderContext.textures !== null ) {
  48507. return renderContext.textures[ 0 ].colorSpace;
  48508. }
  48509. return this.backend.renderer.outputColorSpace;
  48510. }
  48511. /**
  48512. * Returns GPU primitive topology for the given object and material.
  48513. *
  48514. * @param {Object3D} object - The 3D object.
  48515. * @param {Material} material - The material.
  48516. * @return {string} The GPU primitive topology.
  48517. */
  48518. getPrimitiveTopology( object, material ) {
  48519. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  48520. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  48521. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  48522. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  48523. }
  48524. /**
  48525. * Returns a modified sample count from the given sample count value.
  48526. *
  48527. * That is required since WebGPU does not support arbitrary sample counts.
  48528. *
  48529. * @param {number} sampleCount - The input sample count.
  48530. * @return {number} The (potentially updated) output sample count.
  48531. */
  48532. getSampleCount( sampleCount ) {
  48533. let count = 1;
  48534. if ( sampleCount > 1 ) {
  48535. // WebGPU only supports power-of-two sample counts and 2 is not a valid value
  48536. count = Math.pow( 2, Math.floor( Math.log2( sampleCount ) ) );
  48537. if ( count === 2 ) {
  48538. count = 4;
  48539. }
  48540. }
  48541. return count;
  48542. }
  48543. /**
  48544. * Returns the sample count of the given render context.
  48545. *
  48546. * @param {RenderContext} renderContext - The render context.
  48547. * @return {number} The sample count.
  48548. */
  48549. getSampleCountRenderContext( renderContext ) {
  48550. if ( renderContext.textures !== null ) {
  48551. return this.getSampleCount( renderContext.sampleCount );
  48552. }
  48553. return this.getSampleCount( this.backend.renderer.samples );
  48554. }
  48555. /**
  48556. * Returns the preferred canvas format.
  48557. *
  48558. * There is a separate method for this so it's possible to
  48559. * honor edge cases for specific devices.
  48560. *
  48561. * @return {string} The GPU texture format of the canvas.
  48562. */
  48563. getPreferredCanvasFormat() {
  48564. const outputType = this.backend.parameters.outputType;
  48565. if ( outputType === undefined ) {
  48566. return navigator.gpu.getPreferredCanvasFormat();
  48567. } else if ( outputType === UnsignedByteType ) {
  48568. return GPUTextureFormat.BGRA8Unorm;
  48569. } else if ( outputType === HalfFloatType ) {
  48570. return GPUTextureFormat.RGBA16Float;
  48571. } else {
  48572. throw new Error( 'Unsupported outputType' );
  48573. }
  48574. }
  48575. }
  48576. const typedArraysToVertexFormatPrefix = new Map( [
  48577. [ Int8Array, [ 'sint8', 'snorm8' ]],
  48578. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  48579. [ Int16Array, [ 'sint16', 'snorm16' ]],
  48580. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  48581. [ Int32Array, [ 'sint32', 'snorm32' ]],
  48582. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  48583. [ Float32Array, [ 'float32', ]],
  48584. ] );
  48585. const typedAttributeToVertexFormatPrefix = new Map( [
  48586. [ Float16BufferAttribute, [ 'float16', ]],
  48587. ] );
  48588. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  48589. [ Int32Array, 'sint32' ],
  48590. [ Int16Array, 'sint32' ], // patch for INT16
  48591. [ Uint32Array, 'uint32' ],
  48592. [ Uint16Array, 'uint32' ], // patch for UINT16
  48593. [ Float32Array, 'float32' ]
  48594. ] );
  48595. /**
  48596. * A WebGPU backend utility module for managing shader attributes.
  48597. *
  48598. * @private
  48599. */
  48600. class WebGPUAttributeUtils {
  48601. /**
  48602. * Constructs a new utility object.
  48603. *
  48604. * @param {WebGPUBackend} backend - The WebGPU backend.
  48605. */
  48606. constructor( backend ) {
  48607. /**
  48608. * A reference to the WebGPU backend.
  48609. *
  48610. * @type {WebGPUBackend}
  48611. */
  48612. this.backend = backend;
  48613. }
  48614. /**
  48615. * Creates the GPU buffer for the given buffer attribute.
  48616. *
  48617. * @param {BufferAttribute} attribute - The buffer attribute.
  48618. * @param {GPUBufferUsage} usage - A flag that indicates how the buffer may be used after its creation.
  48619. */
  48620. createAttribute( attribute, usage ) {
  48621. const bufferAttribute = this._getBufferAttribute( attribute );
  48622. const backend = this.backend;
  48623. const bufferData = backend.get( bufferAttribute );
  48624. let buffer = bufferData.buffer;
  48625. if ( buffer === undefined ) {
  48626. const device = backend.device;
  48627. let array = bufferAttribute.array;
  48628. // patch for INT16 and UINT16
  48629. if ( attribute.normalized === false ) {
  48630. if ( array.constructor === Int16Array || array.constructor === Int8Array ) {
  48631. array = new Int32Array( array );
  48632. } else if ( array.constructor === Uint16Array || array.constructor === Uint8Array ) {
  48633. array = new Uint32Array( array );
  48634. if ( usage & GPUBufferUsage.INDEX ) {
  48635. for ( let i = 0; i < array.length; i ++ ) {
  48636. if ( array[ i ] === 0xffff ) array[ i ] = 0xffffffff; // use correct primitive restart index
  48637. }
  48638. }
  48639. }
  48640. }
  48641. bufferAttribute.array = array;
  48642. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  48643. array = new array.constructor( bufferAttribute.count * 4 );
  48644. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  48645. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  48646. }
  48647. // Update BufferAttribute
  48648. bufferAttribute.itemSize = 4;
  48649. bufferAttribute.array = array;
  48650. bufferData._force3to4BytesAlignment = true;
  48651. }
  48652. // ensure 4 byte alignment
  48653. const byteLength = array.byteLength;
  48654. const size = byteLength + ( ( 4 - ( byteLength % 4 ) ) % 4 );
  48655. buffer = device.createBuffer( {
  48656. label: bufferAttribute.name,
  48657. size: size,
  48658. usage: usage,
  48659. mappedAtCreation: true
  48660. } );
  48661. new array.constructor( buffer.getMappedRange() ).set( array );
  48662. buffer.unmap();
  48663. bufferData.buffer = buffer;
  48664. }
  48665. }
  48666. /**
  48667. * Updates the GPU buffer of the given buffer attribute.
  48668. *
  48669. * @param {BufferAttribute} attribute - The buffer attribute.
  48670. */
  48671. updateAttribute( attribute ) {
  48672. const bufferAttribute = this._getBufferAttribute( attribute );
  48673. const backend = this.backend;
  48674. const device = backend.device;
  48675. const bufferData = backend.get( bufferAttribute );
  48676. const buffer = backend.get( bufferAttribute ).buffer;
  48677. let array = bufferAttribute.array;
  48678. // if storage buffer ensure 4 byte alignment
  48679. if ( bufferData._force3to4BytesAlignment === true ) {
  48680. array = new array.constructor( bufferAttribute.count * 4 );
  48681. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  48682. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  48683. }
  48684. bufferAttribute.array = array;
  48685. }
  48686. const isTypedArray = this._isTypedArray( array );
  48687. const updateRanges = bufferAttribute.updateRanges;
  48688. if ( updateRanges.length === 0 ) {
  48689. // Not using update ranges
  48690. device.queue.writeBuffer(
  48691. buffer,
  48692. 0,
  48693. array,
  48694. 0
  48695. );
  48696. } else {
  48697. const byteOffsetFactor = isTypedArray ? 1 : array.BYTES_PER_ELEMENT;
  48698. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  48699. const range = updateRanges[ i ];
  48700. let dataOffset, size;
  48701. if ( bufferData._force3to4BytesAlignment === true ) {
  48702. const vertexStart = Math.floor( range.start / 3 );
  48703. const vertexCount = Math.ceil( range.count / 3 );
  48704. dataOffset = vertexStart * 4 * byteOffsetFactor;
  48705. size = vertexCount * 4 * byteOffsetFactor;
  48706. } else {
  48707. dataOffset = range.start * byteOffsetFactor;
  48708. size = range.count * byteOffsetFactor;
  48709. }
  48710. const bufferOffset = dataOffset * ( isTypedArray ? array.BYTES_PER_ELEMENT : 1 ); // bufferOffset is always in bytes
  48711. device.queue.writeBuffer(
  48712. buffer,
  48713. bufferOffset,
  48714. array,
  48715. dataOffset,
  48716. size
  48717. );
  48718. }
  48719. bufferAttribute.clearUpdateRanges();
  48720. }
  48721. }
  48722. /**
  48723. * This method creates the vertex buffer layout data which are
  48724. * require when creating a render pipeline for the given render object.
  48725. *
  48726. * @param {RenderObject} renderObject - The render object.
  48727. * @return {Array<Object>} An array holding objects which describe the vertex buffer layout.
  48728. */
  48729. createShaderVertexBuffers( renderObject ) {
  48730. const attributes = renderObject.getAttributes();
  48731. const vertexBuffers = new Map();
  48732. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  48733. const geometryAttribute = attributes[ slot ];
  48734. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  48735. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  48736. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  48737. if ( vertexBufferLayout === undefined ) {
  48738. let arrayStride, stepMode;
  48739. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  48740. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  48741. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  48742. } else {
  48743. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  48744. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  48745. }
  48746. // patch for INT16 and UINT16
  48747. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  48748. arrayStride = 4;
  48749. }
  48750. vertexBufferLayout = {
  48751. arrayStride,
  48752. attributes: [],
  48753. stepMode
  48754. };
  48755. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  48756. }
  48757. const format = this._getVertexFormat( geometryAttribute );
  48758. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  48759. vertexBufferLayout.attributes.push( {
  48760. shaderLocation: slot,
  48761. offset,
  48762. format
  48763. } );
  48764. }
  48765. return Array.from( vertexBuffers.values() );
  48766. }
  48767. /**
  48768. * Destroys the GPU buffer of the given buffer attribute.
  48769. *
  48770. * @param {BufferAttribute} attribute - The buffer attribute.
  48771. */
  48772. destroyAttribute( attribute ) {
  48773. const backend = this.backend;
  48774. const data = backend.get( this._getBufferAttribute( attribute ) );
  48775. data.buffer.destroy();
  48776. backend.delete( attribute );
  48777. }
  48778. /**
  48779. * This method performs a readback operation by moving buffer data from
  48780. * a storage buffer attribute from the GPU to the CPU.
  48781. *
  48782. * @async
  48783. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  48784. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  48785. */
  48786. async getArrayBufferAsync( attribute ) {
  48787. const backend = this.backend;
  48788. const device = backend.device;
  48789. const data = backend.get( this._getBufferAttribute( attribute ) );
  48790. const bufferGPU = data.buffer;
  48791. const size = bufferGPU.size;
  48792. const readBufferGPU = device.createBuffer( {
  48793. label: `${ attribute.name }_readback`,
  48794. size,
  48795. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  48796. } );
  48797. const cmdEncoder = device.createCommandEncoder( {
  48798. label: `readback_encoder_${ attribute.name }`
  48799. } );
  48800. cmdEncoder.copyBufferToBuffer(
  48801. bufferGPU,
  48802. 0,
  48803. readBufferGPU,
  48804. 0,
  48805. size
  48806. );
  48807. const gpuCommands = cmdEncoder.finish();
  48808. device.queue.submit( [ gpuCommands ] );
  48809. await readBufferGPU.mapAsync( GPUMapMode.READ );
  48810. const arrayBuffer = readBufferGPU.getMappedRange();
  48811. const dstBuffer = new attribute.array.constructor( arrayBuffer.slice( 0 ) );
  48812. readBufferGPU.unmap();
  48813. return dstBuffer.buffer;
  48814. }
  48815. /**
  48816. * Returns the vertex format of the given buffer attribute.
  48817. *
  48818. * @private
  48819. * @param {BufferAttribute} geometryAttribute - The buffer attribute.
  48820. * @return {string|undefined} The vertex format (e.g. 'float32x3').
  48821. */
  48822. _getVertexFormat( geometryAttribute ) {
  48823. const { itemSize, normalized } = geometryAttribute;
  48824. const ArrayType = geometryAttribute.array.constructor;
  48825. const AttributeType = geometryAttribute.constructor;
  48826. let format;
  48827. if ( itemSize === 1 ) {
  48828. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  48829. } else {
  48830. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  48831. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  48832. if ( prefix ) {
  48833. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  48834. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  48835. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  48836. if ( paddedItemSize % 1 ) {
  48837. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  48838. }
  48839. format = `${prefix}x${paddedItemSize}`;
  48840. }
  48841. }
  48842. if ( ! format ) {
  48843. console.error( 'THREE.WebGPUAttributeUtils: Vertex format not supported yet.' );
  48844. }
  48845. return format;
  48846. }
  48847. /**
  48848. * Returns `true` if the given array is a typed array.
  48849. *
  48850. * @private
  48851. * @param {any} array - The array.
  48852. * @return {boolean} Whether the given array is a typed array or not.
  48853. */
  48854. _isTypedArray( array ) {
  48855. return ArrayBuffer.isView( array ) && ! ( array instanceof DataView );
  48856. }
  48857. /**
  48858. * Utility method for handling interleaved buffer attributes correctly.
  48859. * To process them, their `InterleavedBuffer` is returned.
  48860. *
  48861. * @private
  48862. * @param {BufferAttribute} attribute - The attribute.
  48863. * @return {BufferAttribute|InterleavedBuffer}
  48864. */
  48865. _getBufferAttribute( attribute ) {
  48866. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  48867. return attribute;
  48868. }
  48869. }
  48870. /**
  48871. * A WebGPU backend utility module for managing bindings.
  48872. *
  48873. * When reading the documentation it's helpful to keep in mind that
  48874. * all class definitions starting with 'GPU*' are modules from the
  48875. * WebGPU API. So for example `BindGroup` is a class from the engine
  48876. * whereas `GPUBindGroup` is a class from WebGPU.
  48877. *
  48878. * @private
  48879. */
  48880. class WebGPUBindingUtils {
  48881. /**
  48882. * Constructs a new utility object.
  48883. *
  48884. * @param {WebGPUBackend} backend - The WebGPU backend.
  48885. */
  48886. constructor( backend ) {
  48887. /**
  48888. * A reference to the WebGPU backend.
  48889. *
  48890. * @type {WebGPUBackend}
  48891. */
  48892. this.backend = backend;
  48893. /**
  48894. * A cache for managing bind group layouts.
  48895. *
  48896. * @type {WeakMap<Array<Binding>,GPUBindGroupLayout>}
  48897. */
  48898. this.bindGroupLayoutCache = new WeakMap();
  48899. }
  48900. /**
  48901. * Creates a GPU bind group layout for the given bind group.
  48902. *
  48903. * @param {BindGroup} bindGroup - The bind group.
  48904. * @return {GPUBindGroupLayout} The GPU bind group layout.
  48905. */
  48906. createBindingsLayout( bindGroup ) {
  48907. const backend = this.backend;
  48908. const device = backend.device;
  48909. const entries = [];
  48910. let index = 0;
  48911. for ( const binding of bindGroup.bindings ) {
  48912. const bindingGPU = {
  48913. binding: index ++,
  48914. visibility: binding.visibility
  48915. };
  48916. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  48917. const buffer = {}; // GPUBufferBindingLayout
  48918. if ( binding.isStorageBuffer ) {
  48919. if ( binding.visibility & 4 ) {
  48920. // compute
  48921. if ( binding.access === NodeAccess.READ_WRITE || binding.access === NodeAccess.WRITE_ONLY ) {
  48922. buffer.type = GPUBufferBindingType.Storage;
  48923. } else {
  48924. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  48925. }
  48926. } else {
  48927. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  48928. }
  48929. }
  48930. bindingGPU.buffer = buffer;
  48931. } else if ( binding.isSampler ) {
  48932. const sampler = {}; // GPUSamplerBindingLayout
  48933. if ( binding.texture.isDepthTexture ) {
  48934. if ( binding.texture.compareFunction !== null ) {
  48935. sampler.type = GPUSamplerBindingType.Comparison;
  48936. } else if ( backend.compatibilityMode ) {
  48937. sampler.type = GPUSamplerBindingType.NonFiltering;
  48938. }
  48939. }
  48940. bindingGPU.sampler = sampler;
  48941. } else if ( binding.isSampledTexture && binding.texture.isVideoTexture ) {
  48942. bindingGPU.externalTexture = {}; // GPUExternalTextureBindingLayout
  48943. } else if ( binding.isSampledTexture && binding.store ) {
  48944. const storageTexture = {}; // GPUStorageTextureBindingLayout
  48945. storageTexture.format = this.backend.get( binding.texture ).texture.format;
  48946. const access = binding.access;
  48947. if ( access === NodeAccess.READ_WRITE ) {
  48948. storageTexture.access = GPUStorageTextureAccess.ReadWrite;
  48949. } else if ( access === NodeAccess.WRITE_ONLY ) {
  48950. storageTexture.access = GPUStorageTextureAccess.WriteOnly;
  48951. } else {
  48952. storageTexture.access = GPUStorageTextureAccess.ReadOnly;
  48953. }
  48954. bindingGPU.storageTexture = storageTexture;
  48955. } else if ( binding.isSampledTexture ) {
  48956. const texture = {}; // GPUTextureBindingLayout
  48957. const { primarySamples } = backend.utils.getTextureSampleData( binding.texture );
  48958. if ( primarySamples > 1 ) {
  48959. texture.multisampled = true;
  48960. if ( ! binding.texture.isDepthTexture ) {
  48961. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  48962. }
  48963. }
  48964. if ( binding.texture.isDepthTexture ) {
  48965. if ( backend.compatibilityMode && binding.texture.compareFunction === null ) {
  48966. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  48967. } else {
  48968. texture.sampleType = GPUTextureSampleType.Depth;
  48969. }
  48970. } else if ( binding.texture.isDataTexture || binding.texture.isDataArrayTexture || binding.texture.isData3DTexture ) {
  48971. const type = binding.texture.type;
  48972. if ( type === IntType ) {
  48973. texture.sampleType = GPUTextureSampleType.SInt;
  48974. } else if ( type === UnsignedIntType ) {
  48975. texture.sampleType = GPUTextureSampleType.UInt;
  48976. } else if ( type === FloatType ) {
  48977. if ( this.backend.hasFeature( 'float32-filterable' ) ) {
  48978. texture.sampleType = GPUTextureSampleType.Float;
  48979. } else {
  48980. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  48981. }
  48982. }
  48983. }
  48984. if ( binding.isSampledCubeTexture ) {
  48985. texture.viewDimension = GPUTextureViewDimension.Cube;
  48986. } else if ( binding.texture.isArrayTexture || binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  48987. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  48988. } else if ( binding.isSampledTexture3D ) {
  48989. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  48990. }
  48991. bindingGPU.texture = texture;
  48992. } else {
  48993. console.error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  48994. }
  48995. entries.push( bindingGPU );
  48996. }
  48997. return device.createBindGroupLayout( { entries } );
  48998. }
  48999. /**
  49000. * Creates bindings from the given bind group definition.
  49001. *
  49002. * @param {BindGroup} bindGroup - The bind group.
  49003. * @param {Array<BindGroup>} bindings - Array of bind groups.
  49004. * @param {number} cacheIndex - The cache index.
  49005. * @param {number} version - The version.
  49006. */
  49007. createBindings( bindGroup, bindings, cacheIndex, version = 0 ) {
  49008. const { backend, bindGroupLayoutCache } = this;
  49009. const bindingsData = backend.get( bindGroup );
  49010. // setup (static) binding layout and (dynamic) binding group
  49011. let bindLayoutGPU = bindGroupLayoutCache.get( bindGroup.bindingsReference );
  49012. if ( bindLayoutGPU === undefined ) {
  49013. bindLayoutGPU = this.createBindingsLayout( bindGroup );
  49014. bindGroupLayoutCache.set( bindGroup.bindingsReference, bindLayoutGPU );
  49015. }
  49016. let bindGroupGPU;
  49017. if ( cacheIndex > 0 ) {
  49018. if ( bindingsData.groups === undefined ) {
  49019. bindingsData.groups = [];
  49020. bindingsData.versions = [];
  49021. }
  49022. if ( bindingsData.versions[ cacheIndex ] === version ) {
  49023. bindGroupGPU = bindingsData.groups[ cacheIndex ];
  49024. }
  49025. }
  49026. if ( bindGroupGPU === undefined ) {
  49027. bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  49028. if ( cacheIndex > 0 ) {
  49029. bindingsData.groups[ cacheIndex ] = bindGroupGPU;
  49030. bindingsData.versions[ cacheIndex ] = version;
  49031. }
  49032. }
  49033. bindingsData.group = bindGroupGPU;
  49034. bindingsData.layout = bindLayoutGPU;
  49035. }
  49036. /**
  49037. * Updates a buffer binding.
  49038. *
  49039. * @param {Buffer} binding - The buffer binding to update.
  49040. */
  49041. updateBinding( binding ) {
  49042. const backend = this.backend;
  49043. const device = backend.device;
  49044. const buffer = binding.buffer;
  49045. const bufferGPU = backend.get( binding ).buffer;
  49046. device.queue.writeBuffer( bufferGPU, 0, buffer, 0 );
  49047. }
  49048. /**
  49049. * Creates a GPU bind group for the camera index.
  49050. *
  49051. * @param {Uint32Array} data - The index data.
  49052. * @param {GPUBindGroupLayout} layout - The GPU bind group layout.
  49053. * @return {GPUBindGroup} The GPU bind group.
  49054. */
  49055. createBindGroupIndex( data, layout ) {
  49056. const backend = this.backend;
  49057. const device = backend.device;
  49058. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  49059. const index = data[ 0 ];
  49060. const buffer = device.createBuffer( {
  49061. label: 'bindingCameraIndex_' + index,
  49062. size: 16, // uint(4) * 4
  49063. usage: usage
  49064. } );
  49065. device.queue.writeBuffer( buffer, 0, data, 0 );
  49066. const entries = [ { binding: 0, resource: { buffer } } ];
  49067. return device.createBindGroup( {
  49068. label: 'bindGroupCameraIndex_' + index,
  49069. layout,
  49070. entries
  49071. } );
  49072. }
  49073. /**
  49074. * Creates a GPU bind group for the given bind group and GPU layout.
  49075. *
  49076. * @param {BindGroup} bindGroup - The bind group.
  49077. * @param {GPUBindGroupLayout} layoutGPU - The GPU bind group layout.
  49078. * @return {GPUBindGroup} The GPU bind group.
  49079. */
  49080. createBindGroup( bindGroup, layoutGPU ) {
  49081. const backend = this.backend;
  49082. const device = backend.device;
  49083. let bindingPoint = 0;
  49084. const entriesGPU = [];
  49085. for ( const binding of bindGroup.bindings ) {
  49086. if ( binding.isUniformBuffer ) {
  49087. const bindingData = backend.get( binding );
  49088. if ( bindingData.buffer === undefined ) {
  49089. const byteLength = binding.byteLength;
  49090. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  49091. const bufferGPU = device.createBuffer( {
  49092. label: 'bindingBuffer_' + binding.name,
  49093. size: byteLength,
  49094. usage: usage
  49095. } );
  49096. bindingData.buffer = bufferGPU;
  49097. }
  49098. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  49099. } else if ( binding.isStorageBuffer ) {
  49100. const bindingData = backend.get( binding );
  49101. if ( bindingData.buffer === undefined ) {
  49102. const attribute = binding.attribute;
  49103. //const usage = GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | /*GPUBufferUsage.COPY_SRC |*/ GPUBufferUsage.COPY_DST;
  49104. //backend.attributeUtils.createAttribute( attribute, usage ); // @TODO: Move it to universal renderer
  49105. bindingData.buffer = backend.get( attribute ).buffer;
  49106. }
  49107. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  49108. } else if ( binding.isSampler ) {
  49109. const textureGPU = backend.get( binding.texture );
  49110. entriesGPU.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  49111. } else if ( binding.isSampledTexture ) {
  49112. const textureData = backend.get( binding.texture );
  49113. let resourceGPU;
  49114. if ( textureData.externalTexture !== undefined ) {
  49115. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  49116. } else {
  49117. const mipLevelCount = binding.store ? 1 : textureData.texture.mipLevelCount;
  49118. const propertyName = `view-${ textureData.texture.width }-${ textureData.texture.height }-${ mipLevelCount }`;
  49119. resourceGPU = textureData[ propertyName ];
  49120. if ( resourceGPU === undefined ) {
  49121. const aspectGPU = GPUTextureAspect.All;
  49122. let dimensionViewGPU;
  49123. if ( binding.isSampledCubeTexture ) {
  49124. dimensionViewGPU = GPUTextureViewDimension.Cube;
  49125. } else if ( binding.isSampledTexture3D ) {
  49126. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  49127. } else if ( binding.texture.isArrayTexture || binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  49128. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  49129. } else {
  49130. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  49131. }
  49132. resourceGPU = textureData[ propertyName ] = textureData.texture.createView( { aspect: aspectGPU, dimension: dimensionViewGPU, mipLevelCount } );
  49133. }
  49134. }
  49135. entriesGPU.push( { binding: bindingPoint, resource: resourceGPU } );
  49136. }
  49137. bindingPoint ++;
  49138. }
  49139. return device.createBindGroup( {
  49140. label: 'bindGroup_' + bindGroup.name,
  49141. layout: layoutGPU,
  49142. entries: entriesGPU
  49143. } );
  49144. }
  49145. }
  49146. /**
  49147. * A WebGPU backend utility module for managing pipelines.
  49148. *
  49149. * @private
  49150. */
  49151. class WebGPUPipelineUtils {
  49152. /**
  49153. * Constructs a new utility object.
  49154. *
  49155. * @param {WebGPUBackend} backend - The WebGPU backend.
  49156. */
  49157. constructor( backend ) {
  49158. /**
  49159. * A reference to the WebGPU backend.
  49160. *
  49161. * @type {WebGPUBackend}
  49162. */
  49163. this.backend = backend;
  49164. /**
  49165. * A Weak Map that tracks the active pipeline for render or compute passes.
  49166. *
  49167. * @private
  49168. * @type {WeakMap<(GPURenderPassEncoder|GPUComputePassEncoder),(GPURenderPipeline|GPUComputePipeline)>}
  49169. */
  49170. this._activePipelines = new WeakMap();
  49171. }
  49172. /**
  49173. * Sets the given pipeline for the given pass. The method makes sure to only set the
  49174. * pipeline when necessary.
  49175. *
  49176. * @param {(GPURenderPassEncoder|GPUComputePassEncoder)} pass - The pass encoder.
  49177. * @param {(GPURenderPipeline|GPUComputePipeline)} pipeline - The pipeline.
  49178. */
  49179. setPipeline( pass, pipeline ) {
  49180. const currentPipeline = this._activePipelines.get( pass );
  49181. if ( currentPipeline !== pipeline ) {
  49182. pass.setPipeline( pipeline );
  49183. this._activePipelines.set( pass, pipeline );
  49184. }
  49185. }
  49186. /**
  49187. * Returns the sample count derived from the given render context.
  49188. *
  49189. * @private
  49190. * @param {RenderContext} renderContext - The render context.
  49191. * @return {number} The sample count.
  49192. */
  49193. _getSampleCount( renderContext ) {
  49194. return this.backend.utils.getSampleCountRenderContext( renderContext );
  49195. }
  49196. /**
  49197. * Creates a render pipeline for the given render object.
  49198. *
  49199. * @param {RenderObject} renderObject - The render object.
  49200. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  49201. */
  49202. createRenderPipeline( renderObject, promises ) {
  49203. const { object, material, geometry, pipeline } = renderObject;
  49204. const { vertexProgram, fragmentProgram } = pipeline;
  49205. const backend = this.backend;
  49206. const device = backend.device;
  49207. const utils = backend.utils;
  49208. const pipelineData = backend.get( pipeline );
  49209. // bind group layouts
  49210. const bindGroupLayouts = [];
  49211. for ( const bindGroup of renderObject.getBindings() ) {
  49212. const bindingsData = backend.get( bindGroup );
  49213. bindGroupLayouts.push( bindingsData.layout );
  49214. }
  49215. // vertex buffers
  49216. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  49217. // blending
  49218. let blending;
  49219. if ( material.blending !== NoBlending && ( material.blending !== NormalBlending || material.transparent !== false ) ) {
  49220. blending = this._getBlending( material );
  49221. }
  49222. // stencil
  49223. let stencilFront = {};
  49224. if ( material.stencilWrite === true ) {
  49225. stencilFront = {
  49226. compare: this._getStencilCompare( material ),
  49227. failOp: this._getStencilOperation( material.stencilFail ),
  49228. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  49229. passOp: this._getStencilOperation( material.stencilZPass )
  49230. };
  49231. }
  49232. const colorWriteMask = this._getColorWriteMask( material );
  49233. const targets = [];
  49234. if ( renderObject.context.textures !== null ) {
  49235. const textures = renderObject.context.textures;
  49236. for ( let i = 0; i < textures.length; i ++ ) {
  49237. const colorFormat = utils.getTextureFormatGPU( textures[ i ] );
  49238. targets.push( {
  49239. format: colorFormat,
  49240. blend: blending,
  49241. writeMask: colorWriteMask
  49242. } );
  49243. }
  49244. } else {
  49245. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  49246. targets.push( {
  49247. format: colorFormat,
  49248. blend: blending,
  49249. writeMask: colorWriteMask
  49250. } );
  49251. }
  49252. const vertexModule = backend.get( vertexProgram ).module;
  49253. const fragmentModule = backend.get( fragmentProgram ).module;
  49254. const primitiveState = this._getPrimitiveState( object, geometry, material );
  49255. const depthCompare = this._getDepthCompare( material );
  49256. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  49257. const sampleCount = this._getSampleCount( renderObject.context );
  49258. const pipelineDescriptor = {
  49259. label: `renderPipeline_${ material.name || material.type }_${ material.id }`,
  49260. vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ),
  49261. fragment: Object.assign( {}, fragmentModule, { targets } ),
  49262. primitive: primitiveState,
  49263. multisample: {
  49264. count: sampleCount,
  49265. alphaToCoverageEnabled: material.alphaToCoverage && sampleCount > 1
  49266. },
  49267. layout: device.createPipelineLayout( {
  49268. bindGroupLayouts
  49269. } )
  49270. };
  49271. const depthStencil = {};
  49272. const renderDepth = renderObject.context.depth;
  49273. const renderStencil = renderObject.context.stencil;
  49274. if ( renderDepth === true || renderStencil === true ) {
  49275. if ( renderDepth === true ) {
  49276. depthStencil.format = depthStencilFormat;
  49277. depthStencil.depthWriteEnabled = material.depthWrite;
  49278. depthStencil.depthCompare = depthCompare;
  49279. }
  49280. if ( renderStencil === true ) {
  49281. depthStencil.stencilFront = stencilFront;
  49282. depthStencil.stencilBack = {}; // three.js does not provide an API to configure the back function (gl.stencilFuncSeparate() was never used)
  49283. depthStencil.stencilReadMask = material.stencilFuncMask;
  49284. depthStencil.stencilWriteMask = material.stencilWriteMask;
  49285. }
  49286. if ( material.polygonOffset === true ) {
  49287. depthStencil.depthBias = material.polygonOffsetUnits;
  49288. depthStencil.depthBiasSlopeScale = material.polygonOffsetFactor;
  49289. depthStencil.depthBiasClamp = 0; // three.js does not provide an API to configure this value
  49290. }
  49291. pipelineDescriptor.depthStencil = depthStencil;
  49292. }
  49293. if ( promises === null ) {
  49294. pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor );
  49295. } else {
  49296. const p = new Promise( ( resolve /*, reject*/ ) => {
  49297. device.createRenderPipelineAsync( pipelineDescriptor ).then( pipeline => {
  49298. pipelineData.pipeline = pipeline;
  49299. resolve();
  49300. } );
  49301. } );
  49302. promises.push( p );
  49303. }
  49304. }
  49305. /**
  49306. * Creates GPU render bundle encoder for the given render context.
  49307. *
  49308. * @param {RenderContext} renderContext - The render context.
  49309. * @param {?string} [label='renderBundleEncoder'] - The label.
  49310. * @return {GPURenderBundleEncoder} The GPU render bundle encoder.
  49311. */
  49312. createBundleEncoder( renderContext, label = 'renderBundleEncoder' ) {
  49313. const backend = this.backend;
  49314. const { utils, device } = backend;
  49315. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  49316. const colorFormat = utils.getCurrentColorFormat( renderContext );
  49317. const sampleCount = this._getSampleCount( renderContext );
  49318. const descriptor = {
  49319. label: label,
  49320. colorFormats: [ colorFormat ],
  49321. depthStencilFormat,
  49322. sampleCount
  49323. };
  49324. return device.createRenderBundleEncoder( descriptor );
  49325. }
  49326. /**
  49327. * Creates a compute pipeline for the given compute node.
  49328. *
  49329. * @param {ComputePipeline} pipeline - The compute pipeline.
  49330. * @param {Array<BindGroup>} bindings - The bindings.
  49331. */
  49332. createComputePipeline( pipeline, bindings ) {
  49333. const backend = this.backend;
  49334. const device = backend.device;
  49335. const computeProgram = backend.get( pipeline.computeProgram ).module;
  49336. const pipelineGPU = backend.get( pipeline );
  49337. // bind group layouts
  49338. const bindGroupLayouts = [];
  49339. for ( const bindingsGroup of bindings ) {
  49340. const bindingsData = backend.get( bindingsGroup );
  49341. bindGroupLayouts.push( bindingsData.layout );
  49342. }
  49343. pipelineGPU.pipeline = device.createComputePipeline( {
  49344. compute: computeProgram,
  49345. layout: device.createPipelineLayout( {
  49346. bindGroupLayouts
  49347. } )
  49348. } );
  49349. }
  49350. /**
  49351. * Returns the blending state as a descriptor object required
  49352. * for the pipeline creation.
  49353. *
  49354. * @private
  49355. * @param {Material} material - The material.
  49356. * @return {Object} The blending state.
  49357. */
  49358. _getBlending( material ) {
  49359. let color, alpha;
  49360. const blending = material.blending;
  49361. const blendSrc = material.blendSrc;
  49362. const blendDst = material.blendDst;
  49363. const blendEquation = material.blendEquation;
  49364. if ( blending === CustomBlending ) {
  49365. const blendSrcAlpha = material.blendSrcAlpha !== null ? material.blendSrcAlpha : blendSrc;
  49366. const blendDstAlpha = material.blendDstAlpha !== null ? material.blendDstAlpha : blendDst;
  49367. const blendEquationAlpha = material.blendEquationAlpha !== null ? material.blendEquationAlpha : blendEquation;
  49368. color = {
  49369. srcFactor: this._getBlendFactor( blendSrc ),
  49370. dstFactor: this._getBlendFactor( blendDst ),
  49371. operation: this._getBlendOperation( blendEquation )
  49372. };
  49373. alpha = {
  49374. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  49375. dstFactor: this._getBlendFactor( blendDstAlpha ),
  49376. operation: this._getBlendOperation( blendEquationAlpha )
  49377. };
  49378. } else {
  49379. const premultipliedAlpha = material.premultipliedAlpha;
  49380. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  49381. color = {
  49382. srcFactor: srcRGB,
  49383. dstFactor: dstRGB,
  49384. operation: GPUBlendOperation.Add
  49385. };
  49386. alpha = {
  49387. srcFactor: srcAlpha,
  49388. dstFactor: dstAlpha,
  49389. operation: GPUBlendOperation.Add
  49390. };
  49391. };
  49392. if ( premultipliedAlpha ) {
  49393. switch ( blending ) {
  49394. case NormalBlending:
  49395. setBlend( GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  49396. break;
  49397. case AdditiveBlending:
  49398. setBlend( GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  49399. break;
  49400. case SubtractiveBlending:
  49401. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  49402. break;
  49403. case MultiplyBlending:
  49404. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.SrcAlpha );
  49405. break;
  49406. }
  49407. } else {
  49408. switch ( blending ) {
  49409. case NormalBlending:
  49410. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  49411. break;
  49412. case AdditiveBlending:
  49413. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.SrcAlpha, GPUBlendFactor.One );
  49414. break;
  49415. case SubtractiveBlending:
  49416. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  49417. break;
  49418. case MultiplyBlending:
  49419. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.Src );
  49420. break;
  49421. }
  49422. }
  49423. }
  49424. if ( color !== undefined && alpha !== undefined ) {
  49425. return { color, alpha };
  49426. } else {
  49427. console.error( 'THREE.WebGPURenderer: Invalid blending: ', blending );
  49428. }
  49429. }
  49430. /**
  49431. * Returns the GPU blend factor which is required for the pipeline creation.
  49432. *
  49433. * @private
  49434. * @param {number} blend - The blend factor as a three.js constant.
  49435. * @return {string} The GPU blend factor.
  49436. */
  49437. _getBlendFactor( blend ) {
  49438. let blendFactor;
  49439. switch ( blend ) {
  49440. case ZeroFactor:
  49441. blendFactor = GPUBlendFactor.Zero;
  49442. break;
  49443. case OneFactor:
  49444. blendFactor = GPUBlendFactor.One;
  49445. break;
  49446. case SrcColorFactor:
  49447. blendFactor = GPUBlendFactor.Src;
  49448. break;
  49449. case OneMinusSrcColorFactor:
  49450. blendFactor = GPUBlendFactor.OneMinusSrc;
  49451. break;
  49452. case SrcAlphaFactor:
  49453. blendFactor = GPUBlendFactor.SrcAlpha;
  49454. break;
  49455. case OneMinusSrcAlphaFactor:
  49456. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  49457. break;
  49458. case DstColorFactor:
  49459. blendFactor = GPUBlendFactor.Dst;
  49460. break;
  49461. case OneMinusDstColorFactor:
  49462. blendFactor = GPUBlendFactor.OneMinusDst;
  49463. break;
  49464. case DstAlphaFactor:
  49465. blendFactor = GPUBlendFactor.DstAlpha;
  49466. break;
  49467. case OneMinusDstAlphaFactor:
  49468. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  49469. break;
  49470. case SrcAlphaSaturateFactor:
  49471. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  49472. break;
  49473. case BlendColorFactor:
  49474. blendFactor = GPUBlendFactor.Constant;
  49475. break;
  49476. case OneMinusBlendColorFactor:
  49477. blendFactor = GPUBlendFactor.OneMinusConstant;
  49478. break;
  49479. default:
  49480. console.error( 'THREE.WebGPURenderer: Blend factor not supported.', blend );
  49481. }
  49482. return blendFactor;
  49483. }
  49484. /**
  49485. * Returns the GPU stencil compare function which is required for the pipeline creation.
  49486. *
  49487. * @private
  49488. * @param {Material} material - The material.
  49489. * @return {string} The GPU stencil compare function.
  49490. */
  49491. _getStencilCompare( material ) {
  49492. let stencilCompare;
  49493. const stencilFunc = material.stencilFunc;
  49494. switch ( stencilFunc ) {
  49495. case NeverStencilFunc:
  49496. stencilCompare = GPUCompareFunction.Never;
  49497. break;
  49498. case AlwaysStencilFunc:
  49499. stencilCompare = GPUCompareFunction.Always;
  49500. break;
  49501. case LessStencilFunc:
  49502. stencilCompare = GPUCompareFunction.Less;
  49503. break;
  49504. case LessEqualStencilFunc:
  49505. stencilCompare = GPUCompareFunction.LessEqual;
  49506. break;
  49507. case EqualStencilFunc:
  49508. stencilCompare = GPUCompareFunction.Equal;
  49509. break;
  49510. case GreaterEqualStencilFunc:
  49511. stencilCompare = GPUCompareFunction.GreaterEqual;
  49512. break;
  49513. case GreaterStencilFunc:
  49514. stencilCompare = GPUCompareFunction.Greater;
  49515. break;
  49516. case NotEqualStencilFunc:
  49517. stencilCompare = GPUCompareFunction.NotEqual;
  49518. break;
  49519. default:
  49520. console.error( 'THREE.WebGPURenderer: Invalid stencil function.', stencilFunc );
  49521. }
  49522. return stencilCompare;
  49523. }
  49524. /**
  49525. * Returns the GPU stencil operation which is required for the pipeline creation.
  49526. *
  49527. * @private
  49528. * @param {number} op - A three.js constant defining the stencil operation.
  49529. * @return {string} The GPU stencil operation.
  49530. */
  49531. _getStencilOperation( op ) {
  49532. let stencilOperation;
  49533. switch ( op ) {
  49534. case KeepStencilOp:
  49535. stencilOperation = GPUStencilOperation.Keep;
  49536. break;
  49537. case ZeroStencilOp:
  49538. stencilOperation = GPUStencilOperation.Zero;
  49539. break;
  49540. case ReplaceStencilOp:
  49541. stencilOperation = GPUStencilOperation.Replace;
  49542. break;
  49543. case InvertStencilOp:
  49544. stencilOperation = GPUStencilOperation.Invert;
  49545. break;
  49546. case IncrementStencilOp:
  49547. stencilOperation = GPUStencilOperation.IncrementClamp;
  49548. break;
  49549. case DecrementStencilOp:
  49550. stencilOperation = GPUStencilOperation.DecrementClamp;
  49551. break;
  49552. case IncrementWrapStencilOp:
  49553. stencilOperation = GPUStencilOperation.IncrementWrap;
  49554. break;
  49555. case DecrementWrapStencilOp:
  49556. stencilOperation = GPUStencilOperation.DecrementWrap;
  49557. break;
  49558. default:
  49559. console.error( 'THREE.WebGPURenderer: Invalid stencil operation.', stencilOperation );
  49560. }
  49561. return stencilOperation;
  49562. }
  49563. /**
  49564. * Returns the GPU blend operation which is required for the pipeline creation.
  49565. *
  49566. * @private
  49567. * @param {number} blendEquation - A three.js constant defining the blend equation.
  49568. * @return {string} The GPU blend operation.
  49569. */
  49570. _getBlendOperation( blendEquation ) {
  49571. let blendOperation;
  49572. switch ( blendEquation ) {
  49573. case AddEquation:
  49574. blendOperation = GPUBlendOperation.Add;
  49575. break;
  49576. case SubtractEquation:
  49577. blendOperation = GPUBlendOperation.Subtract;
  49578. break;
  49579. case ReverseSubtractEquation:
  49580. blendOperation = GPUBlendOperation.ReverseSubtract;
  49581. break;
  49582. case MinEquation:
  49583. blendOperation = GPUBlendOperation.Min;
  49584. break;
  49585. case MaxEquation:
  49586. blendOperation = GPUBlendOperation.Max;
  49587. break;
  49588. default:
  49589. console.error( 'THREE.WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  49590. }
  49591. return blendOperation;
  49592. }
  49593. /**
  49594. * Returns the primitive state as a descriptor object required
  49595. * for the pipeline creation.
  49596. *
  49597. * @private
  49598. * @param {Object3D} object - The 3D object.
  49599. * @param {BufferGeometry} geometry - The geometry.
  49600. * @param {Material} material - The material.
  49601. * @return {Object} The primitive state.
  49602. */
  49603. _getPrimitiveState( object, geometry, material ) {
  49604. const descriptor = {};
  49605. const utils = this.backend.utils;
  49606. descriptor.topology = utils.getPrimitiveTopology( object, material );
  49607. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  49608. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  49609. }
  49610. switch ( material.side ) {
  49611. case FrontSide:
  49612. descriptor.frontFace = GPUFrontFace.CCW;
  49613. descriptor.cullMode = GPUCullMode.Back;
  49614. break;
  49615. case BackSide:
  49616. descriptor.frontFace = GPUFrontFace.CCW;
  49617. descriptor.cullMode = GPUCullMode.Front;
  49618. break;
  49619. case DoubleSide:
  49620. descriptor.frontFace = GPUFrontFace.CCW;
  49621. descriptor.cullMode = GPUCullMode.None;
  49622. break;
  49623. default:
  49624. console.error( 'THREE.WebGPUPipelineUtils: Unknown material.side value.', material.side );
  49625. break;
  49626. }
  49627. return descriptor;
  49628. }
  49629. /**
  49630. * Returns the GPU color write mask which is required for the pipeline creation.
  49631. *
  49632. * @private
  49633. * @param {Material} material - The material.
  49634. * @return {string} The GPU color write mask.
  49635. */
  49636. _getColorWriteMask( material ) {
  49637. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  49638. }
  49639. /**
  49640. * Returns the GPU depth compare function which is required for the pipeline creation.
  49641. *
  49642. * @private
  49643. * @param {Material} material - The material.
  49644. * @return {string} The GPU depth compare function.
  49645. */
  49646. _getDepthCompare( material ) {
  49647. let depthCompare;
  49648. if ( material.depthTest === false ) {
  49649. depthCompare = GPUCompareFunction.Always;
  49650. } else {
  49651. const depthFunc = material.depthFunc;
  49652. switch ( depthFunc ) {
  49653. case NeverDepth:
  49654. depthCompare = GPUCompareFunction.Never;
  49655. break;
  49656. case AlwaysDepth:
  49657. depthCompare = GPUCompareFunction.Always;
  49658. break;
  49659. case LessDepth:
  49660. depthCompare = GPUCompareFunction.Less;
  49661. break;
  49662. case LessEqualDepth:
  49663. depthCompare = GPUCompareFunction.LessEqual;
  49664. break;
  49665. case EqualDepth:
  49666. depthCompare = GPUCompareFunction.Equal;
  49667. break;
  49668. case GreaterEqualDepth:
  49669. depthCompare = GPUCompareFunction.GreaterEqual;
  49670. break;
  49671. case GreaterDepth:
  49672. depthCompare = GPUCompareFunction.Greater;
  49673. break;
  49674. case NotEqualDepth:
  49675. depthCompare = GPUCompareFunction.NotEqual;
  49676. break;
  49677. default:
  49678. console.error( 'THREE.WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  49679. }
  49680. }
  49681. return depthCompare;
  49682. }
  49683. }
  49684. /**
  49685. * Manages a pool of WebGPU timestamp queries for performance measurement.
  49686. * Extends the base TimestampQueryPool to provide WebGPU-specific implementation.
  49687. *
  49688. * @augments TimestampQueryPool
  49689. */
  49690. class WebGPUTimestampQueryPool extends TimestampQueryPool {
  49691. /**
  49692. * Creates a new WebGPU timestamp query pool.
  49693. *
  49694. * @param {GPUDevice} device - The WebGPU device to create queries on.
  49695. * @param {string} type - The type identifier for this query pool.
  49696. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  49697. */
  49698. constructor( device, type, maxQueries = 2048 ) {
  49699. super( maxQueries );
  49700. this.device = device;
  49701. this.type = type;
  49702. this.querySet = this.device.createQuerySet( {
  49703. type: 'timestamp',
  49704. count: this.maxQueries,
  49705. label: `queryset_global_timestamp_${type}`
  49706. } );
  49707. const bufferSize = this.maxQueries * 8;
  49708. this.resolveBuffer = this.device.createBuffer( {
  49709. label: `buffer_timestamp_resolve_${type}`,
  49710. size: bufferSize,
  49711. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  49712. } );
  49713. this.resultBuffer = this.device.createBuffer( {
  49714. label: `buffer_timestamp_result_${type}`,
  49715. size: bufferSize,
  49716. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  49717. } );
  49718. }
  49719. /**
  49720. * Allocates a pair of queries for a given render context.
  49721. *
  49722. * @param {Object} renderContext - The render context to allocate queries for.
  49723. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  49724. */
  49725. allocateQueriesForContext( renderContext ) {
  49726. if ( ! this.trackTimestamp || this.isDisposed ) return null;
  49727. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  49728. 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() } ).` );
  49729. return null;
  49730. }
  49731. const baseOffset = this.currentQueryIndex;
  49732. this.currentQueryIndex += 2;
  49733. this.queryOffsets.set( renderContext.id, baseOffset );
  49734. return baseOffset;
  49735. }
  49736. /**
  49737. * Asynchronously resolves all pending queries and returns the total duration.
  49738. * If there's already a pending resolve operation, returns that promise instead.
  49739. *
  49740. * @async
  49741. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  49742. */
  49743. async resolveQueriesAsync() {
  49744. if ( ! this.trackTimestamp || this.currentQueryIndex === 0 || this.isDisposed ) {
  49745. return this.lastValue;
  49746. }
  49747. if ( this.pendingResolve ) {
  49748. return this.pendingResolve;
  49749. }
  49750. this.pendingResolve = this._resolveQueries();
  49751. try {
  49752. const result = await this.pendingResolve;
  49753. return result;
  49754. } finally {
  49755. this.pendingResolve = null;
  49756. }
  49757. }
  49758. /**
  49759. * Internal method to resolve queries and calculate total duration.
  49760. *
  49761. * @async
  49762. * @private
  49763. * @returns {Promise<number>} The total duration in milliseconds.
  49764. */
  49765. async _resolveQueries() {
  49766. if ( this.isDisposed ) {
  49767. return this.lastValue;
  49768. }
  49769. try {
  49770. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  49771. return this.lastValue;
  49772. }
  49773. const currentOffsets = new Map( this.queryOffsets );
  49774. const queryCount = this.currentQueryIndex;
  49775. const bytesUsed = queryCount * 8;
  49776. // Reset state before GPU work
  49777. this.currentQueryIndex = 0;
  49778. this.queryOffsets.clear();
  49779. const commandEncoder = this.device.createCommandEncoder();
  49780. commandEncoder.resolveQuerySet(
  49781. this.querySet,
  49782. 0,
  49783. queryCount,
  49784. this.resolveBuffer,
  49785. 0
  49786. );
  49787. commandEncoder.copyBufferToBuffer(
  49788. this.resolveBuffer,
  49789. 0,
  49790. this.resultBuffer,
  49791. 0,
  49792. bytesUsed
  49793. );
  49794. const commandBuffer = commandEncoder.finish();
  49795. this.device.queue.submit( [ commandBuffer ] );
  49796. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  49797. return this.lastValue;
  49798. }
  49799. // Create and track the mapping operation
  49800. await this.resultBuffer.mapAsync( GPUMapMode.READ, 0, bytesUsed );
  49801. if ( this.isDisposed ) {
  49802. if ( this.resultBuffer.mapState === 'mapped' ) {
  49803. this.resultBuffer.unmap();
  49804. }
  49805. return this.lastValue;
  49806. }
  49807. const times = new BigUint64Array( this.resultBuffer.getMappedRange( 0, bytesUsed ) );
  49808. let totalDuration = 0;
  49809. for ( const [ , baseOffset ] of currentOffsets ) {
  49810. const startTime = times[ baseOffset ];
  49811. const endTime = times[ baseOffset + 1 ];
  49812. const duration = Number( endTime - startTime ) / 1e6;
  49813. totalDuration += duration;
  49814. }
  49815. this.resultBuffer.unmap();
  49816. this.lastValue = totalDuration;
  49817. return totalDuration;
  49818. } catch ( error ) {
  49819. console.error( 'Error resolving queries:', error );
  49820. if ( this.resultBuffer.mapState === 'mapped' ) {
  49821. this.resultBuffer.unmap();
  49822. }
  49823. return this.lastValue;
  49824. }
  49825. }
  49826. /**
  49827. * Dispose of the query pool.
  49828. *
  49829. * @async
  49830. * @returns {Promise} A Promise that resolves when the dispose has been executed.
  49831. */
  49832. async dispose() {
  49833. if ( this.isDisposed ) {
  49834. return;
  49835. }
  49836. this.isDisposed = true;
  49837. // Wait for pending resolve operation
  49838. if ( this.pendingResolve ) {
  49839. try {
  49840. await this.pendingResolve;
  49841. } catch ( error ) {
  49842. console.error( 'Error waiting for pending resolve:', error );
  49843. }
  49844. }
  49845. // Ensure buffer is unmapped before destroying
  49846. if ( this.resultBuffer && this.resultBuffer.mapState === 'mapped' ) {
  49847. try {
  49848. this.resultBuffer.unmap();
  49849. } catch ( error ) {
  49850. console.error( 'Error unmapping buffer:', error );
  49851. }
  49852. }
  49853. // Destroy resources
  49854. if ( this.querySet ) {
  49855. this.querySet.destroy();
  49856. this.querySet = null;
  49857. }
  49858. if ( this.resolveBuffer ) {
  49859. this.resolveBuffer.destroy();
  49860. this.resolveBuffer = null;
  49861. }
  49862. if ( this.resultBuffer ) {
  49863. this.resultBuffer.destroy();
  49864. this.resultBuffer = null;
  49865. }
  49866. this.queryOffsets.clear();
  49867. this.pendingResolve = null;
  49868. }
  49869. }
  49870. /*// debugger tools
  49871. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  49872. //*/
  49873. /**
  49874. * A backend implementation targeting WebGPU.
  49875. *
  49876. * @private
  49877. * @augments Backend
  49878. */
  49879. class WebGPUBackend extends Backend {
  49880. /**
  49881. * WebGPUBackend options.
  49882. *
  49883. * @typedef {Object} WebGPUBackend~Options
  49884. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  49885. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  49886. * @property {boolean} [compatibilityMode=false] - Whether the backend should be in compatibility mode or not.
  49887. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  49888. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  49889. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  49890. * @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.
  49891. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  49892. * @property {boolean} [trackTimestamp=false] - Whether to track timestamps with a Timestamp Query API or not.
  49893. * @property {string} [powerPreference=undefined] - The power preference.
  49894. * @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.
  49895. * @property {GPUDevice} [device=undefined] - If there is an existing GPU device on app level, it can be passed to the renderer as a parameter.
  49896. * @property {number} [outputType=undefined] - Texture type for output to canvas. By default, device's preferred format is used; other formats may incur overhead.
  49897. */
  49898. /**
  49899. * Constructs a new WebGPU backend.
  49900. *
  49901. * @param {WebGPUBackend~Options} [parameters] - The configuration parameter.
  49902. */
  49903. constructor( parameters = {} ) {
  49904. super( parameters );
  49905. /**
  49906. * This flag can be used for type testing.
  49907. *
  49908. * @type {boolean}
  49909. * @readonly
  49910. * @default true
  49911. */
  49912. this.isWebGPUBackend = true;
  49913. // some parameters require default values other than "undefined"
  49914. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  49915. this.parameters.compatibilityMode = ( parameters.compatibilityMode === undefined ) ? false : parameters.compatibilityMode;
  49916. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  49917. /**
  49918. * Indicates whether the backend is in compatibility mode or not.
  49919. * @type {boolean}
  49920. * @default false
  49921. */
  49922. this.compatibilityMode = this.parameters.compatibilityMode;
  49923. /**
  49924. * A reference to the device.
  49925. *
  49926. * @type {?GPUDevice}
  49927. * @default null
  49928. */
  49929. this.device = null;
  49930. /**
  49931. * A reference to the context.
  49932. *
  49933. * @type {?GPUCanvasContext}
  49934. * @default null
  49935. */
  49936. this.context = null;
  49937. /**
  49938. * A reference to the color attachment of the default framebuffer.
  49939. *
  49940. * @type {?GPUTexture}
  49941. * @default null
  49942. */
  49943. this.colorBuffer = null;
  49944. /**
  49945. * A reference to the default render pass descriptor.
  49946. *
  49947. * @type {?Object}
  49948. * @default null
  49949. */
  49950. this.defaultRenderPassdescriptor = null;
  49951. /**
  49952. * A reference to a backend module holding common utility functions.
  49953. *
  49954. * @type {WebGPUUtils}
  49955. */
  49956. this.utils = new WebGPUUtils( this );
  49957. /**
  49958. * A reference to a backend module holding shader attribute-related
  49959. * utility functions.
  49960. *
  49961. * @type {WebGPUAttributeUtils}
  49962. */
  49963. this.attributeUtils = new WebGPUAttributeUtils( this );
  49964. /**
  49965. * A reference to a backend module holding shader binding-related
  49966. * utility functions.
  49967. *
  49968. * @type {WebGPUBindingUtils}
  49969. */
  49970. this.bindingUtils = new WebGPUBindingUtils( this );
  49971. /**
  49972. * A reference to a backend module holding shader pipeline-related
  49973. * utility functions.
  49974. *
  49975. * @type {WebGPUPipelineUtils}
  49976. */
  49977. this.pipelineUtils = new WebGPUPipelineUtils( this );
  49978. /**
  49979. * A reference to a backend module holding shader texture-related
  49980. * utility functions.
  49981. *
  49982. * @type {WebGPUTextureUtils}
  49983. */
  49984. this.textureUtils = new WebGPUTextureUtils( this );
  49985. /**
  49986. * A map that manages the resolve buffers for occlusion queries.
  49987. *
  49988. * @type {Map<number,GPUBuffer>}
  49989. */
  49990. this.occludedResolveCache = new Map();
  49991. }
  49992. /**
  49993. * Initializes the backend so it is ready for usage.
  49994. *
  49995. * @async
  49996. * @param {Renderer} renderer - The renderer.
  49997. * @return {Promise} A Promise that resolves when the backend has been initialized.
  49998. */
  49999. async init( renderer ) {
  50000. await super.init( renderer );
  50001. //
  50002. const parameters = this.parameters;
  50003. // create the device if it is not passed with parameters
  50004. let device;
  50005. if ( parameters.device === undefined ) {
  50006. const adapterOptions = {
  50007. powerPreference: parameters.powerPreference,
  50008. featureLevel: parameters.compatibilityMode ? 'compatibility' : undefined
  50009. };
  50010. const adapter = ( typeof navigator !== 'undefined' ) ? await navigator.gpu.requestAdapter( adapterOptions ) : null;
  50011. if ( adapter === null ) {
  50012. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  50013. }
  50014. // feature support
  50015. const features = Object.values( GPUFeatureName );
  50016. const supportedFeatures = [];
  50017. for ( const name of features ) {
  50018. if ( adapter.features.has( name ) ) {
  50019. supportedFeatures.push( name );
  50020. }
  50021. }
  50022. const deviceDescriptor = {
  50023. requiredFeatures: supportedFeatures,
  50024. requiredLimits: parameters.requiredLimits
  50025. };
  50026. device = await adapter.requestDevice( deviceDescriptor );
  50027. } else {
  50028. device = parameters.device;
  50029. }
  50030. device.lost.then( ( info ) => {
  50031. const deviceLossInfo = {
  50032. api: 'WebGPU',
  50033. message: info.message || 'Unknown reason',
  50034. reason: info.reason || null,
  50035. originalEvent: info
  50036. };
  50037. renderer.onDeviceLost( deviceLossInfo );
  50038. } );
  50039. const context = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgpu' );
  50040. this.device = device;
  50041. this.context = context;
  50042. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  50043. this.trackTimestamp = this.trackTimestamp && this.hasFeature( GPUFeatureName.TimestampQuery );
  50044. this.context.configure( {
  50045. device: this.device,
  50046. format: this.utils.getPreferredCanvasFormat(),
  50047. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  50048. alphaMode: alphaMode
  50049. } );
  50050. this.updateSize();
  50051. }
  50052. /**
  50053. * The coordinate system of the backend.
  50054. *
  50055. * @type {number}
  50056. * @readonly
  50057. */
  50058. get coordinateSystem() {
  50059. return WebGPUCoordinateSystem;
  50060. }
  50061. /**
  50062. * This method performs a readback operation by moving buffer data from
  50063. * a storage buffer attribute from the GPU to the CPU.
  50064. *
  50065. * @async
  50066. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  50067. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  50068. */
  50069. async getArrayBufferAsync( attribute ) {
  50070. return await this.attributeUtils.getArrayBufferAsync( attribute );
  50071. }
  50072. /**
  50073. * Returns the backend's rendering context.
  50074. *
  50075. * @return {GPUCanvasContext} The rendering context.
  50076. */
  50077. getContext() {
  50078. return this.context;
  50079. }
  50080. /**
  50081. * Returns the default render pass descriptor.
  50082. *
  50083. * In WebGPU, the default framebuffer must be configured
  50084. * like custom framebuffers so the backend needs a render
  50085. * pass descriptor even when rendering directly to screen.
  50086. *
  50087. * @private
  50088. * @return {Object} The render pass descriptor.
  50089. */
  50090. _getDefaultRenderPassDescriptor() {
  50091. let descriptor = this.defaultRenderPassdescriptor;
  50092. if ( descriptor === null ) {
  50093. const renderer = this.renderer;
  50094. descriptor = {
  50095. colorAttachments: [ {
  50096. view: null
  50097. } ],
  50098. };
  50099. if ( this.renderer.depth === true || this.renderer.stencil === true ) {
  50100. descriptor.depthStencilAttachment = {
  50101. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  50102. };
  50103. }
  50104. const colorAttachment = descriptor.colorAttachments[ 0 ];
  50105. if ( this.renderer.samples > 0 ) {
  50106. colorAttachment.view = this.colorBuffer.createView();
  50107. } else {
  50108. colorAttachment.resolveTarget = undefined;
  50109. }
  50110. this.defaultRenderPassdescriptor = descriptor;
  50111. }
  50112. const colorAttachment = descriptor.colorAttachments[ 0 ];
  50113. if ( this.renderer.samples > 0 ) {
  50114. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  50115. } else {
  50116. colorAttachment.view = this.context.getCurrentTexture().createView();
  50117. }
  50118. return descriptor;
  50119. }
  50120. /**
  50121. * Internal to determine if the current render target is a render target array with depth 2D array texture.
  50122. *
  50123. * @param {RenderContext} renderContext - The render context.
  50124. * @return {boolean} Whether the render target is a render target array with depth 2D array texture.
  50125. *
  50126. * @private
  50127. */
  50128. _isRenderCameraDepthArray( renderContext ) {
  50129. return renderContext.depthTexture && renderContext.depthTexture.image.depth > 1 && renderContext.camera.isArrayCamera;
  50130. }
  50131. /**
  50132. * Returns the render pass descriptor for the given render context.
  50133. *
  50134. * @private
  50135. * @param {RenderContext} renderContext - The render context.
  50136. * @param {Object} colorAttachmentsConfig - Configuration object for the color attachments.
  50137. * @return {Object} The render pass descriptor.
  50138. */
  50139. _getRenderPassDescriptor( renderContext, colorAttachmentsConfig = {} ) {
  50140. const renderTarget = renderContext.renderTarget;
  50141. const renderTargetData = this.get( renderTarget );
  50142. let descriptors = renderTargetData.descriptors;
  50143. if ( descriptors === undefined ||
  50144. renderTargetData.width !== renderTarget.width ||
  50145. renderTargetData.height !== renderTarget.height ||
  50146. renderTargetData.dimensions !== renderTarget.dimensions ||
  50147. renderTargetData.activeMipmapLevel !== renderContext.activeMipmapLevel ||
  50148. renderTargetData.activeCubeFace !== renderContext.activeCubeFace ||
  50149. renderTargetData.samples !== renderTarget.samples
  50150. ) {
  50151. descriptors = {};
  50152. renderTargetData.descriptors = descriptors;
  50153. // dispose
  50154. const onDispose = () => {
  50155. renderTarget.removeEventListener( 'dispose', onDispose );
  50156. this.delete( renderTarget );
  50157. };
  50158. if ( renderTarget.hasEventListener( 'dispose', onDispose ) === false ) {
  50159. renderTarget.addEventListener( 'dispose', onDispose );
  50160. }
  50161. }
  50162. const cacheKey = renderContext.getCacheKey();
  50163. let descriptorBase = descriptors[ cacheKey ];
  50164. if ( descriptorBase === undefined ) {
  50165. const textures = renderContext.textures;
  50166. const textureViews = [];
  50167. let sliceIndex;
  50168. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( renderContext );
  50169. for ( let i = 0; i < textures.length; i ++ ) {
  50170. const textureData = this.get( textures[ i ] );
  50171. const viewDescriptor = {
  50172. label: `colorAttachment_${ i }`,
  50173. baseMipLevel: renderContext.activeMipmapLevel,
  50174. mipLevelCount: 1,
  50175. baseArrayLayer: renderContext.activeCubeFace,
  50176. arrayLayerCount: 1,
  50177. dimension: GPUTextureViewDimension.TwoD
  50178. };
  50179. if ( renderTarget.isRenderTarget3D ) {
  50180. sliceIndex = renderContext.activeCubeFace;
  50181. viewDescriptor.baseArrayLayer = 0;
  50182. viewDescriptor.dimension = GPUTextureViewDimension.ThreeD;
  50183. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  50184. } else if ( renderTarget.isRenderTarget && textures[ i ].image.depth > 1 ) {
  50185. if ( isRenderCameraDepthArray === true ) {
  50186. const cameras = renderContext.camera.cameras;
  50187. for ( let layer = 0; layer < cameras.length; layer ++ ) {
  50188. const layerViewDescriptor = {
  50189. ...viewDescriptor,
  50190. baseArrayLayer: layer,
  50191. arrayLayerCount: 1,
  50192. dimension: GPUTextureViewDimension.TwoD
  50193. };
  50194. const textureView = textureData.texture.createView( layerViewDescriptor );
  50195. textureViews.push( {
  50196. view: textureView,
  50197. resolveTarget: undefined,
  50198. depthSlice: undefined
  50199. } );
  50200. }
  50201. } else {
  50202. viewDescriptor.dimension = GPUTextureViewDimension.TwoDArray;
  50203. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  50204. }
  50205. }
  50206. if ( isRenderCameraDepthArray !== true ) {
  50207. const textureView = textureData.texture.createView( viewDescriptor );
  50208. let view, resolveTarget;
  50209. if ( textureData.msaaTexture !== undefined ) {
  50210. view = textureData.msaaTexture.createView();
  50211. resolveTarget = textureView;
  50212. } else {
  50213. view = textureView;
  50214. resolveTarget = undefined;
  50215. }
  50216. textureViews.push( {
  50217. view,
  50218. resolveTarget,
  50219. depthSlice: sliceIndex
  50220. } );
  50221. }
  50222. }
  50223. descriptorBase = { textureViews };
  50224. if ( renderContext.depth ) {
  50225. const depthTextureData = this.get( renderContext.depthTexture );
  50226. const options = {};
  50227. if ( renderContext.depthTexture.isArrayTexture ) {
  50228. options.dimension = GPUTextureViewDimension.TwoD;
  50229. options.arrayLayerCount = 1;
  50230. options.baseArrayLayer = renderContext.activeCubeFace;
  50231. }
  50232. descriptorBase.depthStencilView = depthTextureData.texture.createView( options );
  50233. }
  50234. descriptors[ cacheKey ] = descriptorBase;
  50235. renderTargetData.width = renderTarget.width;
  50236. renderTargetData.height = renderTarget.height;
  50237. renderTargetData.samples = renderTarget.samples;
  50238. renderTargetData.activeMipmapLevel = renderContext.activeMipmapLevel;
  50239. renderTargetData.activeCubeFace = renderContext.activeCubeFace;
  50240. renderTargetData.dimensions = renderTarget.dimensions;
  50241. }
  50242. const descriptor = {
  50243. colorAttachments: []
  50244. };
  50245. // Apply dynamic properties to cached views
  50246. for ( let i = 0; i < descriptorBase.textureViews.length; i ++ ) {
  50247. const viewInfo = descriptorBase.textureViews[ i ];
  50248. let clearValue = { r: 0, g: 0, b: 0, a: 1 };
  50249. if ( i === 0 && colorAttachmentsConfig.clearValue ) {
  50250. clearValue = colorAttachmentsConfig.clearValue;
  50251. }
  50252. descriptor.colorAttachments.push( {
  50253. view: viewInfo.view,
  50254. depthSlice: viewInfo.depthSlice,
  50255. resolveTarget: viewInfo.resolveTarget,
  50256. loadOp: colorAttachmentsConfig.loadOp || GPULoadOp.Load,
  50257. storeOp: colorAttachmentsConfig.storeOp || GPUStoreOp.Store,
  50258. clearValue: clearValue
  50259. } );
  50260. }
  50261. if ( descriptorBase.depthStencilView ) {
  50262. descriptor.depthStencilAttachment = {
  50263. view: descriptorBase.depthStencilView
  50264. };
  50265. }
  50266. return descriptor;
  50267. }
  50268. /**
  50269. * This method is executed at the beginning of a render call and prepares
  50270. * the WebGPU state for upcoming render calls
  50271. *
  50272. * @param {RenderContext} renderContext - The render context.
  50273. */
  50274. beginRender( renderContext ) {
  50275. const renderContextData = this.get( renderContext );
  50276. const device = this.device;
  50277. const occlusionQueryCount = renderContext.occlusionQueryCount;
  50278. let occlusionQuerySet;
  50279. if ( occlusionQueryCount > 0 ) {
  50280. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  50281. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  50282. // Get a reference to the array of objects with queries. The renderContextData property
  50283. // can be changed by another render pass before the buffer.mapAsyc() completes.
  50284. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  50285. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  50286. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  50287. //
  50288. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount, label: `occlusionQuerySet_${ renderContext.id }` } );
  50289. renderContextData.occlusionQuerySet = occlusionQuerySet;
  50290. renderContextData.occlusionQueryIndex = 0;
  50291. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  50292. renderContextData.lastOcclusionObject = null;
  50293. }
  50294. let descriptor;
  50295. if ( renderContext.textures === null ) {
  50296. descriptor = this._getDefaultRenderPassDescriptor();
  50297. } else {
  50298. descriptor = this._getRenderPassDescriptor( renderContext, { loadOp: GPULoadOp.Load } );
  50299. }
  50300. this.initTimestampQuery( renderContext, descriptor );
  50301. descriptor.occlusionQuerySet = occlusionQuerySet;
  50302. const depthStencilAttachment = descriptor.depthStencilAttachment;
  50303. if ( renderContext.textures !== null ) {
  50304. const colorAttachments = descriptor.colorAttachments;
  50305. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  50306. const colorAttachment = colorAttachments[ i ];
  50307. if ( renderContext.clearColor ) {
  50308. colorAttachment.clearValue = i === 0 ? renderContext.clearColorValue : { r: 0, g: 0, b: 0, a: 1 };
  50309. colorAttachment.loadOp = GPULoadOp.Clear;
  50310. } else {
  50311. colorAttachment.loadOp = GPULoadOp.Load;
  50312. }
  50313. colorAttachment.storeOp = GPUStoreOp.Store;
  50314. }
  50315. } else {
  50316. const colorAttachment = descriptor.colorAttachments[ 0 ];
  50317. if ( renderContext.clearColor ) {
  50318. colorAttachment.clearValue = renderContext.clearColorValue;
  50319. colorAttachment.loadOp = GPULoadOp.Clear;
  50320. } else {
  50321. colorAttachment.loadOp = GPULoadOp.Load;
  50322. }
  50323. colorAttachment.storeOp = GPUStoreOp.Store;
  50324. }
  50325. //
  50326. if ( renderContext.depth ) {
  50327. if ( renderContext.clearDepth ) {
  50328. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  50329. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  50330. } else {
  50331. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  50332. }
  50333. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  50334. }
  50335. if ( renderContext.stencil ) {
  50336. if ( renderContext.clearStencil ) {
  50337. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  50338. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  50339. } else {
  50340. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  50341. }
  50342. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  50343. }
  50344. //
  50345. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  50346. // shadow arrays - prepare bundle encoders for each camera in an array camera
  50347. if ( this._isRenderCameraDepthArray( renderContext ) === true ) {
  50348. const cameras = renderContext.camera.cameras;
  50349. if ( ! renderContextData.layerDescriptors || renderContextData.layerDescriptors.length !== cameras.length ) {
  50350. this._createDepthLayerDescriptors( renderContext, renderContextData, descriptor, cameras );
  50351. } else {
  50352. this._updateDepthLayerDescriptors( renderContext, renderContextData, cameras );
  50353. }
  50354. // Create bundle encoders for each layer
  50355. renderContextData.bundleEncoders = [];
  50356. renderContextData.bundleSets = [];
  50357. // Create separate bundle encoders for each camera in the array
  50358. for ( let i = 0; i < cameras.length; i ++ ) {
  50359. const bundleEncoder = this.pipelineUtils.createBundleEncoder(
  50360. renderContext,
  50361. 'renderBundleArrayCamera_' + i
  50362. );
  50363. // Initialize state tracking for this bundle
  50364. const bundleSets = {
  50365. attributes: {},
  50366. bindingGroups: [],
  50367. pipeline: null,
  50368. index: null
  50369. };
  50370. renderContextData.bundleEncoders.push( bundleEncoder );
  50371. renderContextData.bundleSets.push( bundleSets );
  50372. }
  50373. // We'll complete the bundles in finishRender
  50374. renderContextData.currentPass = null;
  50375. } else {
  50376. const currentPass = encoder.beginRenderPass( descriptor );
  50377. renderContextData.currentPass = currentPass;
  50378. if ( renderContext.viewport ) {
  50379. this.updateViewport( renderContext );
  50380. }
  50381. if ( renderContext.scissor ) {
  50382. const { x, y, width, height } = renderContext.scissorValue;
  50383. currentPass.setScissorRect( x, y, width, height );
  50384. }
  50385. }
  50386. //
  50387. renderContextData.descriptor = descriptor;
  50388. renderContextData.encoder = encoder;
  50389. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  50390. renderContextData.renderBundles = [];
  50391. }
  50392. /**
  50393. * This method creates layer descriptors for each camera in an array camera
  50394. * to prepare for rendering to a depth array texture.
  50395. *
  50396. * @param {RenderContext} renderContext - The render context.
  50397. * @param {Object} renderContextData - The render context data.
  50398. * @param {Object} descriptor - The render pass descriptor.
  50399. * @param {ArrayCamera} cameras - The array camera.
  50400. *
  50401. * @private
  50402. */
  50403. _createDepthLayerDescriptors( renderContext, renderContextData, descriptor, cameras ) {
  50404. const depthStencilAttachment = descriptor.depthStencilAttachment;
  50405. renderContextData.layerDescriptors = [];
  50406. const depthTextureData = this.get( renderContext.depthTexture );
  50407. if ( ! depthTextureData.viewCache ) {
  50408. depthTextureData.viewCache = [];
  50409. }
  50410. for ( let i = 0; i < cameras.length; i ++ ) {
  50411. const layerDescriptor = {
  50412. ...descriptor,
  50413. colorAttachments: [ {
  50414. ...descriptor.colorAttachments[ 0 ],
  50415. view: descriptor.colorAttachments[ i ].view
  50416. } ]
  50417. };
  50418. if ( descriptor.depthStencilAttachment ) {
  50419. const layerIndex = i;
  50420. if ( ! depthTextureData.viewCache[ layerIndex ] ) {
  50421. depthTextureData.viewCache[ layerIndex ] = depthTextureData.texture.createView( {
  50422. dimension: GPUTextureViewDimension.TwoD,
  50423. baseArrayLayer: i,
  50424. arrayLayerCount: 1
  50425. } );
  50426. }
  50427. layerDescriptor.depthStencilAttachment = {
  50428. view: depthTextureData.viewCache[ layerIndex ],
  50429. depthLoadOp: depthStencilAttachment.depthLoadOp || GPULoadOp.Clear,
  50430. depthStoreOp: depthStencilAttachment.depthStoreOp || GPUStoreOp.Store,
  50431. depthClearValue: depthStencilAttachment.depthClearValue || 1.0
  50432. };
  50433. if ( renderContext.stencil ) {
  50434. layerDescriptor.depthStencilAttachment.stencilLoadOp = depthStencilAttachment.stencilLoadOp;
  50435. layerDescriptor.depthStencilAttachment.stencilStoreOp = depthStencilAttachment.stencilStoreOp;
  50436. layerDescriptor.depthStencilAttachment.stencilClearValue = depthStencilAttachment.stencilClearValue;
  50437. }
  50438. } else {
  50439. layerDescriptor.depthStencilAttachment = { ...depthStencilAttachment };
  50440. }
  50441. renderContextData.layerDescriptors.push( layerDescriptor );
  50442. }
  50443. }
  50444. /**
  50445. * This method updates the layer descriptors for each camera in an array camera
  50446. * to prepare for rendering to a depth array texture.
  50447. *
  50448. * @param {RenderContext} renderContext - The render context.
  50449. * @param {Object} renderContextData - The render context data.
  50450. * @param {ArrayCamera} cameras - The array camera.
  50451. *
  50452. */
  50453. _updateDepthLayerDescriptors( renderContext, renderContextData, cameras ) {
  50454. for ( let i = 0; i < cameras.length; i ++ ) {
  50455. const layerDescriptor = renderContextData.layerDescriptors[ i ];
  50456. if ( layerDescriptor.depthStencilAttachment ) {
  50457. const depthAttachment = layerDescriptor.depthStencilAttachment;
  50458. if ( renderContext.depth ) {
  50459. if ( renderContext.clearDepth ) {
  50460. depthAttachment.depthClearValue = renderContext.clearDepthValue;
  50461. depthAttachment.depthLoadOp = GPULoadOp.Clear;
  50462. } else {
  50463. depthAttachment.depthLoadOp = GPULoadOp.Load;
  50464. }
  50465. }
  50466. if ( renderContext.stencil ) {
  50467. if ( renderContext.clearStencil ) {
  50468. depthAttachment.stencilClearValue = renderContext.clearStencilValue;
  50469. depthAttachment.stencilLoadOp = GPULoadOp.Clear;
  50470. } else {
  50471. depthAttachment.stencilLoadOp = GPULoadOp.Load;
  50472. }
  50473. }
  50474. }
  50475. }
  50476. }
  50477. /**
  50478. * This method is executed at the end of a render call and finalizes work
  50479. * after draw calls.
  50480. *
  50481. * @param {RenderContext} renderContext - The render context.
  50482. */
  50483. finishRender( renderContext ) {
  50484. const renderContextData = this.get( renderContext );
  50485. const occlusionQueryCount = renderContext.occlusionQueryCount;
  50486. if ( renderContextData.renderBundles.length > 0 ) {
  50487. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  50488. }
  50489. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  50490. renderContextData.currentPass.endOcclusionQuery();
  50491. }
  50492. // shadow arrays - Execute bundles for each layer
  50493. const encoder = renderContextData.encoder;
  50494. if ( this._isRenderCameraDepthArray( renderContext ) === true ) {
  50495. const bundles = [];
  50496. for ( let i = 0; i < renderContextData.bundleEncoders.length; i ++ ) {
  50497. const bundleEncoder = renderContextData.bundleEncoders[ i ];
  50498. bundles.push( bundleEncoder.finish() );
  50499. }
  50500. for ( let i = 0; i < renderContextData.layerDescriptors.length; i ++ ) {
  50501. if ( i < bundles.length ) {
  50502. const layerDescriptor = renderContextData.layerDescriptors[ i ];
  50503. const renderPass = encoder.beginRenderPass( layerDescriptor );
  50504. if ( renderContext.viewport ) {
  50505. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  50506. renderPass.setViewport( x, y, width, height, minDepth, maxDepth );
  50507. }
  50508. if ( renderContext.scissor ) {
  50509. const { x, y, width, height } = renderContext.scissorValue;
  50510. renderPass.setScissorRect( x, y, width, height );
  50511. }
  50512. renderPass.executeBundles( [ bundles[ i ] ] );
  50513. renderPass.end();
  50514. }
  50515. }
  50516. } else if ( renderContextData.currentPass ) {
  50517. renderContextData.currentPass.end();
  50518. }
  50519. if ( occlusionQueryCount > 0 ) {
  50520. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  50521. //
  50522. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  50523. if ( queryResolveBuffer === undefined ) {
  50524. queryResolveBuffer = this.device.createBuffer(
  50525. {
  50526. size: bufferSize,
  50527. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  50528. }
  50529. );
  50530. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  50531. }
  50532. //
  50533. const readBuffer = this.device.createBuffer(
  50534. {
  50535. size: bufferSize,
  50536. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  50537. }
  50538. );
  50539. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  50540. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  50541. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  50542. renderContextData.occlusionQueryBuffer = readBuffer;
  50543. //
  50544. this.resolveOccludedAsync( renderContext );
  50545. }
  50546. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  50547. //
  50548. if ( renderContext.textures !== null ) {
  50549. const textures = renderContext.textures;
  50550. for ( let i = 0; i < textures.length; i ++ ) {
  50551. const texture = textures[ i ];
  50552. if ( texture.generateMipmaps === true ) {
  50553. this.textureUtils.generateMipmaps( texture );
  50554. }
  50555. }
  50556. }
  50557. }
  50558. /**
  50559. * Returns `true` if the given 3D object is fully occluded by other
  50560. * 3D objects in the scene.
  50561. *
  50562. * @param {RenderContext} renderContext - The render context.
  50563. * @param {Object3D} object - The 3D object to test.
  50564. * @return {boolean} Whether the 3D object is fully occluded or not.
  50565. */
  50566. isOccluded( renderContext, object ) {
  50567. const renderContextData = this.get( renderContext );
  50568. return renderContextData.occluded && renderContextData.occluded.has( object );
  50569. }
  50570. /**
  50571. * This method processes the result of occlusion queries and writes it
  50572. * into render context data.
  50573. *
  50574. * @async
  50575. * @param {RenderContext} renderContext - The render context.
  50576. * @return {Promise} A Promise that resolves when the occlusion query results have been processed.
  50577. */
  50578. async resolveOccludedAsync( renderContext ) {
  50579. const renderContextData = this.get( renderContext );
  50580. // handle occlusion query results
  50581. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  50582. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  50583. const occluded = new WeakSet();
  50584. renderContextData.currentOcclusionQueryObjects = null;
  50585. renderContextData.currentOcclusionQueryBuffer = null;
  50586. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  50587. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  50588. const results = new BigUint64Array( buffer );
  50589. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  50590. if ( results[ i ] === BigInt( 0 ) ) {
  50591. occluded.add( currentOcclusionQueryObjects[ i ] );
  50592. }
  50593. }
  50594. currentOcclusionQueryBuffer.destroy();
  50595. renderContextData.occluded = occluded;
  50596. }
  50597. }
  50598. /**
  50599. * Updates the viewport with the values from the given render context.
  50600. *
  50601. * @param {RenderContext} renderContext - The render context.
  50602. */
  50603. updateViewport( renderContext ) {
  50604. const { currentPass } = this.get( renderContext );
  50605. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  50606. currentPass.setViewport( x, y, width, height, minDepth, maxDepth );
  50607. }
  50608. /**
  50609. * Returns the clear color and alpha into a single
  50610. * color object.
  50611. *
  50612. * @return {Color4} The clear color.
  50613. */
  50614. getClearColor() {
  50615. const clearColor = super.getClearColor();
  50616. // only premultiply alpha when alphaMode is "premultiplied"
  50617. if ( this.renderer.alpha === true ) {
  50618. clearColor.r *= clearColor.a;
  50619. clearColor.g *= clearColor.a;
  50620. clearColor.b *= clearColor.a;
  50621. }
  50622. return clearColor;
  50623. }
  50624. /**
  50625. * Performs a clear operation.
  50626. *
  50627. * @param {boolean} color - Whether the color buffer should be cleared or not.
  50628. * @param {boolean} depth - Whether the depth buffer should be cleared or not.
  50629. * @param {boolean} stencil - Whether the stencil buffer should be cleared or not.
  50630. * @param {?RenderContext} [renderTargetContext=null] - The render context of the current set render target.
  50631. */
  50632. clear( color, depth, stencil, renderTargetContext = null ) {
  50633. const device = this.device;
  50634. const renderer = this.renderer;
  50635. let colorAttachments = [];
  50636. let depthStencilAttachment;
  50637. let clearValue;
  50638. let supportsDepth;
  50639. let supportsStencil;
  50640. if ( color ) {
  50641. const clearColor = this.getClearColor();
  50642. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  50643. }
  50644. if ( renderTargetContext === null ) {
  50645. supportsDepth = renderer.depth;
  50646. supportsStencil = renderer.stencil;
  50647. const descriptor = this._getDefaultRenderPassDescriptor();
  50648. if ( color ) {
  50649. colorAttachments = descriptor.colorAttachments;
  50650. const colorAttachment = colorAttachments[ 0 ];
  50651. colorAttachment.clearValue = clearValue;
  50652. colorAttachment.loadOp = GPULoadOp.Clear;
  50653. colorAttachment.storeOp = GPUStoreOp.Store;
  50654. }
  50655. if ( supportsDepth || supportsStencil ) {
  50656. depthStencilAttachment = descriptor.depthStencilAttachment;
  50657. }
  50658. } else {
  50659. supportsDepth = renderTargetContext.depth;
  50660. supportsStencil = renderTargetContext.stencil;
  50661. const clearConfig = {
  50662. loadOp: color ? GPULoadOp.Clear : GPULoadOp.Load,
  50663. clearValue: color ? clearValue : undefined
  50664. };
  50665. if ( supportsDepth ) {
  50666. clearConfig.depthLoadOp = depth ? GPULoadOp.Clear : GPULoadOp.Load;
  50667. clearConfig.depthClearValue = depth ? renderer.getClearDepth() : undefined;
  50668. clearConfig.depthStoreOp = GPUStoreOp.Store;
  50669. }
  50670. if ( supportsStencil ) {
  50671. clearConfig.stencilLoadOp = stencil ? GPULoadOp.Clear : GPULoadOp.Load;
  50672. clearConfig.stencilClearValue = stencil ? renderer.getClearStencil() : undefined;
  50673. clearConfig.stencilStoreOp = GPUStoreOp.Store;
  50674. }
  50675. const descriptor = this._getRenderPassDescriptor( renderTargetContext, clearConfig );
  50676. colorAttachments = descriptor.colorAttachments;
  50677. depthStencilAttachment = descriptor.depthStencilAttachment;
  50678. }
  50679. if ( supportsDepth && depthStencilAttachment && depthStencilAttachment.depthLoadOp === undefined ) {
  50680. if ( depth ) {
  50681. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  50682. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  50683. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  50684. } else {
  50685. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  50686. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  50687. }
  50688. }
  50689. //
  50690. if ( supportsStencil && depthStencilAttachment && depthStencilAttachment.stencilLoadOp === undefined ) {
  50691. if ( stencil ) {
  50692. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  50693. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  50694. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  50695. } else {
  50696. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  50697. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  50698. }
  50699. }
  50700. //
  50701. const encoder = device.createCommandEncoder( { label: 'clear' } );
  50702. const currentPass = encoder.beginRenderPass( {
  50703. colorAttachments,
  50704. depthStencilAttachment
  50705. } );
  50706. currentPass.end();
  50707. device.queue.submit( [ encoder.finish() ] );
  50708. }
  50709. // compute
  50710. /**
  50711. * This method is executed at the beginning of a compute call and
  50712. * prepares the state for upcoming compute tasks.
  50713. *
  50714. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  50715. */
  50716. beginCompute( computeGroup ) {
  50717. const groupGPU = this.get( computeGroup );
  50718. const descriptor = {
  50719. label: 'computeGroup_' + computeGroup.id
  50720. };
  50721. this.initTimestampQuery( computeGroup, descriptor );
  50722. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder( { label: 'computeGroup_' + computeGroup.id } );
  50723. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  50724. }
  50725. /**
  50726. * Executes a compute command for the given compute node.
  50727. *
  50728. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  50729. * @param {Node} computeNode - The compute node.
  50730. * @param {Array<BindGroup>} bindings - The bindings.
  50731. * @param {ComputePipeline} pipeline - The compute pipeline.
  50732. */
  50733. compute( computeGroup, computeNode, bindings, pipeline ) {
  50734. const { passEncoderGPU } = this.get( computeGroup );
  50735. // pipeline
  50736. const pipelineGPU = this.get( pipeline ).pipeline;
  50737. this.pipelineUtils.setPipeline( passEncoderGPU, pipelineGPU );
  50738. // bind groups
  50739. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  50740. const bindGroup = bindings[ i ];
  50741. const bindingsData = this.get( bindGroup );
  50742. passEncoderGPU.setBindGroup( i, bindingsData.group );
  50743. }
  50744. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  50745. const computeNodeData = this.get( computeNode );
  50746. if ( computeNodeData.dispatchSize === undefined ) computeNodeData.dispatchSize = { x: 0, y: 1, z: 1 };
  50747. const { dispatchSize } = computeNodeData;
  50748. if ( computeNode.dispatchCount > maxComputeWorkgroupsPerDimension ) {
  50749. dispatchSize.x = Math.min( computeNode.dispatchCount, maxComputeWorkgroupsPerDimension );
  50750. dispatchSize.y = Math.ceil( computeNode.dispatchCount / maxComputeWorkgroupsPerDimension );
  50751. } else {
  50752. dispatchSize.x = computeNode.dispatchCount;
  50753. }
  50754. passEncoderGPU.dispatchWorkgroups(
  50755. dispatchSize.x,
  50756. dispatchSize.y,
  50757. dispatchSize.z
  50758. );
  50759. }
  50760. /**
  50761. * This method is executed at the end of a compute call and
  50762. * finalizes work after compute tasks.
  50763. *
  50764. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  50765. */
  50766. finishCompute( computeGroup ) {
  50767. const groupData = this.get( computeGroup );
  50768. groupData.passEncoderGPU.end();
  50769. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  50770. }
  50771. /**
  50772. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  50773. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  50774. *
  50775. * @async
  50776. * @return {Promise} A Promise that resolves when synchronization has been finished.
  50777. */
  50778. async waitForGPU() {
  50779. await this.device.queue.onSubmittedWorkDone();
  50780. }
  50781. // render object
  50782. /**
  50783. * Executes a draw command for the given render object.
  50784. *
  50785. * @param {RenderObject} renderObject - The render object to draw.
  50786. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  50787. */
  50788. draw( renderObject, info ) {
  50789. const { object, material, context, pipeline } = renderObject;
  50790. const bindings = renderObject.getBindings();
  50791. const renderContextData = this.get( context );
  50792. const pipelineGPU = this.get( pipeline ).pipeline;
  50793. const index = renderObject.getIndex();
  50794. const hasIndex = ( index !== null );
  50795. const drawParams = renderObject.getDrawParameters();
  50796. if ( drawParams === null ) return;
  50797. // pipeline
  50798. const setPipelineAndBindings = ( passEncoderGPU, currentSets ) => {
  50799. // pipeline
  50800. this.pipelineUtils.setPipeline( passEncoderGPU, pipelineGPU );
  50801. currentSets.pipeline = pipelineGPU;
  50802. // bind groups
  50803. const currentBindingGroups = currentSets.bindingGroups;
  50804. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  50805. const bindGroup = bindings[ i ];
  50806. const bindingsData = this.get( bindGroup );
  50807. if ( currentBindingGroups[ bindGroup.index ] !== bindGroup.id ) {
  50808. passEncoderGPU.setBindGroup( bindGroup.index, bindingsData.group );
  50809. currentBindingGroups[ bindGroup.index ] = bindGroup.id;
  50810. }
  50811. }
  50812. // attributes
  50813. // index
  50814. if ( hasIndex === true ) {
  50815. if ( currentSets.index !== index ) {
  50816. const buffer = this.get( index ).buffer;
  50817. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  50818. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  50819. currentSets.index = index;
  50820. }
  50821. }
  50822. // vertex buffers
  50823. const vertexBuffers = renderObject.getVertexBuffers();
  50824. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  50825. const vertexBuffer = vertexBuffers[ i ];
  50826. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  50827. const buffer = this.get( vertexBuffer ).buffer;
  50828. passEncoderGPU.setVertexBuffer( i, buffer );
  50829. currentSets.attributes[ i ] = vertexBuffer;
  50830. }
  50831. }
  50832. // stencil
  50833. if ( context.stencil === true && material.stencilWrite === true && renderContextData.currentStencilRef !== material.stencilRef ) {
  50834. passEncoderGPU.setStencilReference( material.stencilRef );
  50835. renderContextData.currentStencilRef = material.stencilRef;
  50836. }
  50837. };
  50838. // Define draw function
  50839. const draw = ( passEncoderGPU, currentSets ) => {
  50840. setPipelineAndBindings( passEncoderGPU, currentSets );
  50841. if ( object.isBatchedMesh === true ) {
  50842. const starts = object._multiDrawStarts;
  50843. const counts = object._multiDrawCounts;
  50844. const drawCount = object._multiDrawCount;
  50845. const drawInstances = object._multiDrawInstances;
  50846. if ( drawInstances !== null ) {
  50847. // @deprecated, r174
  50848. warnOnce( 'THREE.WebGPUBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  50849. }
  50850. for ( let i = 0; i < drawCount; i ++ ) {
  50851. const count = drawInstances ? drawInstances[ i ] : 1;
  50852. const firstInstance = count > 1 ? 0 : i;
  50853. if ( hasIndex === true ) {
  50854. passEncoderGPU.drawIndexed( counts[ i ], count, starts[ i ] / index.array.BYTES_PER_ELEMENT, 0, firstInstance );
  50855. } else {
  50856. passEncoderGPU.draw( counts[ i ], count, starts[ i ], firstInstance );
  50857. }
  50858. info.update( object, counts[ i ], count );
  50859. }
  50860. } else if ( hasIndex === true ) {
  50861. const { vertexCount: indexCount, instanceCount, firstVertex: firstIndex } = drawParams;
  50862. const indirect = renderObject.getIndirect();
  50863. if ( indirect !== null ) {
  50864. const buffer = this.get( indirect ).buffer;
  50865. passEncoderGPU.drawIndexedIndirect( buffer, 0 );
  50866. } else {
  50867. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstIndex, 0, 0 );
  50868. }
  50869. info.update( object, indexCount, instanceCount );
  50870. } else {
  50871. const { vertexCount, instanceCount, firstVertex } = drawParams;
  50872. const indirect = renderObject.getIndirect();
  50873. if ( indirect !== null ) {
  50874. const buffer = this.get( indirect ).buffer;
  50875. passEncoderGPU.drawIndirect( buffer, 0 );
  50876. } else {
  50877. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  50878. }
  50879. info.update( object, vertexCount, instanceCount );
  50880. }
  50881. };
  50882. if ( renderObject.camera.isArrayCamera && renderObject.camera.cameras.length > 0 ) {
  50883. const cameraData = this.get( renderObject.camera );
  50884. const cameras = renderObject.camera.cameras;
  50885. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' );
  50886. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  50887. const bindingsData = this.get( cameraIndex );
  50888. const indexesGPU = [];
  50889. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  50890. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  50891. data[ 0 ] = i;
  50892. const bindGroupIndex = this.bindingUtils.createBindGroupIndex( data, bindingsData.layout );
  50893. indexesGPU.push( bindGroupIndex );
  50894. }
  50895. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  50896. }
  50897. const pixelRatio = this.renderer.getPixelRatio();
  50898. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  50899. const subCamera = cameras[ i ];
  50900. if ( object.layers.test( subCamera.layers ) ) {
  50901. const vp = subCamera.viewport;
  50902. let pass = renderContextData.currentPass;
  50903. let sets = renderContextData.currentSets;
  50904. if ( renderContextData.bundleEncoders ) {
  50905. const bundleEncoder = renderContextData.bundleEncoders[ i ];
  50906. const bundleSets = renderContextData.bundleSets[ i ];
  50907. pass = bundleEncoder;
  50908. sets = bundleSets;
  50909. }
  50910. if ( vp ) {
  50911. pass.setViewport(
  50912. Math.floor( vp.x * pixelRatio ),
  50913. Math.floor( vp.y * pixelRatio ),
  50914. Math.floor( vp.width * pixelRatio ),
  50915. Math.floor( vp.height * pixelRatio ),
  50916. context.viewportValue.minDepth,
  50917. context.viewportValue.maxDepth
  50918. );
  50919. }
  50920. // Set camera index binding for this layer
  50921. if ( cameraIndex && cameraData.indexesGPU ) {
  50922. pass.setBindGroup( cameraIndex.index, cameraData.indexesGPU[ i ] );
  50923. sets.bindingGroups[ cameraIndex.index ] = cameraIndex.id;
  50924. }
  50925. draw( pass, sets );
  50926. }
  50927. }
  50928. } else {
  50929. // Regular single camera rendering
  50930. if ( renderContextData.currentPass ) {
  50931. // Handle occlusion queries
  50932. if ( renderContextData.occlusionQuerySet !== undefined ) {
  50933. const lastObject = renderContextData.lastOcclusionObject;
  50934. if ( lastObject !== object ) {
  50935. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  50936. renderContextData.currentPass.endOcclusionQuery();
  50937. renderContextData.occlusionQueryIndex ++;
  50938. }
  50939. if ( object.occlusionTest === true ) {
  50940. renderContextData.currentPass.beginOcclusionQuery( renderContextData.occlusionQueryIndex );
  50941. renderContextData.occlusionQueryObjects[ renderContextData.occlusionQueryIndex ] = object;
  50942. }
  50943. renderContextData.lastOcclusionObject = object;
  50944. }
  50945. }
  50946. draw( renderContextData.currentPass, renderContextData.currentSets );
  50947. }
  50948. }
  50949. }
  50950. // cache key
  50951. /**
  50952. * Returns `true` if the render pipeline requires an update.
  50953. *
  50954. * @param {RenderObject} renderObject - The render object.
  50955. * @return {boolean} Whether the render pipeline requires an update or not.
  50956. */
  50957. needsRenderUpdate( renderObject ) {
  50958. const data = this.get( renderObject );
  50959. const { object, material } = renderObject;
  50960. const utils = this.utils;
  50961. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  50962. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  50963. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  50964. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  50965. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  50966. let needsUpdate = false;
  50967. if ( data.material !== material || data.materialVersion !== material.version ||
  50968. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  50969. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  50970. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  50971. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  50972. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  50973. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  50974. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  50975. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  50976. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  50977. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  50978. data.primitiveTopology !== primitiveTopology ||
  50979. data.clippingContextCacheKey !== renderObject.clippingContextCacheKey
  50980. ) {
  50981. data.material = material; data.materialVersion = material.version;
  50982. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  50983. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  50984. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  50985. data.colorWrite = material.colorWrite;
  50986. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  50987. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  50988. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  50989. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  50990. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  50991. data.sampleCount = sampleCount;
  50992. data.colorSpace = colorSpace;
  50993. data.colorFormat = colorFormat;
  50994. data.depthStencilFormat = depthStencilFormat;
  50995. data.primitiveTopology = primitiveTopology;
  50996. data.clippingContextCacheKey = renderObject.clippingContextCacheKey;
  50997. needsUpdate = true;
  50998. }
  50999. return needsUpdate;
  51000. }
  51001. /**
  51002. * Returns a cache key that is used to identify render pipelines.
  51003. *
  51004. * @param {RenderObject} renderObject - The render object.
  51005. * @return {string} The cache key.
  51006. */
  51007. getRenderCacheKey( renderObject ) {
  51008. const { object, material } = renderObject;
  51009. const utils = this.utils;
  51010. const renderContext = renderObject.context;
  51011. return [
  51012. material.transparent, material.blending, material.premultipliedAlpha,
  51013. material.blendSrc, material.blendDst, material.blendEquation,
  51014. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  51015. material.colorWrite,
  51016. material.depthWrite, material.depthTest, material.depthFunc,
  51017. material.stencilWrite, material.stencilFunc,
  51018. material.stencilFail, material.stencilZFail, material.stencilZPass,
  51019. material.stencilFuncMask, material.stencilWriteMask,
  51020. material.side,
  51021. utils.getSampleCountRenderContext( renderContext ),
  51022. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  51023. utils.getPrimitiveTopology( object, material ),
  51024. renderObject.getGeometryCacheKey(),
  51025. renderObject.clippingContextCacheKey
  51026. ].join();
  51027. }
  51028. // textures
  51029. /**
  51030. * Creates a GPU sampler for the given texture.
  51031. *
  51032. * @param {Texture} texture - The texture to create the sampler for.
  51033. */
  51034. createSampler( texture ) {
  51035. this.textureUtils.createSampler( texture );
  51036. }
  51037. /**
  51038. * Destroys the GPU sampler for the given texture.
  51039. *
  51040. * @param {Texture} texture - The texture to destroy the sampler for.
  51041. */
  51042. destroySampler( texture ) {
  51043. this.textureUtils.destroySampler( texture );
  51044. }
  51045. /**
  51046. * Creates a default texture for the given texture that can be used
  51047. * as a placeholder until the actual texture is ready for usage.
  51048. *
  51049. * @param {Texture} texture - The texture to create a default texture for.
  51050. */
  51051. createDefaultTexture( texture ) {
  51052. this.textureUtils.createDefaultTexture( texture );
  51053. }
  51054. /**
  51055. * Defines a texture on the GPU for the given texture object.
  51056. *
  51057. * @param {Texture} texture - The texture.
  51058. * @param {Object} [options={}] - Optional configuration parameter.
  51059. */
  51060. createTexture( texture, options ) {
  51061. this.textureUtils.createTexture( texture, options );
  51062. }
  51063. /**
  51064. * Uploads the updated texture data to the GPU.
  51065. *
  51066. * @param {Texture} texture - The texture.
  51067. * @param {Object} [options={}] - Optional configuration parameter.
  51068. */
  51069. updateTexture( texture, options ) {
  51070. this.textureUtils.updateTexture( texture, options );
  51071. }
  51072. /**
  51073. * Generates mipmaps for the given texture.
  51074. *
  51075. * @param {Texture} texture - The texture.
  51076. */
  51077. generateMipmaps( texture ) {
  51078. this.textureUtils.generateMipmaps( texture );
  51079. }
  51080. /**
  51081. * Destroys the GPU data for the given texture object.
  51082. *
  51083. * @param {Texture} texture - The texture.
  51084. */
  51085. destroyTexture( texture ) {
  51086. this.textureUtils.destroyTexture( texture );
  51087. }
  51088. /**
  51089. * Returns texture data as a typed array.
  51090. *
  51091. * @async
  51092. * @param {Texture} texture - The texture to copy.
  51093. * @param {number} x - The x coordinate of the copy origin.
  51094. * @param {number} y - The y coordinate of the copy origin.
  51095. * @param {number} width - The width of the copy.
  51096. * @param {number} height - The height of the copy.
  51097. * @param {number} faceIndex - The face index.
  51098. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  51099. */
  51100. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  51101. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  51102. }
  51103. /**
  51104. * Inits a time stamp query for the given render context.
  51105. *
  51106. * @param {RenderContext} renderContext - The render context.
  51107. * @param {Object} descriptor - The query descriptor.
  51108. */
  51109. initTimestampQuery( renderContext, descriptor ) {
  51110. if ( ! this.trackTimestamp ) return;
  51111. const type = renderContext.isComputeNode ? 'compute' : 'render';
  51112. if ( ! this.timestampQueryPool[ type ] ) {
  51113. // TODO: Variable maxQueries?
  51114. this.timestampQueryPool[ type ] = new WebGPUTimestampQueryPool( this.device, type, 2048 );
  51115. }
  51116. const timestampQueryPool = this.timestampQueryPool[ type ];
  51117. const baseOffset = timestampQueryPool.allocateQueriesForContext( renderContext );
  51118. descriptor.timestampWrites = {
  51119. querySet: timestampQueryPool.querySet,
  51120. beginningOfPassWriteIndex: baseOffset,
  51121. endOfPassWriteIndex: baseOffset + 1,
  51122. };
  51123. }
  51124. // node builder
  51125. /**
  51126. * Returns a node builder for the given render object.
  51127. *
  51128. * @param {RenderObject} object - The render object.
  51129. * @param {Renderer} renderer - The renderer.
  51130. * @return {WGSLNodeBuilder} The node builder.
  51131. */
  51132. createNodeBuilder( object, renderer ) {
  51133. return new WGSLNodeBuilder( object, renderer );
  51134. }
  51135. // program
  51136. /**
  51137. * Creates a shader program from the given programmable stage.
  51138. *
  51139. * @param {ProgrammableStage} program - The programmable stage.
  51140. */
  51141. createProgram( program ) {
  51142. const programGPU = this.get( program );
  51143. programGPU.module = {
  51144. module: this.device.createShaderModule( { code: program.code, label: program.stage + ( program.name !== '' ? `_${ program.name }` : '' ) } ),
  51145. entryPoint: 'main'
  51146. };
  51147. }
  51148. /**
  51149. * Destroys the shader program of the given programmable stage.
  51150. *
  51151. * @param {ProgrammableStage} program - The programmable stage.
  51152. */
  51153. destroyProgram( program ) {
  51154. this.delete( program );
  51155. }
  51156. // pipelines
  51157. /**
  51158. * Creates a render pipeline for the given render object.
  51159. *
  51160. * @param {RenderObject} renderObject - The render object.
  51161. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  51162. */
  51163. createRenderPipeline( renderObject, promises ) {
  51164. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  51165. }
  51166. /**
  51167. * Creates a compute pipeline for the given compute node.
  51168. *
  51169. * @param {ComputePipeline} computePipeline - The compute pipeline.
  51170. * @param {Array<BindGroup>} bindings - The bindings.
  51171. */
  51172. createComputePipeline( computePipeline, bindings ) {
  51173. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  51174. }
  51175. /**
  51176. * Prepares the state for encoding render bundles.
  51177. *
  51178. * @param {RenderContext} renderContext - The render context.
  51179. */
  51180. beginBundle( renderContext ) {
  51181. const renderContextData = this.get( renderContext );
  51182. renderContextData._currentPass = renderContextData.currentPass;
  51183. renderContextData._currentSets = renderContextData.currentSets;
  51184. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  51185. renderContextData.currentPass = this.pipelineUtils.createBundleEncoder( renderContext );
  51186. }
  51187. /**
  51188. * After processing render bundles this method finalizes related work.
  51189. *
  51190. * @param {RenderContext} renderContext - The render context.
  51191. * @param {RenderBundle} bundle - The render bundle.
  51192. */
  51193. finishBundle( renderContext, bundle ) {
  51194. const renderContextData = this.get( renderContext );
  51195. const bundleEncoder = renderContextData.currentPass;
  51196. const bundleGPU = bundleEncoder.finish();
  51197. this.get( bundle ).bundleGPU = bundleGPU;
  51198. // restore render pass state
  51199. renderContextData.currentSets = renderContextData._currentSets;
  51200. renderContextData.currentPass = renderContextData._currentPass;
  51201. }
  51202. /**
  51203. * Adds a render bundle to the render context data.
  51204. *
  51205. * @param {RenderContext} renderContext - The render context.
  51206. * @param {RenderBundle} bundle - The render bundle to add.
  51207. */
  51208. addBundle( renderContext, bundle ) {
  51209. const renderContextData = this.get( renderContext );
  51210. renderContextData.renderBundles.push( this.get( bundle ).bundleGPU );
  51211. }
  51212. // bindings
  51213. /**
  51214. * Creates bindings from the given bind group definition.
  51215. *
  51216. * @param {BindGroup} bindGroup - The bind group.
  51217. * @param {Array<BindGroup>} bindings - Array of bind groups.
  51218. * @param {number} cacheIndex - The cache index.
  51219. * @param {number} version - The version.
  51220. */
  51221. createBindings( bindGroup, bindings, cacheIndex, version ) {
  51222. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  51223. }
  51224. /**
  51225. * Updates the given bind group definition.
  51226. *
  51227. * @param {BindGroup} bindGroup - The bind group.
  51228. * @param {Array<BindGroup>} bindings - Array of bind groups.
  51229. * @param {number} cacheIndex - The cache index.
  51230. * @param {number} version - The version.
  51231. */
  51232. updateBindings( bindGroup, bindings, cacheIndex, version ) {
  51233. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  51234. }
  51235. /**
  51236. * Updates a buffer binding.
  51237. *
  51238. * @param {Buffer} binding - The buffer binding to update.
  51239. */
  51240. updateBinding( binding ) {
  51241. this.bindingUtils.updateBinding( binding );
  51242. }
  51243. // attributes
  51244. /**
  51245. * Creates the buffer of an indexed shader attribute.
  51246. *
  51247. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  51248. */
  51249. createIndexAttribute( attribute ) {
  51250. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  51251. }
  51252. /**
  51253. * Creates the GPU buffer of a shader attribute.
  51254. *
  51255. * @param {BufferAttribute} attribute - The buffer attribute.
  51256. */
  51257. createAttribute( attribute ) {
  51258. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  51259. }
  51260. /**
  51261. * Creates the GPU buffer of a storage attribute.
  51262. *
  51263. * @param {BufferAttribute} attribute - The buffer attribute.
  51264. */
  51265. createStorageAttribute( attribute ) {
  51266. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  51267. }
  51268. /**
  51269. * Creates the GPU buffer of an indirect storage attribute.
  51270. *
  51271. * @param {BufferAttribute} attribute - The buffer attribute.
  51272. */
  51273. createIndirectStorageAttribute( attribute ) {
  51274. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  51275. }
  51276. /**
  51277. * Updates the GPU buffer of a shader attribute.
  51278. *
  51279. * @param {BufferAttribute} attribute - The buffer attribute to update.
  51280. */
  51281. updateAttribute( attribute ) {
  51282. this.attributeUtils.updateAttribute( attribute );
  51283. }
  51284. /**
  51285. * Destroys the GPU buffer of a shader attribute.
  51286. *
  51287. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  51288. */
  51289. destroyAttribute( attribute ) {
  51290. this.attributeUtils.destroyAttribute( attribute );
  51291. }
  51292. // canvas
  51293. /**
  51294. * Triggers an update of the default render pass descriptor.
  51295. */
  51296. updateSize() {
  51297. this.colorBuffer = this.textureUtils.getColorBuffer();
  51298. this.defaultRenderPassdescriptor = null;
  51299. }
  51300. // utils public
  51301. /**
  51302. * Returns the maximum anisotropy texture filtering value.
  51303. *
  51304. * @return {number} The maximum anisotropy texture filtering value.
  51305. */
  51306. getMaxAnisotropy() {
  51307. return 16;
  51308. }
  51309. /**
  51310. * Checks if the given feature is supported by the backend.
  51311. *
  51312. * @param {string} name - The feature's name.
  51313. * @return {boolean} Whether the feature is supported or not.
  51314. */
  51315. hasFeature( name ) {
  51316. return this.device.features.has( name );
  51317. }
  51318. /**
  51319. * Copies data of the given source texture to the given destination texture.
  51320. *
  51321. * @param {Texture} srcTexture - The source texture.
  51322. * @param {Texture} dstTexture - The destination texture.
  51323. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  51324. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  51325. * @param {number} [srcLevel=0] - The mipmap level to copy.
  51326. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  51327. */
  51328. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  51329. let dstX = 0;
  51330. let dstY = 0;
  51331. let dstZ = 0;
  51332. let srcX = 0;
  51333. let srcY = 0;
  51334. let srcZ = 0;
  51335. let srcWidth = srcTexture.image.width;
  51336. let srcHeight = srcTexture.image.height;
  51337. let srcDepth = 1;
  51338. if ( srcRegion !== null ) {
  51339. if ( srcRegion.isBox3 === true ) {
  51340. srcX = srcRegion.min.x;
  51341. srcY = srcRegion.min.y;
  51342. srcZ = srcRegion.min.z;
  51343. srcWidth = srcRegion.max.x - srcRegion.min.x;
  51344. srcHeight = srcRegion.max.y - srcRegion.min.y;
  51345. srcDepth = srcRegion.max.z - srcRegion.min.z;
  51346. } else {
  51347. // Assume it's a Box2
  51348. srcX = srcRegion.min.x;
  51349. srcY = srcRegion.min.y;
  51350. srcWidth = srcRegion.max.x - srcRegion.min.x;
  51351. srcHeight = srcRegion.max.y - srcRegion.min.y;
  51352. srcDepth = 1;
  51353. }
  51354. }
  51355. if ( dstPosition !== null ) {
  51356. dstX = dstPosition.x;
  51357. dstY = dstPosition.y;
  51358. dstZ = dstPosition.z || 0;
  51359. }
  51360. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  51361. const sourceGPU = this.get( srcTexture ).texture;
  51362. const destinationGPU = this.get( dstTexture ).texture;
  51363. encoder.copyTextureToTexture(
  51364. {
  51365. texture: sourceGPU,
  51366. mipLevel: srcLevel,
  51367. origin: { x: srcX, y: srcY, z: srcZ }
  51368. },
  51369. {
  51370. texture: destinationGPU,
  51371. mipLevel: dstLevel,
  51372. origin: { x: dstX, y: dstY, z: dstZ }
  51373. },
  51374. [
  51375. srcWidth,
  51376. srcHeight,
  51377. srcDepth
  51378. ]
  51379. );
  51380. this.device.queue.submit( [ encoder.finish() ] );
  51381. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  51382. this.textureUtils.generateMipmaps( dstTexture );
  51383. }
  51384. }
  51385. /**
  51386. * Copies the current bound framebuffer to the given texture.
  51387. *
  51388. * @param {Texture} texture - The destination texture.
  51389. * @param {RenderContext} renderContext - The render context.
  51390. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  51391. */
  51392. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  51393. const renderContextData = this.get( renderContext );
  51394. let sourceGPU = null;
  51395. if ( renderContext.renderTarget ) {
  51396. if ( texture.isDepthTexture ) {
  51397. sourceGPU = this.get( renderContext.depthTexture ).texture;
  51398. } else {
  51399. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  51400. }
  51401. } else {
  51402. if ( texture.isDepthTexture ) {
  51403. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  51404. } else {
  51405. sourceGPU = this.context.getCurrentTexture();
  51406. }
  51407. }
  51408. const destinationGPU = this.get( texture ).texture;
  51409. if ( sourceGPU.format !== destinationGPU.format ) {
  51410. console.error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  51411. return;
  51412. }
  51413. let encoder;
  51414. if ( renderContextData.currentPass ) {
  51415. renderContextData.currentPass.end();
  51416. encoder = renderContextData.encoder;
  51417. } else {
  51418. encoder = this.device.createCommandEncoder( { label: 'copyFramebufferToTexture_' + texture.id } );
  51419. }
  51420. encoder.copyTextureToTexture(
  51421. {
  51422. texture: sourceGPU,
  51423. origin: [ rectangle.x, rectangle.y, 0 ],
  51424. },
  51425. {
  51426. texture: destinationGPU
  51427. },
  51428. [
  51429. rectangle.z,
  51430. rectangle.w
  51431. ]
  51432. );
  51433. if ( renderContextData.currentPass ) {
  51434. const { descriptor } = renderContextData;
  51435. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  51436. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  51437. }
  51438. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  51439. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  51440. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  51441. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  51442. if ( renderContext.viewport ) {
  51443. this.updateViewport( renderContext );
  51444. }
  51445. if ( renderContext.scissor ) {
  51446. const { x, y, width, height } = renderContext.scissorValue;
  51447. renderContextData.currentPass.setScissorRect( x, y, width, height );
  51448. }
  51449. } else {
  51450. this.device.queue.submit( [ encoder.finish() ] );
  51451. }
  51452. if ( texture.generateMipmaps ) {
  51453. this.textureUtils.generateMipmaps( texture );
  51454. }
  51455. }
  51456. }
  51457. /**
  51458. * A IES version of {@link SpotLight}. Can only be used with {@link WebGPURenderer}.
  51459. *
  51460. * @augments SpotLight
  51461. */
  51462. class IESSpotLight extends SpotLight {
  51463. /**
  51464. * Constructs a new IES spot light.
  51465. *
  51466. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  51467. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  51468. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  51469. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  51470. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  51471. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  51472. */
  51473. constructor( color, intensity, distance, angle, penumbra, decay ) {
  51474. super( color, intensity, distance, angle, penumbra, decay );
  51475. /**
  51476. * TODO
  51477. *
  51478. * @type {?Texture}
  51479. * @default null
  51480. */
  51481. this.iesMap = null;
  51482. }
  51483. copy( source, recursive ) {
  51484. super.copy( source, recursive );
  51485. this.iesMap = source.iesMap;
  51486. return this;
  51487. }
  51488. }
  51489. /**
  51490. * A projector light version of {@link SpotLight}. Can only be used with {@link WebGPURenderer}.
  51491. *
  51492. * @augments SpotLight
  51493. */
  51494. class ProjectorLight extends SpotLight {
  51495. /**
  51496. * Constructs a new projector light.
  51497. *
  51498. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  51499. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  51500. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  51501. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  51502. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  51503. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  51504. */
  51505. constructor( color, intensity, distance, angle, penumbra, decay ) {
  51506. super( color, intensity, distance, angle, penumbra, decay );
  51507. /**
  51508. * Aspect ratio of the light. Set to `null` to use the texture aspect ratio.
  51509. *
  51510. * @type {number}
  51511. * @default null
  51512. */
  51513. this.aspect = null;
  51514. }
  51515. copy( source, recursive ) {
  51516. super.copy( source, recursive );
  51517. this.aspect = source.aspect;
  51518. return this;
  51519. }
  51520. }
  51521. /**
  51522. * This version of a node library represents the standard version
  51523. * used in {@link WebGPURenderer}. It maps lights, tone mapping
  51524. * techniques and materials to node-based implementations.
  51525. *
  51526. * @private
  51527. * @augments NodeLibrary
  51528. */
  51529. class StandardNodeLibrary extends NodeLibrary {
  51530. /**
  51531. * Constructs a new standard node library.
  51532. */
  51533. constructor() {
  51534. super();
  51535. this.addMaterial( MeshPhongNodeMaterial, 'MeshPhongMaterial' );
  51536. this.addMaterial( MeshStandardNodeMaterial, 'MeshStandardMaterial' );
  51537. this.addMaterial( MeshPhysicalNodeMaterial, 'MeshPhysicalMaterial' );
  51538. this.addMaterial( MeshToonNodeMaterial, 'MeshToonMaterial' );
  51539. this.addMaterial( MeshBasicNodeMaterial, 'MeshBasicMaterial' );
  51540. this.addMaterial( MeshLambertNodeMaterial, 'MeshLambertMaterial' );
  51541. this.addMaterial( MeshNormalNodeMaterial, 'MeshNormalMaterial' );
  51542. this.addMaterial( MeshMatcapNodeMaterial, 'MeshMatcapMaterial' );
  51543. this.addMaterial( LineBasicNodeMaterial, 'LineBasicMaterial' );
  51544. this.addMaterial( LineDashedNodeMaterial, 'LineDashedMaterial' );
  51545. this.addMaterial( PointsNodeMaterial, 'PointsMaterial' );
  51546. this.addMaterial( SpriteNodeMaterial, 'SpriteMaterial' );
  51547. this.addMaterial( ShadowNodeMaterial, 'ShadowMaterial' );
  51548. this.addLight( PointLightNode, PointLight );
  51549. this.addLight( DirectionalLightNode, DirectionalLight );
  51550. this.addLight( RectAreaLightNode, RectAreaLight );
  51551. this.addLight( SpotLightNode, SpotLight );
  51552. this.addLight( AmbientLightNode, AmbientLight );
  51553. this.addLight( HemisphereLightNode, HemisphereLight );
  51554. this.addLight( LightProbeNode, LightProbe );
  51555. this.addLight( IESSpotLightNode, IESSpotLight );
  51556. this.addLight( ProjectorLightNode, ProjectorLight );
  51557. this.addToneMapping( linearToneMapping, LinearToneMapping );
  51558. this.addToneMapping( reinhardToneMapping, ReinhardToneMapping );
  51559. this.addToneMapping( cineonToneMapping, CineonToneMapping );
  51560. this.addToneMapping( acesFilmicToneMapping, ACESFilmicToneMapping );
  51561. this.addToneMapping( agxToneMapping, AgXToneMapping );
  51562. this.addToneMapping( neutralToneMapping, NeutralToneMapping );
  51563. }
  51564. }
  51565. /*
  51566. const debugHandler = {
  51567. get: function ( target, name ) {
  51568. // Add |update
  51569. if ( /^(create|destroy)/.test( name ) ) console.log( 'WebGPUBackend.' + name );
  51570. return target[ name ];
  51571. }
  51572. };
  51573. */
  51574. /**
  51575. * This renderer is the new alternative of `WebGLRenderer`. `WebGPURenderer` has the ability
  51576. * to target different backends. By default, the renderer tries to use a WebGPU backend if the
  51577. * browser supports WebGPU. If not, `WebGPURenderer` falls backs to a WebGL 2 backend.
  51578. *
  51579. * @augments Renderer
  51580. */
  51581. class WebGPURenderer extends Renderer {
  51582. /**
  51583. * WebGPURenderer options.
  51584. *
  51585. * @typedef {Object} WebGPURenderer~Options
  51586. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  51587. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  51588. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  51589. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  51590. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  51591. * @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.
  51592. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  51593. * @property {boolean} [multiview=false] - If set to `true`, the renderer will use multiview during WebXR rendering if supported.
  51594. * @property {number} [outputType=undefined] - Texture type for output to canvas. By default, device's preferred format is used; other formats may incur overhead.
  51595. * @property {number} [colorBufferType=HalfFloatType] - Defines the type of color buffers. The default `HalfFloatType` is recommend for best
  51596. * quality. To save memory and bandwidth, `UnsignedByteType` might be used. This will reduce rendering quality though.
  51597. */
  51598. /**
  51599. * Constructs a new WebGPU renderer.
  51600. *
  51601. * @param {WebGPURenderer~Options} [parameters] - The configuration parameter.
  51602. */
  51603. constructor( parameters = {} ) {
  51604. let BackendClass;
  51605. if ( parameters.forceWebGL ) {
  51606. BackendClass = WebGLBackend;
  51607. } else {
  51608. BackendClass = WebGPUBackend;
  51609. parameters.getFallback = () => {
  51610. console.warn( 'THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  51611. return new WebGLBackend( parameters );
  51612. };
  51613. }
  51614. const backend = new BackendClass( parameters );
  51615. //super( new Proxy( backend, debugHandler ) );
  51616. super( backend, parameters );
  51617. /**
  51618. * The generic default value is overwritten with the
  51619. * standard node library for type mapping.
  51620. *
  51621. * @type {StandardNodeLibrary}
  51622. */
  51623. this.library = new StandardNodeLibrary();
  51624. /**
  51625. * This flag can be used for type testing.
  51626. *
  51627. * @type {boolean}
  51628. * @readonly
  51629. * @default true
  51630. */
  51631. this.isWebGPURenderer = true;
  51632. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  51633. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  51634. }
  51635. }
  51636. }
  51637. /**
  51638. * A specialized group which enables applications access to the
  51639. * Render Bundle API of WebGPU. The group with all its descendant nodes
  51640. * are considered as one render bundle and processed as such by
  51641. * the renderer.
  51642. *
  51643. * This module is only fully supported by `WebGPURenderer` with a WebGPU backend.
  51644. * With a WebGL backend, the group can technically be rendered but without
  51645. * any performance improvements.
  51646. *
  51647. * @augments Group
  51648. */
  51649. class BundleGroup extends Group {
  51650. /**
  51651. * Constructs a new bundle group.
  51652. */
  51653. constructor() {
  51654. super();
  51655. /**
  51656. * This flag can be used for type testing.
  51657. *
  51658. * @type {boolean}
  51659. * @readonly
  51660. * @default true
  51661. */
  51662. this.isBundleGroup = true;
  51663. /**
  51664. * This property is only relevant for detecting types
  51665. * during serialization/deserialization. It should always
  51666. * match the class name.
  51667. *
  51668. * @type {string}
  51669. * @readonly
  51670. * @default 'BundleGroup'
  51671. */
  51672. this.type = 'BundleGroup';
  51673. /**
  51674. * Whether the bundle is static or not. When set to `true`, the structure
  51675. * is assumed to be static and does not change. E.g. no new objects are
  51676. * added to the group
  51677. *
  51678. * If a change is required, an update can still be forced by setting the
  51679. * `needsUpdate` flag to `true`.
  51680. *
  51681. * @type {boolean}
  51682. * @default true
  51683. */
  51684. this.static = true;
  51685. /**
  51686. * The bundle group's version.
  51687. *
  51688. * @type {number}
  51689. * @readonly
  51690. * @default 0
  51691. */
  51692. this.version = 0;
  51693. }
  51694. /**
  51695. * Set this property to `true` when the bundle group has changed.
  51696. *
  51697. * @type {boolean}
  51698. * @default false
  51699. * @param {boolean} value
  51700. */
  51701. set needsUpdate( value ) {
  51702. if ( value === true ) this.version ++;
  51703. }
  51704. }
  51705. /**
  51706. * This module is responsible to manage the post processing setups in apps.
  51707. * You usually create a single instance of this class and use it to define
  51708. * the output of your post processing effect chain.
  51709. * ```js
  51710. * const postProcessing = new PostProcessing( renderer );
  51711. *
  51712. * const scenePass = pass( scene, camera );
  51713. *
  51714. * postProcessing.outputNode = scenePass;
  51715. * ```
  51716. *
  51717. * Note: This module can only be used with `WebGPURenderer`.
  51718. */
  51719. class PostProcessing {
  51720. /**
  51721. * Constructs a new post processing management module.
  51722. *
  51723. * @param {Renderer} renderer - A reference to the renderer.
  51724. * @param {Node<vec4>} outputNode - An optional output node.
  51725. */
  51726. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  51727. /**
  51728. * A reference to the renderer.
  51729. *
  51730. * @type {Renderer}
  51731. */
  51732. this.renderer = renderer;
  51733. /**
  51734. * A node which defines the final output of the post
  51735. * processing. This is usually the last node in a chain
  51736. * of effect nodes.
  51737. *
  51738. * @type {Node<vec4>}
  51739. */
  51740. this.outputNode = outputNode;
  51741. /**
  51742. * Whether the default output tone mapping and color
  51743. * space transformation should be enabled or not.
  51744. *
  51745. * It is enabled by default by it must be disabled when
  51746. * effects must be executed after tone mapping and color
  51747. * space conversion. A typical example is FXAA which
  51748. * requires sRGB input.
  51749. *
  51750. * When set to `false`, the app must control the output
  51751. * transformation with `RenderOutputNode`.
  51752. *
  51753. * ```js
  51754. * const outputPass = renderOutput( scenePass );
  51755. * ```
  51756. *
  51757. * @type {boolean}
  51758. */
  51759. this.outputColorTransform = true;
  51760. /**
  51761. * Must be set to `true` when the output node changes.
  51762. *
  51763. * @type {Node<vec4>}
  51764. */
  51765. this.needsUpdate = true;
  51766. const material = new NodeMaterial();
  51767. material.name = 'PostProcessing';
  51768. /**
  51769. * The full screen quad that is used to render
  51770. * the effects.
  51771. *
  51772. * @private
  51773. * @type {QuadMesh}
  51774. */
  51775. this._quadMesh = new QuadMesh( material );
  51776. }
  51777. /**
  51778. * When `PostProcessing` is used to apply post processing effects,
  51779. * the application must use this version of `render()` inside
  51780. * its animation loop (not the one from the renderer).
  51781. */
  51782. render() {
  51783. this._update();
  51784. const renderer = this.renderer;
  51785. const toneMapping = renderer.toneMapping;
  51786. const outputColorSpace = renderer.outputColorSpace;
  51787. renderer.toneMapping = NoToneMapping;
  51788. renderer.outputColorSpace = LinearSRGBColorSpace;
  51789. //
  51790. const currentXR = renderer.xr.enabled;
  51791. renderer.xr.enabled = false;
  51792. this._quadMesh.render( renderer );
  51793. renderer.xr.enabled = currentXR;
  51794. //
  51795. renderer.toneMapping = toneMapping;
  51796. renderer.outputColorSpace = outputColorSpace;
  51797. }
  51798. /**
  51799. * Frees internal resources.
  51800. */
  51801. dispose() {
  51802. this._quadMesh.material.dispose();
  51803. }
  51804. /**
  51805. * Updates the state of the module.
  51806. *
  51807. * @private
  51808. */
  51809. _update() {
  51810. if ( this.needsUpdate === true ) {
  51811. const renderer = this.renderer;
  51812. const toneMapping = renderer.toneMapping;
  51813. const outputColorSpace = renderer.outputColorSpace;
  51814. this._quadMesh.material.fragmentNode = this.outputColorTransform === true ? renderOutput( this.outputNode, toneMapping, outputColorSpace ) : this.outputNode.context( { toneMapping, outputColorSpace } );
  51815. this._quadMesh.material.needsUpdate = true;
  51816. this.needsUpdate = false;
  51817. }
  51818. }
  51819. /**
  51820. * When `PostProcessing` is used to apply post processing effects,
  51821. * the application must use this version of `renderAsync()` inside
  51822. * its animation loop (not the one from the renderer).
  51823. *
  51824. * @async
  51825. * @return {Promise} A Promise that resolves when the render has been finished.
  51826. */
  51827. async renderAsync() {
  51828. this._update();
  51829. const renderer = this.renderer;
  51830. const toneMapping = renderer.toneMapping;
  51831. const outputColorSpace = renderer.outputColorSpace;
  51832. renderer.toneMapping = NoToneMapping;
  51833. renderer.outputColorSpace = LinearSRGBColorSpace;
  51834. //
  51835. const currentXR = renderer.xr.enabled;
  51836. renderer.xr.enabled = false;
  51837. await this._quadMesh.renderAsync( renderer );
  51838. renderer.xr.enabled = currentXR;
  51839. //
  51840. renderer.toneMapping = toneMapping;
  51841. renderer.outputColorSpace = outputColorSpace;
  51842. }
  51843. }
  51844. /**
  51845. * This special type of texture is intended for compute shaders.
  51846. * It can be used to compute the data of a texture with a compute shader.
  51847. *
  51848. * Note: This type of texture can only be used with `WebGPURenderer`
  51849. * and a WebGPU backend.
  51850. *
  51851. * @augments Texture
  51852. */
  51853. class StorageTexture extends Texture {
  51854. /**
  51855. * Constructs a new storage texture.
  51856. *
  51857. * @param {number} [width=1] - The storage texture's width.
  51858. * @param {number} [height=1] - The storage texture's height.
  51859. */
  51860. constructor( width = 1, height = 1 ) {
  51861. super();
  51862. /**
  51863. * The image object which just represents the texture's dimension.
  51864. *
  51865. * @type {{width: number, height: number}}
  51866. */
  51867. this.image = { width, height };
  51868. /**
  51869. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  51870. *
  51871. * @type {number}
  51872. */
  51873. this.magFilter = LinearFilter;
  51874. /**
  51875. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  51876. *
  51877. * @type {number}
  51878. */
  51879. this.minFilter = LinearFilter;
  51880. /**
  51881. * This flag can be used for type testing.
  51882. *
  51883. * @type {boolean}
  51884. * @readonly
  51885. * @default true
  51886. */
  51887. this.isStorageTexture = true;
  51888. }
  51889. }
  51890. /**
  51891. * This special type of buffer attribute is intended for compute shaders.
  51892. * It can be used to encode draw parameters for indirect draw calls.
  51893. *
  51894. * Note: This type of buffer attribute can only be used with `WebGPURenderer`
  51895. * and a WebGPU backend.
  51896. *
  51897. * @augments StorageBufferAttribute
  51898. */
  51899. class IndirectStorageBufferAttribute extends StorageBufferAttribute {
  51900. /**
  51901. * Constructs a new storage buffer attribute.
  51902. *
  51903. * @param {number|Uint32Array} count - The item count. It is also valid to pass a `Uint32Array` as an argument.
  51904. * The subsequent parameter is then obsolete.
  51905. * @param {number} itemSize - The item size.
  51906. */
  51907. constructor( count, itemSize ) {
  51908. super( count, itemSize, Uint32Array );
  51909. /**
  51910. * This flag can be used for type testing.
  51911. *
  51912. * @type {boolean}
  51913. * @readonly
  51914. * @default true
  51915. */
  51916. this.isIndirectStorageBufferAttribute = true;
  51917. }
  51918. }
  51919. /**
  51920. * A loader for loading node objects in the three.js JSON Object/Scene format.
  51921. *
  51922. * @augments Loader
  51923. */
  51924. class NodeLoader extends Loader {
  51925. /**
  51926. * Constructs a new node loader.
  51927. *
  51928. * @param {LoadingManager} [manager] - A reference to a loading manager.
  51929. */
  51930. constructor( manager ) {
  51931. super( manager );
  51932. /**
  51933. * Represents a dictionary of textures.
  51934. *
  51935. * @type {Object<string,Texture>}
  51936. */
  51937. this.textures = {};
  51938. /**
  51939. * Represents a dictionary of node types.
  51940. *
  51941. * @type {Object<string,Node.constructor>}
  51942. */
  51943. this.nodes = {};
  51944. }
  51945. /**
  51946. * Loads the node definitions from the given URL.
  51947. *
  51948. * @param {string} url - The path/URL of the file to be loaded.
  51949. * @param {Function} onLoad - Will be called when load completes.
  51950. * @param {Function} onProgress - Will be called while load progresses.
  51951. * @param {Function} onError - Will be called when errors are thrown during the loading process.
  51952. */
  51953. load( url, onLoad, onProgress, onError ) {
  51954. const loader = new FileLoader( this.manager );
  51955. loader.setPath( this.path );
  51956. loader.setRequestHeader( this.requestHeader );
  51957. loader.setWithCredentials( this.withCredentials );
  51958. loader.load( url, ( text ) => {
  51959. try {
  51960. onLoad( this.parse( JSON.parse( text ) ) );
  51961. } catch ( e ) {
  51962. if ( onError ) {
  51963. onError( e );
  51964. } else {
  51965. console.error( e );
  51966. }
  51967. this.manager.itemError( url );
  51968. }
  51969. }, onProgress, onError );
  51970. }
  51971. /**
  51972. * Parse the node dependencies for the loaded node.
  51973. *
  51974. * @param {Array<Object>} [json] - The JSON definition
  51975. * @return {Object<string,Node>} A dictionary with node dependencies.
  51976. */
  51977. parseNodes( json ) {
  51978. const nodes = {};
  51979. if ( json !== undefined ) {
  51980. for ( const nodeJSON of json ) {
  51981. const { uuid, type } = nodeJSON;
  51982. nodes[ uuid ] = this.createNodeFromType( type );
  51983. nodes[ uuid ].uuid = uuid;
  51984. }
  51985. const meta = { nodes, textures: this.textures };
  51986. for ( const nodeJSON of json ) {
  51987. nodeJSON.meta = meta;
  51988. const node = nodes[ nodeJSON.uuid ];
  51989. node.deserialize( nodeJSON );
  51990. delete nodeJSON.meta;
  51991. }
  51992. }
  51993. return nodes;
  51994. }
  51995. /**
  51996. * Parses the node from the given JSON.
  51997. *
  51998. * @param {Object} json - The JSON definition
  51999. * @param {string} json.type - The node type.
  52000. * @param {string} json.uuid - The node UUID.
  52001. * @param {Array<Object>} [json.nodes] - The node dependencies.
  52002. * @param {Object} [json.meta] - The meta data.
  52003. * @return {Node} The parsed node.
  52004. */
  52005. parse( json ) {
  52006. const node = this.createNodeFromType( json.type );
  52007. node.uuid = json.uuid;
  52008. const nodes = this.parseNodes( json.nodes );
  52009. const meta = { nodes, textures: this.textures };
  52010. json.meta = meta;
  52011. node.deserialize( json );
  52012. delete json.meta;
  52013. return node;
  52014. }
  52015. /**
  52016. * Defines the dictionary of textures.
  52017. *
  52018. * @param {Object<string,Texture>} value - The texture library defines as `<uuid,texture>`.
  52019. * @return {NodeLoader} A reference to this loader.
  52020. */
  52021. setTextures( value ) {
  52022. this.textures = value;
  52023. return this;
  52024. }
  52025. /**
  52026. * Defines the dictionary of node types.
  52027. *
  52028. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  52029. * @return {NodeLoader} A reference to this loader.
  52030. */
  52031. setNodes( value ) {
  52032. this.nodes = value;
  52033. return this;
  52034. }
  52035. /**
  52036. * Creates a node object from the given type.
  52037. *
  52038. * @param {string} type - The node type.
  52039. * @return {Node} The created node instance.
  52040. */
  52041. createNodeFromType( type ) {
  52042. if ( this.nodes[ type ] === undefined ) {
  52043. console.error( 'THREE.NodeLoader: Node type not found:', type );
  52044. return float();
  52045. }
  52046. return nodeObject( new this.nodes[ type ]() );
  52047. }
  52048. }
  52049. /**
  52050. * A special type of material loader for loading node materials.
  52051. *
  52052. * @augments MaterialLoader
  52053. */
  52054. class NodeMaterialLoader extends MaterialLoader {
  52055. /**
  52056. * Constructs a new node material loader.
  52057. *
  52058. * @param {LoadingManager} [manager] - A reference to a loading manager.
  52059. */
  52060. constructor( manager ) {
  52061. super( manager );
  52062. /**
  52063. * Represents a dictionary of node types.
  52064. *
  52065. * @type {Object<string,Node.constructor>}
  52066. */
  52067. this.nodes = {};
  52068. /**
  52069. * Represents a dictionary of node material types.
  52070. *
  52071. * @type {Object<string,NodeMaterial.constructor>}
  52072. */
  52073. this.nodeMaterials = {};
  52074. }
  52075. /**
  52076. * Parses the node material from the given JSON.
  52077. *
  52078. * @param {Object} json - The JSON definition
  52079. * @return {NodeMaterial}. The parsed material.
  52080. */
  52081. parse( json ) {
  52082. const material = super.parse( json );
  52083. const nodes = this.nodes;
  52084. const inputNodes = json.inputNodes;
  52085. for ( const property in inputNodes ) {
  52086. const uuid = inputNodes[ property ];
  52087. material[ property ] = nodes[ uuid ];
  52088. }
  52089. return material;
  52090. }
  52091. /**
  52092. * Defines the dictionary of node types.
  52093. *
  52094. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  52095. * @return {NodeLoader} A reference to this loader.
  52096. */
  52097. setNodes( value ) {
  52098. this.nodes = value;
  52099. return this;
  52100. }
  52101. /**
  52102. * Defines the dictionary of node material types.
  52103. *
  52104. * @param {Object<string,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  52105. * @return {NodeLoader} A reference to this loader.
  52106. */
  52107. setNodeMaterials( value ) {
  52108. this.nodeMaterials = value;
  52109. return this;
  52110. }
  52111. /**
  52112. * Creates a node material from the given type.
  52113. *
  52114. * @param {string} type - The node material type.
  52115. * @return {Node} The created node material instance.
  52116. */
  52117. createMaterialFromType( type ) {
  52118. const materialClass = this.nodeMaterials[ type ];
  52119. if ( materialClass !== undefined ) {
  52120. return new materialClass();
  52121. }
  52122. return super.createMaterialFromType( type );
  52123. }
  52124. }
  52125. /**
  52126. * A special type of object loader for loading 3D objects using
  52127. * node materials.
  52128. *
  52129. * @augments ObjectLoader
  52130. */
  52131. class NodeObjectLoader extends ObjectLoader {
  52132. /**
  52133. * Constructs a new node object loader.
  52134. *
  52135. * @param {LoadingManager} [manager] - A reference to a loading manager.
  52136. */
  52137. constructor( manager ) {
  52138. super( manager );
  52139. /**
  52140. * Represents a dictionary of node types.
  52141. *
  52142. * @type {Object<string,Node.constructor>}
  52143. */
  52144. this.nodes = {};
  52145. /**
  52146. * Represents a dictionary of node material types.
  52147. *
  52148. * @type {Object<string,NodeMaterial.constructor>}
  52149. */
  52150. this.nodeMaterials = {};
  52151. /**
  52152. * A reference to hold the `nodes` JSON property.
  52153. *
  52154. * @private
  52155. * @type {?Object[]}
  52156. */
  52157. this._nodesJSON = null;
  52158. }
  52159. /**
  52160. * Defines the dictionary of node types.
  52161. *
  52162. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  52163. * @return {NodeObjectLoader} A reference to this loader.
  52164. */
  52165. setNodes( value ) {
  52166. this.nodes = value;
  52167. return this;
  52168. }
  52169. /**
  52170. * Defines the dictionary of node material types.
  52171. *
  52172. * @param {Object<string,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  52173. * @return {NodeObjectLoader} A reference to this loader.
  52174. */
  52175. setNodeMaterials( value ) {
  52176. this.nodeMaterials = value;
  52177. return this;
  52178. }
  52179. /**
  52180. * Parses the node objects from the given JSON.
  52181. *
  52182. * @param {Object} json - The JSON definition
  52183. * @param {Function} onLoad - The onLoad callback function.
  52184. * @return {Object3D}. The parsed 3D object.
  52185. */
  52186. parse( json, onLoad ) {
  52187. this._nodesJSON = json.nodes;
  52188. const data = super.parse( json, onLoad );
  52189. this._nodesJSON = null; // dispose
  52190. return data;
  52191. }
  52192. /**
  52193. * Parses the node objects from the given JSON and textures.
  52194. *
  52195. * @param {Object[]} json - The JSON definition
  52196. * @param {Object<string,Texture>} textures - The texture library.
  52197. * @return {Object<string,Node>}. The parsed nodes.
  52198. */
  52199. parseNodes( json, textures ) {
  52200. if ( json !== undefined ) {
  52201. const loader = new NodeLoader();
  52202. loader.setNodes( this.nodes );
  52203. loader.setTextures( textures );
  52204. return loader.parseNodes( json );
  52205. }
  52206. return {};
  52207. }
  52208. /**
  52209. * Parses the node objects from the given JSON and textures.
  52210. *
  52211. * @param {Object} json - The JSON definition
  52212. * @param {Object<string,Texture>} textures - The texture library.
  52213. * @return {Object<string,NodeMaterial>}. The parsed materials.
  52214. */
  52215. parseMaterials( json, textures ) {
  52216. const materials = {};
  52217. if ( json !== undefined ) {
  52218. const nodes = this.parseNodes( this._nodesJSON, textures );
  52219. const loader = new NodeMaterialLoader();
  52220. loader.setTextures( textures );
  52221. loader.setNodes( nodes );
  52222. loader.setNodeMaterials( this.nodeMaterials );
  52223. for ( let i = 0, l = json.length; i < l; i ++ ) {
  52224. const data = json[ i ];
  52225. materials[ data.uuid ] = loader.parse( data );
  52226. }
  52227. }
  52228. return materials;
  52229. }
  52230. }
  52231. /**
  52232. * In earlier three.js versions, clipping was defined globally
  52233. * on the renderer or on material level. This special version of
  52234. * `THREE.Group` allows to encode the clipping state into the scene
  52235. * graph. Meaning if you create an instance of this group, all
  52236. * descendant 3D objects will be affected by the respective clipping
  52237. * planes.
  52238. *
  52239. * Note: `ClippingGroup` can only be used with `WebGPURenderer`.
  52240. *
  52241. * @augments Group
  52242. */
  52243. class ClippingGroup extends Group {
  52244. /**
  52245. * Constructs a new clipping group.
  52246. */
  52247. constructor() {
  52248. super();
  52249. /**
  52250. * This flag can be used for type testing.
  52251. *
  52252. * @type {boolean}
  52253. * @readonly
  52254. * @default true
  52255. */
  52256. this.isClippingGroup = true;
  52257. /**
  52258. * An array with clipping planes.
  52259. *
  52260. * @type {Array<Plane>}
  52261. */
  52262. this.clippingPlanes = [];
  52263. /**
  52264. * Whether clipping should be enabled or not.
  52265. *
  52266. * @type {boolean}
  52267. * @default true
  52268. */
  52269. this.enabled = true;
  52270. /**
  52271. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  52272. *
  52273. * @type {boolean}
  52274. * @default false
  52275. */
  52276. this.clipIntersection = false;
  52277. /**
  52278. * Whether shadows should be clipped or not.
  52279. *
  52280. * @type {boolean}
  52281. * @default false
  52282. */
  52283. this.clipShadows = false;
  52284. }
  52285. }
  52286. export { ACESFilmicToneMapping, AONode, AddEquation, AddOperation, AdditiveBlending, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightNode, AnalyticLightNode, ArrayCamera, ArrayElementNode, ArrayNode, AssignNode, AttributeNode, BackSide, BasicEnvironmentNode, BasicShadowMap, BatchNode, 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, EquirectUVNode, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, 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, MatcapUVNode, 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, SubtractEquation, SubtractiveBlending, TSL, TangentSpaceNormalMap, TempNode, Texture, Texture3DNode, TextureNode, TextureSizeNode, ToneMappingNode, ToonOutlinePassNode, TriplanarTexturesNode, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, UniformArrayNode, UniformGroupNode, UniformNode, UnsignedByteType, 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, shaderStages, vectorComponents };
粤ICP备19079148号