three.webgpu.js 1.7 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364
  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, DoubleSide, Euler, CubeTexture, CubeReflectionMapping, CubeRefractionMapping, TangentSpaceNormalMap, ObjectSpaceNormalMap, InstancedInterleavedBuffer, InstancedBufferAttribute, DataArrayTexture, FloatType, FramebufferTexture, LinearMipmapLinearFilter, DepthTexture, Material, NormalBlending, LineBasicMaterial, LineDashedMaterial, NoBlending, MeshNormalMaterial, SRGBColorSpace, WebGLCubeRenderTarget, BoxGeometry, Mesh, Scene, LinearFilter, CubeCamera, EquirectangularReflectionMapping, EquirectangularRefractionMapping, AddOperation, MixOperation, MultiplyOperation, MeshBasicMaterial, MeshLambertMaterial, MeshPhongMaterial, OrthographicCamera, PerspectiveCamera, RenderTarget, LinearSRGBColorSpace, RGBAFormat, HalfFloatType, CubeUVReflectionMapping, BufferGeometry, BufferAttribute, MeshStandardMaterial, MeshPhysicalMaterial, MeshToonMaterial, MeshMatcapMaterial, SpriteMaterial, PointsMaterial, ShadowMaterial, Uint32BufferAttribute, Uint16BufferAttribute, arrayNeedsUint32, Camera, DepthStencilFormat, DepthFormat, UnsignedInt248Type, UnsignedByteType, Plane, Object3D, LinearMipMapLinearFilter, Float32BufferAttribute, UVMapping, VSMShadowMap, LessCompare, RGFormat, BasicShadowMap, SphereGeometry, LinearMipmapNearestFilter, NearestMipmapLinearFilter, Float16BufferAttribute, REVISION, ArrayCamera, PlaneGeometry, FrontSide, CustomBlending, AddEquation, ZeroFactor, CylinderGeometry, Quaternion, WebXRController, RAD2DEG, PCFShadowMap, FrustumArray, Frustum, DataTexture, RedIntegerFormat, RedFormat, ShortType, ByteType, UnsignedShortType, RGIntegerFormat, RGBIntegerFormat, RGBFormat, RGBAIntegerFormat, 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, Timer, 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. * A WeakMap to cache lights data for node materials.
  66. * Cache lights data by render ID to avoid unnecessary recalculations.
  67. *
  68. * @private
  69. * @type {WeakMap<LightsNode,Object>}
  70. */
  71. const _lightsCache = new WeakMap();
  72. /**
  73. * This class is used by {@link WebGPURenderer} as management component.
  74. * It's primary purpose is to determine whether render objects require a
  75. * refresh right before they are going to be rendered or not.
  76. */
  77. class NodeMaterialObserver {
  78. /**
  79. * Constructs a new node material observer.
  80. *
  81. * @param {NodeBuilder} builder - The node builder.
  82. */
  83. constructor( builder ) {
  84. /**
  85. * A node material can be used by more than one render object so the
  86. * monitor must maintain a list of render objects.
  87. *
  88. * @type {WeakMap<RenderObject,Object>}
  89. */
  90. this.renderObjects = new WeakMap();
  91. /**
  92. * Whether the material uses node objects or not.
  93. *
  94. * @type {boolean}
  95. */
  96. this.hasNode = this.containsNode( builder );
  97. /**
  98. * Whether the node builder's 3D object is animated or not.
  99. *
  100. * @type {boolean}
  101. */
  102. this.hasAnimation = builder.object.isSkinnedMesh === true;
  103. /**
  104. * A list of all possible material uniforms
  105. *
  106. * @type {Array<string>}
  107. */
  108. this.refreshUniforms = refreshUniforms;
  109. /**
  110. * Holds the current render ID from the node frame.
  111. *
  112. * @type {number}
  113. * @default 0
  114. */
  115. this.renderId = 0;
  116. }
  117. /**
  118. * Returns `true` if the given render object is verified for the first time of this observer.
  119. *
  120. * @param {RenderObject} renderObject - The render object.
  121. * @return {boolean} Whether the given render object is verified for the first time of this observer.
  122. */
  123. firstInitialization( renderObject ) {
  124. const hasInitialized = this.renderObjects.has( renderObject );
  125. if ( hasInitialized === false ) {
  126. this.getRenderObjectData( renderObject );
  127. return true;
  128. }
  129. return false;
  130. }
  131. /**
  132. * Returns `true` if the current rendering produces motion vectors.
  133. *
  134. * @param {Renderer} renderer - The renderer.
  135. * @return {boolean} Whether the current rendering produces motion vectors or not.
  136. */
  137. needsVelocity( renderer ) {
  138. const mrt = renderer.getMRT();
  139. return ( mrt !== null && mrt.has( 'velocity' ) );
  140. }
  141. /**
  142. * Returns monitoring data for the given render object.
  143. *
  144. * @param {RenderObject} renderObject - The render object.
  145. * @return {Object} The monitoring data.
  146. */
  147. getRenderObjectData( renderObject ) {
  148. let data = this.renderObjects.get( renderObject );
  149. if ( data === undefined ) {
  150. const { geometry, material, object } = renderObject;
  151. data = {
  152. material: this.getMaterialData( material ),
  153. geometry: {
  154. id: geometry.id,
  155. attributes: this.getAttributesData( geometry.attributes ),
  156. indexVersion: geometry.index ? geometry.index.version : null,
  157. drawRange: { start: geometry.drawRange.start, count: geometry.drawRange.count }
  158. },
  159. worldMatrix: object.matrixWorld.clone()
  160. };
  161. if ( object.center ) {
  162. data.center = object.center.clone();
  163. }
  164. if ( object.morphTargetInfluences ) {
  165. data.morphTargetInfluences = object.morphTargetInfluences.slice();
  166. }
  167. if ( renderObject.bundle !== null ) {
  168. data.version = renderObject.bundle.version;
  169. }
  170. if ( data.material.transmission > 0 ) {
  171. const { width, height } = renderObject.context;
  172. data.bufferWidth = width;
  173. data.bufferHeight = height;
  174. }
  175. data.lights = this.getLightsData( renderObject.lightsNode.getLights() );
  176. this.renderObjects.set( renderObject, data );
  177. }
  178. return data;
  179. }
  180. /**
  181. * Returns an attribute data structure holding the attributes versions for
  182. * monitoring.
  183. *
  184. * @param {Object} attributes - The geometry attributes.
  185. * @return {Object} An object for monitoring the versions of attributes.
  186. */
  187. getAttributesData( attributes ) {
  188. const attributesData = {};
  189. for ( const name in attributes ) {
  190. const attribute = attributes[ name ];
  191. attributesData[ name ] = {
  192. version: attribute.version
  193. };
  194. }
  195. return attributesData;
  196. }
  197. /**
  198. * Returns `true` if the node builder's material uses
  199. * node properties.
  200. *
  201. * @param {NodeBuilder} builder - The current node builder.
  202. * @return {boolean} Whether the node builder's material uses node properties or not.
  203. */
  204. containsNode( builder ) {
  205. const material = builder.material;
  206. for ( const property in material ) {
  207. if ( material[ property ] && material[ property ].isNode )
  208. return true;
  209. }
  210. if ( builder.renderer.overrideNodes.modelViewMatrix !== null || builder.renderer.overrideNodes.modelNormalViewMatrix !== null )
  211. return true;
  212. return false;
  213. }
  214. /**
  215. * Returns a material data structure holding the material property values for
  216. * monitoring.
  217. *
  218. * @param {Material} material - The material.
  219. * @return {Object} An object for monitoring material properties.
  220. */
  221. getMaterialData( material ) {
  222. const data = {};
  223. for ( const property of this.refreshUniforms ) {
  224. const value = material[ property ];
  225. if ( value === null || value === undefined ) continue;
  226. if ( typeof value === 'object' && value.clone !== undefined ) {
  227. if ( value.isTexture === true ) {
  228. data[ property ] = { id: value.id, version: value.version };
  229. } else {
  230. data[ property ] = value.clone();
  231. }
  232. } else {
  233. data[ property ] = value;
  234. }
  235. }
  236. return data;
  237. }
  238. /**
  239. * Returns `true` if the given render object has not changed its state.
  240. *
  241. * @param {RenderObject} renderObject - The render object.
  242. * @param {Array<Light>} lightsData - The current material lights.
  243. * @return {boolean} Whether the given render object has changed its state or not.
  244. */
  245. equals( renderObject, lightsData ) {
  246. const { object, material, geometry } = renderObject;
  247. const renderObjectData = this.getRenderObjectData( renderObject );
  248. // world matrix
  249. if ( renderObjectData.worldMatrix.equals( object.matrixWorld ) !== true ) {
  250. renderObjectData.worldMatrix.copy( object.matrixWorld );
  251. return false;
  252. }
  253. // material
  254. const materialData = renderObjectData.material;
  255. for ( const property in materialData ) {
  256. const value = materialData[ property ];
  257. const mtlValue = material[ property ];
  258. if ( value.equals !== undefined ) {
  259. if ( value.equals( mtlValue ) === false ) {
  260. value.copy( mtlValue );
  261. return false;
  262. }
  263. } else if ( mtlValue.isTexture === true ) {
  264. if ( value.id !== mtlValue.id || value.version !== mtlValue.version ) {
  265. value.id = mtlValue.id;
  266. value.version = mtlValue.version;
  267. return false;
  268. }
  269. } else if ( value !== mtlValue ) {
  270. materialData[ property ] = mtlValue;
  271. return false;
  272. }
  273. }
  274. if ( materialData.transmission > 0 ) {
  275. const { width, height } = renderObject.context;
  276. if ( renderObjectData.bufferWidth !== width || renderObjectData.bufferHeight !== height ) {
  277. renderObjectData.bufferWidth = width;
  278. renderObjectData.bufferHeight = height;
  279. return false;
  280. }
  281. }
  282. // geometry
  283. const storedGeometryData = renderObjectData.geometry;
  284. const attributes = geometry.attributes;
  285. const storedAttributes = storedGeometryData.attributes;
  286. const storedAttributeNames = Object.keys( storedAttributes );
  287. const currentAttributeNames = Object.keys( attributes );
  288. if ( storedGeometryData.id !== geometry.id ) {
  289. storedGeometryData.id = geometry.id;
  290. return false;
  291. }
  292. if ( storedAttributeNames.length !== currentAttributeNames.length ) {
  293. renderObjectData.geometry.attributes = this.getAttributesData( attributes );
  294. return false;
  295. }
  296. // compare each attribute
  297. for ( const name of storedAttributeNames ) {
  298. const storedAttributeData = storedAttributes[ name ];
  299. const attribute = attributes[ name ];
  300. if ( attribute === undefined ) {
  301. // attribute was removed
  302. delete storedAttributes[ name ];
  303. return false;
  304. }
  305. if ( storedAttributeData.version !== attribute.version ) {
  306. storedAttributeData.version = attribute.version;
  307. return false;
  308. }
  309. }
  310. // check index
  311. const index = geometry.index;
  312. const storedIndexVersion = storedGeometryData.indexVersion;
  313. const currentIndexVersion = index ? index.version : null;
  314. if ( storedIndexVersion !== currentIndexVersion ) {
  315. storedGeometryData.indexVersion = currentIndexVersion;
  316. return false;
  317. }
  318. // check drawRange
  319. if ( storedGeometryData.drawRange.start !== geometry.drawRange.start || storedGeometryData.drawRange.count !== geometry.drawRange.count ) {
  320. storedGeometryData.drawRange.start = geometry.drawRange.start;
  321. storedGeometryData.drawRange.count = geometry.drawRange.count;
  322. return false;
  323. }
  324. // morph targets
  325. if ( renderObjectData.morphTargetInfluences ) {
  326. let morphChanged = false;
  327. for ( let i = 0; i < renderObjectData.morphTargetInfluences.length; i ++ ) {
  328. if ( renderObjectData.morphTargetInfluences[ i ] !== object.morphTargetInfluences[ i ] ) {
  329. morphChanged = true;
  330. }
  331. }
  332. if ( morphChanged ) return true;
  333. }
  334. // lights
  335. if ( renderObjectData.lights ) {
  336. for ( let i = 0; i < lightsData.length; i ++ ) {
  337. if ( renderObjectData.lights[ i ].map !== lightsData[ i ].map ) {
  338. return false;
  339. }
  340. }
  341. }
  342. // center
  343. if ( renderObjectData.center ) {
  344. if ( renderObjectData.center.equals( object.center ) === false ) {
  345. renderObjectData.center.copy( object.center );
  346. return true;
  347. }
  348. }
  349. // bundle
  350. if ( renderObject.bundle !== null ) {
  351. renderObjectData.version = renderObject.bundle.version;
  352. }
  353. return true;
  354. }
  355. /**
  356. * Returns the lights data for the given material lights.
  357. *
  358. * @param {Array<Light>} materialLights - The material lights.
  359. * @return {Array<Object>} The lights data for the given material lights.
  360. */
  361. getLightsData( materialLights ) {
  362. const lights = [];
  363. for ( const light of materialLights ) {
  364. if ( light.isSpotLight === true && light.map !== null ) {
  365. // only add lights that have a map
  366. lights.push( { map: light.map.version } );
  367. }
  368. }
  369. return lights;
  370. }
  371. /**
  372. * Returns the lights for the given lights node and render ID.
  373. *
  374. * @param {LightsNode} lightsNode - The lights node.
  375. * @param {number} renderId - The render ID.
  376. * @return {Array} The lights for the given lights node and render ID.
  377. */
  378. getLights( lightsNode, renderId ) {
  379. if ( _lightsCache.has( lightsNode ) ) {
  380. const cached = _lightsCache.get( lightsNode );
  381. if ( cached.renderId === renderId ) {
  382. return cached.lightsData;
  383. }
  384. }
  385. const lightsData = this.getLightsData( lightsNode.getLights() );
  386. _lightsCache.set( lightsNode, { renderId, lightsData } );
  387. return lightsData;
  388. }
  389. /**
  390. * Checks if the given render object requires a refresh.
  391. *
  392. * @param {RenderObject} renderObject - The render object.
  393. * @param {NodeFrame} nodeFrame - The current node frame.
  394. * @return {boolean} Whether the given render object requires a refresh or not.
  395. */
  396. needsRefresh( renderObject, nodeFrame ) {
  397. if ( this.hasNode || this.hasAnimation || this.firstInitialization( renderObject ) || this.needsVelocity( nodeFrame.renderer ) )
  398. return true;
  399. const { renderId } = nodeFrame;
  400. if ( this.renderId !== renderId ) {
  401. this.renderId = renderId;
  402. return true;
  403. }
  404. const isStatic = renderObject.object.static === true;
  405. const isBundle = renderObject.bundle !== null && renderObject.bundle.static === true && this.getRenderObjectData( renderObject ).version === renderObject.bundle.version;
  406. if ( isStatic || isBundle )
  407. return false;
  408. const lightsData = this.getLights( renderObject.lightsNode, renderId );
  409. const notEqual = this.equals( renderObject, lightsData ) !== true;
  410. return notEqual;
  411. }
  412. }
  413. // cyrb53 (c) 2018 bryc (github.com/bryc). License: Public domain. Attribution appreciated.
  414. // A fast and simple 64-bit (or 53-bit) string hash function with decent collision resistance.
  415. // Largely inspired by MurmurHash2/3, but with a focus on speed/simplicity.
  416. // See https://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript/52171480#52171480
  417. // https://github.com/bryc/code/blob/master/jshash/experimental/cyrb53.js
  418. function cyrb53( value, seed = 0 ) {
  419. let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;
  420. if ( value instanceof Array ) {
  421. for ( let i = 0, val; i < value.length; i ++ ) {
  422. val = value[ i ];
  423. h1 = Math.imul( h1 ^ val, 2654435761 );
  424. h2 = Math.imul( h2 ^ val, 1597334677 );
  425. }
  426. } else {
  427. for ( let i = 0, ch; i < value.length; i ++ ) {
  428. ch = value.charCodeAt( i );
  429. h1 = Math.imul( h1 ^ ch, 2654435761 );
  430. h2 = Math.imul( h2 ^ ch, 1597334677 );
  431. }
  432. }
  433. h1 = Math.imul( h1 ^ ( h1 >>> 16 ), 2246822507 );
  434. h1 ^= Math.imul( h2 ^ ( h2 >>> 13 ), 3266489909 );
  435. h2 = Math.imul( h2 ^ ( h2 >>> 16 ), 2246822507 );
  436. h2 ^= Math.imul( h1 ^ ( h1 >>> 13 ), 3266489909 );
  437. return 4294967296 * ( 2097151 & h2 ) + ( h1 >>> 0 );
  438. }
  439. /**
  440. * Computes a hash for the given string.
  441. *
  442. * @method
  443. * @param {string} str - The string to be hashed.
  444. * @return {number} The hash.
  445. */
  446. const hashString = ( str ) => cyrb53( str );
  447. /**
  448. * Computes a hash for the given array.
  449. *
  450. * @method
  451. * @param {Array<number>} array - The array to be hashed.
  452. * @return {number} The hash.
  453. */
  454. const hashArray = ( array ) => cyrb53( array );
  455. /**
  456. * Computes a hash for the given list of parameters.
  457. *
  458. * @method
  459. * @param {...number} params - A list of parameters.
  460. * @return {number} The hash.
  461. */
  462. const hash$1 = ( ...params ) => cyrb53( params );
  463. /**
  464. * Computes a cache key for the given node.
  465. *
  466. * @method
  467. * @param {Object|Node} object - The object to be hashed.
  468. * @param {boolean} [force=false] - Whether to force a cache key computation or not.
  469. * @return {number} The hash.
  470. */
  471. function getCacheKey$1( object, force = false ) {
  472. const values = [];
  473. if ( object.isNode === true ) {
  474. values.push( object.id );
  475. object = object.getSelf();
  476. }
  477. for ( const { property, childNode } of getNodeChildren( object ) ) {
  478. values.push( cyrb53( property.slice( 0, -4 ) ), childNode.getCacheKey( force ) );
  479. }
  480. return cyrb53( values );
  481. }
  482. /**
  483. * This generator function can be used to iterate over the node children
  484. * of the given object.
  485. *
  486. * @generator
  487. * @param {Object} node - The object to be hashed.
  488. * @param {boolean} [toJSON=false] - Whether to return JSON or not.
  489. * @yields {Object} A result node holding the property, index (if available) and the child node.
  490. */
  491. function* getNodeChildren( node, toJSON = false ) {
  492. for ( const property in node ) {
  493. // Ignore private properties.
  494. if ( property.startsWith( '_' ) === true ) continue;
  495. const object = node[ property ];
  496. if ( Array.isArray( object ) === true ) {
  497. for ( let i = 0; i < object.length; i ++ ) {
  498. const child = object[ i ];
  499. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  500. yield { property, index: i, childNode: child };
  501. }
  502. }
  503. } else if ( object && object.isNode === true ) {
  504. yield { property, childNode: object };
  505. } else if ( typeof object === 'object' ) {
  506. for ( const subProperty in object ) {
  507. const child = object[ subProperty ];
  508. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  509. yield { property, index: subProperty, childNode: child };
  510. }
  511. }
  512. }
  513. }
  514. }
  515. const typeFromLength = /*@__PURE__*/ new Map( [
  516. [ 1, 'float' ],
  517. [ 2, 'vec2' ],
  518. [ 3, 'vec3' ],
  519. [ 4, 'vec4' ],
  520. [ 9, 'mat3' ],
  521. [ 16, 'mat4' ]
  522. ] );
  523. const dataFromObject = /*@__PURE__*/ new WeakMap();
  524. /**
  525. * Returns the data type for the given the length.
  526. *
  527. * @method
  528. * @param {number} length - The length.
  529. * @return {string} The data type.
  530. */
  531. function getTypeFromLength( length ) {
  532. return typeFromLength.get( length );
  533. }
  534. /**
  535. * Returns the typed array for the given data type.
  536. *
  537. * @method
  538. * @param {string} type - The data type.
  539. * @return {TypedArray} The typed array.
  540. */
  541. function getTypedArrayFromType( type ) {
  542. // Handle component type for vectors and matrices
  543. if ( /[iu]?vec\d/.test( type ) ) {
  544. // Handle int vectors
  545. if ( type.startsWith( 'ivec' ) ) return Int32Array;
  546. // Handle uint vectors
  547. if ( type.startsWith( 'uvec' ) ) return Uint32Array;
  548. // Default to float vectors
  549. return Float32Array;
  550. }
  551. // Handle matrices (always float)
  552. if ( /mat\d/.test( type ) ) return Float32Array;
  553. // Basic types
  554. if ( /float/.test( type ) ) return Float32Array;
  555. if ( /uint/.test( type ) ) return Uint32Array;
  556. if ( /int/.test( type ) ) return Int32Array;
  557. throw new Error( `THREE.NodeUtils: Unsupported type: ${type}` );
  558. }
  559. /**
  560. * Returns the length for the given data type.
  561. *
  562. * @method
  563. * @param {string} type - The data type.
  564. * @return {number} The length.
  565. */
  566. function getLengthFromType( type ) {
  567. if ( /float|int|uint/.test( type ) ) return 1;
  568. if ( /vec2/.test( type ) ) return 2;
  569. if ( /vec3/.test( type ) ) return 3;
  570. if ( /vec4/.test( type ) ) return 4;
  571. if ( /mat2/.test( type ) ) return 4;
  572. if ( /mat3/.test( type ) ) return 9;
  573. if ( /mat4/.test( type ) ) return 16;
  574. console.error( 'THREE.TSL: Unsupported type:', type );
  575. }
  576. /**
  577. * Returns the gpu memory length for the given data type.
  578. *
  579. * @method
  580. * @param {string} type - The data type.
  581. * @return {number} The length.
  582. */
  583. function getMemoryLengthFromType( type ) {
  584. if ( /float|int|uint/.test( type ) ) return 1;
  585. if ( /vec2/.test( type ) ) return 2;
  586. if ( /vec3/.test( type ) ) return 3;
  587. if ( /vec4/.test( type ) ) return 4;
  588. if ( /mat2/.test( type ) ) return 4;
  589. if ( /mat3/.test( type ) ) return 12;
  590. if ( /mat4/.test( type ) ) return 16;
  591. console.error( 'THREE.TSL: Unsupported type:', type );
  592. }
  593. /**
  594. * Returns the byte boundary for the given data type.
  595. *
  596. * @method
  597. * @param {string} type - The data type.
  598. * @return {number} The byte boundary.
  599. */
  600. function getByteBoundaryFromType( type ) {
  601. if ( /float|int|uint/.test( type ) ) return 4;
  602. if ( /vec2/.test( type ) ) return 8;
  603. if ( /vec3/.test( type ) ) return 16;
  604. if ( /vec4/.test( type ) ) return 16;
  605. if ( /mat2/.test( type ) ) return 8;
  606. if ( /mat3/.test( type ) ) return 48;
  607. if ( /mat4/.test( type ) ) return 64;
  608. console.error( 'THREE.TSL: Unsupported type:', type );
  609. }
  610. /**
  611. * Returns the data type for the given value.
  612. *
  613. * @method
  614. * @param {any} value - The value.
  615. * @return {?string} The data type.
  616. */
  617. function getValueType( value ) {
  618. if ( value === undefined || value === null ) return null;
  619. const typeOf = typeof value;
  620. if ( value.isNode === true ) {
  621. return 'node';
  622. } else if ( typeOf === 'number' ) {
  623. return 'float';
  624. } else if ( typeOf === 'boolean' ) {
  625. return 'bool';
  626. } else if ( typeOf === 'string' ) {
  627. return 'string';
  628. } else if ( typeOf === 'function' ) {
  629. return 'shader';
  630. } else if ( value.isVector2 === true ) {
  631. return 'vec2';
  632. } else if ( value.isVector3 === true ) {
  633. return 'vec3';
  634. } else if ( value.isVector4 === true ) {
  635. return 'vec4';
  636. } else if ( value.isMatrix2 === true ) {
  637. return 'mat2';
  638. } else if ( value.isMatrix3 === true ) {
  639. return 'mat3';
  640. } else if ( value.isMatrix4 === true ) {
  641. return 'mat4';
  642. } else if ( value.isColor === true ) {
  643. return 'color';
  644. } else if ( value instanceof ArrayBuffer ) {
  645. return 'ArrayBuffer';
  646. }
  647. return null;
  648. }
  649. /**
  650. * Returns the value/object for the given data type and parameters.
  651. *
  652. * @method
  653. * @param {string} type - The given type.
  654. * @param {...any} params - A parameter list.
  655. * @return {any} The value/object.
  656. */
  657. function getValueFromType( type, ...params ) {
  658. const last4 = type ? type.slice( -4 ) : undefined;
  659. if ( params.length === 1 ) { // ensure same behaviour as in NodeBuilder.format()
  660. if ( last4 === 'vec2' ) params = [ params[ 0 ], params[ 0 ] ];
  661. else if ( last4 === 'vec3' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ] ];
  662. else if ( last4 === 'vec4' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ], params[ 0 ] ];
  663. }
  664. if ( type === 'color' ) {
  665. return new Color( ...params );
  666. } else if ( last4 === 'vec2' ) {
  667. return new Vector2( ...params );
  668. } else if ( last4 === 'vec3' ) {
  669. return new Vector3( ...params );
  670. } else if ( last4 === 'vec4' ) {
  671. return new Vector4( ...params );
  672. } else if ( last4 === 'mat2' ) {
  673. return new Matrix2( ...params );
  674. } else if ( last4 === 'mat3' ) {
  675. return new Matrix3( ...params );
  676. } else if ( last4 === 'mat4' ) {
  677. return new Matrix4( ...params );
  678. } else if ( type === 'bool' ) {
  679. return params[ 0 ] || false;
  680. } else if ( ( type === 'float' ) || ( type === 'int' ) || ( type === 'uint' ) ) {
  681. return params[ 0 ] || 0;
  682. } else if ( type === 'string' ) {
  683. return params[ 0 ] || '';
  684. } else if ( type === 'ArrayBuffer' ) {
  685. return base64ToArrayBuffer( params[ 0 ] );
  686. }
  687. return null;
  688. }
  689. /**
  690. * Gets the object data that can be shared between different rendering steps.
  691. *
  692. * @param {Object} object - The object to get the data for.
  693. * @return {Object} The object data.
  694. */
  695. function getDataFromObject( object ) {
  696. let data = dataFromObject.get( object );
  697. if ( data === undefined ) {
  698. data = {};
  699. dataFromObject.set( object, data );
  700. }
  701. return data;
  702. }
  703. /**
  704. * Converts the given array buffer to a Base64 string.
  705. *
  706. * @method
  707. * @param {ArrayBuffer} arrayBuffer - The array buffer.
  708. * @return {string} The Base64 string.
  709. */
  710. function arrayBufferToBase64( arrayBuffer ) {
  711. let chars = '';
  712. const array = new Uint8Array( arrayBuffer );
  713. for ( let i = 0; i < array.length; i ++ ) {
  714. chars += String.fromCharCode( array[ i ] );
  715. }
  716. return btoa( chars );
  717. }
  718. /**
  719. * Converts the given Base64 string to an array buffer.
  720. *
  721. * @method
  722. * @param {string} base64 - The Base64 string.
  723. * @return {ArrayBuffer} The array buffer.
  724. */
  725. function base64ToArrayBuffer( base64 ) {
  726. return Uint8Array.from( atob( base64 ), c => c.charCodeAt( 0 ) ).buffer;
  727. }
  728. var NodeUtils = /*#__PURE__*/Object.freeze({
  729. __proto__: null,
  730. arrayBufferToBase64: arrayBufferToBase64,
  731. base64ToArrayBuffer: base64ToArrayBuffer,
  732. getByteBoundaryFromType: getByteBoundaryFromType,
  733. getCacheKey: getCacheKey$1,
  734. getDataFromObject: getDataFromObject,
  735. getLengthFromType: getLengthFromType,
  736. getMemoryLengthFromType: getMemoryLengthFromType,
  737. getNodeChildren: getNodeChildren,
  738. getTypeFromLength: getTypeFromLength,
  739. getTypedArrayFromType: getTypedArrayFromType,
  740. getValueFromType: getValueFromType,
  741. getValueType: getValueType,
  742. hash: hash$1,
  743. hashArray: hashArray,
  744. hashString: hashString
  745. });
  746. /**
  747. * Possible shader stages.
  748. *
  749. * @property {string} VERTEX The vertex shader stage.
  750. * @property {string} FRAGMENT The fragment shader stage.
  751. */
  752. const NodeShaderStage = {
  753. VERTEX: 'vertex',
  754. FRAGMENT: 'fragment'
  755. };
  756. /**
  757. * Update types of a node.
  758. *
  759. * @property {string} NONE The update method is not executed.
  760. * @property {string} FRAME The update method is executed per frame.
  761. * @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.
  762. * @property {string} OBJECT The update method is executed per {@link Object3D} that uses the node for rendering.
  763. */
  764. const NodeUpdateType = {
  765. NONE: 'none',
  766. FRAME: 'frame',
  767. RENDER: 'render',
  768. OBJECT: 'object'
  769. };
  770. /**
  771. * Data types of a node.
  772. *
  773. * @property {string} BOOLEAN Boolean type.
  774. * @property {string} INTEGER Integer type.
  775. * @property {string} FLOAT Float type.
  776. * @property {string} VECTOR2 Two-dimensional vector type.
  777. * @property {string} VECTOR3 Three-dimensional vector type.
  778. * @property {string} VECTOR4 Four-dimensional vector type.
  779. * @property {string} MATRIX2 2x2 matrix type.
  780. * @property {string} MATRIX3 3x3 matrix type.
  781. * @property {string} MATRIX4 4x4 matrix type.
  782. */
  783. const NodeType = {
  784. BOOLEAN: 'bool',
  785. INTEGER: 'int',
  786. FLOAT: 'float',
  787. VECTOR2: 'vec2',
  788. VECTOR3: 'vec3',
  789. VECTOR4: 'vec4',
  790. MATRIX2: 'mat2',
  791. MATRIX3: 'mat3',
  792. MATRIX4: 'mat4'
  793. };
  794. /**
  795. * Access types of a node. These are relevant for compute and storage usage.
  796. *
  797. * @property {string} READ_ONLY Read-only access
  798. * @property {string} WRITE_ONLY Write-only access.
  799. * @property {string} READ_WRITE Read and write access.
  800. */
  801. const NodeAccess = {
  802. READ_ONLY: 'readOnly',
  803. WRITE_ONLY: 'writeOnly',
  804. READ_WRITE: 'readWrite',
  805. };
  806. const defaultShaderStages = [ 'fragment', 'vertex' ];
  807. const defaultBuildStages = [ 'setup', 'analyze', 'generate' ];
  808. const shaderStages = [ ...defaultShaderStages, 'compute' ];
  809. const vectorComponents = [ 'x', 'y', 'z', 'w' ];
  810. const _parentBuildStage = {
  811. analyze: 'setup',
  812. generate: 'analyze'
  813. };
  814. let _nodeId = 0;
  815. /**
  816. * Base class for all nodes.
  817. *
  818. * @augments EventDispatcher
  819. */
  820. class Node extends EventDispatcher {
  821. static get type() {
  822. return 'Node';
  823. }
  824. /**
  825. * Constructs a new node.
  826. *
  827. * @param {?string} nodeType - The node type.
  828. */
  829. constructor( nodeType = null ) {
  830. super();
  831. /**
  832. * The node type. This represents the result type of the node (e.g. `float` or `vec3`).
  833. *
  834. * @type {?string}
  835. * @default null
  836. */
  837. this.nodeType = nodeType;
  838. /**
  839. * The update type of the node's {@link Node#update} method. Possible values are listed in {@link NodeUpdateType}.
  840. *
  841. * @type {string}
  842. * @default 'none'
  843. */
  844. this.updateType = NodeUpdateType.NONE;
  845. /**
  846. * The update type of the node's {@link Node#updateBefore} method. Possible values are listed in {@link NodeUpdateType}.
  847. *
  848. * @type {string}
  849. * @default 'none'
  850. */
  851. this.updateBeforeType = NodeUpdateType.NONE;
  852. /**
  853. * The update type of the node's {@link Node#updateAfter} method. Possible values are listed in {@link NodeUpdateType}.
  854. *
  855. * @type {string}
  856. * @default 'none'
  857. */
  858. this.updateAfterType = NodeUpdateType.NONE;
  859. /**
  860. * The UUID of the node.
  861. *
  862. * @type {string}
  863. * @readonly
  864. */
  865. this.uuid = MathUtils.generateUUID();
  866. /**
  867. * The version of the node. The version automatically is increased when {@link Node#needsUpdate} is set to `true`.
  868. *
  869. * @type {number}
  870. * @readonly
  871. * @default 0
  872. */
  873. this.version = 0;
  874. /**
  875. * Whether this node is global or not. This property is relevant for the internal
  876. * node caching system. All nodes which should be declared just once should
  877. * set this flag to `true` (a typical example is {@link AttributeNode}).
  878. *
  879. * @type {boolean}
  880. * @default false
  881. */
  882. this.global = false;
  883. /**
  884. * Create a list of parents for this node during the build process.
  885. *
  886. * @type {boolean}
  887. * @default false
  888. */
  889. this.parents = false;
  890. /**
  891. * This flag can be used for type testing.
  892. *
  893. * @type {boolean}
  894. * @readonly
  895. * @default true
  896. */
  897. this.isNode = true;
  898. // private
  899. /**
  900. * The cache key of this node.
  901. *
  902. * @private
  903. * @type {?number}
  904. * @default null
  905. */
  906. this._cacheKey = null;
  907. /**
  908. * The cache key 's version.
  909. *
  910. * @private
  911. * @type {number}
  912. * @default 0
  913. */
  914. this._cacheKeyVersion = 0;
  915. Object.defineProperty( this, 'id', { value: _nodeId ++ } );
  916. }
  917. /**
  918. * Set this property to `true` when the node should be regenerated.
  919. *
  920. * @type {boolean}
  921. * @default false
  922. * @param {boolean} value
  923. */
  924. set needsUpdate( value ) {
  925. if ( value === true ) {
  926. this.version ++;
  927. }
  928. }
  929. /**
  930. * The type of the class. The value is usually the constructor name.
  931. *
  932. * @type {string}
  933. * @readonly
  934. */
  935. get type() {
  936. return this.constructor.type;
  937. }
  938. /**
  939. * Convenient method for defining {@link Node#update}.
  940. *
  941. * @param {Function} callback - The update method.
  942. * @param {string} updateType - The update type.
  943. * @return {Node} A reference to this node.
  944. */
  945. onUpdate( callback, updateType ) {
  946. this.updateType = updateType;
  947. this.update = callback.bind( this.getSelf() );
  948. return this;
  949. }
  950. /**
  951. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  952. * this method automatically sets the update type to `FRAME`.
  953. *
  954. * @param {Function} callback - The update method.
  955. * @return {Node} A reference to this node.
  956. */
  957. onFrameUpdate( callback ) {
  958. return this.onUpdate( callback, NodeUpdateType.FRAME );
  959. }
  960. /**
  961. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  962. * this method automatically sets the update type to `RENDER`.
  963. *
  964. * @param {Function} callback - The update method.
  965. * @return {Node} A reference to this node.
  966. */
  967. onRenderUpdate( callback ) {
  968. return this.onUpdate( callback, NodeUpdateType.RENDER );
  969. }
  970. /**
  971. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  972. * this method automatically sets the update type to `OBJECT`.
  973. *
  974. * @param {Function} callback - The update method.
  975. * @return {Node} A reference to this node.
  976. */
  977. onObjectUpdate( callback ) {
  978. return this.onUpdate( callback, NodeUpdateType.OBJECT );
  979. }
  980. /**
  981. * Convenient method for defining {@link Node#updateReference}.
  982. *
  983. * @param {Function} callback - The update method.
  984. * @return {Node} A reference to this node.
  985. */
  986. onReference( callback ) {
  987. this.updateReference = callback.bind( this.getSelf() );
  988. return this;
  989. }
  990. /**
  991. * The `this` reference might point to a Proxy so this method can be used
  992. * to get the reference to the actual node instance.
  993. *
  994. * @return {Node} A reference to the node.
  995. */
  996. getSelf() {
  997. // Returns non-node object.
  998. return this.self || this;
  999. }
  1000. /**
  1001. * Nodes might refer to other objects like materials. This method allows to dynamically update the reference
  1002. * to such objects based on a given state (e.g. the current node frame or builder).
  1003. *
  1004. * @param {any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  1005. * @return {any} The updated reference.
  1006. */
  1007. updateReference( /*state*/ ) {
  1008. return this;
  1009. }
  1010. /**
  1011. * By default this method returns the value of the {@link Node#global} flag. This method
  1012. * can be overwritten in derived classes if an analytical way is required to determine the
  1013. * global cache referring to the current shader-stage.
  1014. *
  1015. * @param {NodeBuilder} builder - The current node builder.
  1016. * @return {boolean} Whether this node is global or not.
  1017. */
  1018. isGlobal( /*builder*/ ) {
  1019. return this.global;
  1020. }
  1021. /**
  1022. * Generator function that can be used to iterate over the child nodes.
  1023. *
  1024. * @generator
  1025. * @yields {Node} A child node.
  1026. */
  1027. * getChildren() {
  1028. for ( const { childNode } of getNodeChildren( this ) ) {
  1029. yield childNode;
  1030. }
  1031. }
  1032. /**
  1033. * Calling this method dispatches the `dispose` event. This event can be used
  1034. * to register event listeners for clean up tasks.
  1035. */
  1036. dispose() {
  1037. this.dispatchEvent( { type: 'dispose' } );
  1038. }
  1039. /**
  1040. * Callback for {@link Node#traverse}.
  1041. *
  1042. * @callback traverseCallback
  1043. * @param {Node} node - The current node.
  1044. */
  1045. /**
  1046. * Can be used to traverse through the node's hierarchy.
  1047. *
  1048. * @param {traverseCallback} callback - A callback that is executed per node.
  1049. */
  1050. traverse( callback ) {
  1051. callback( this );
  1052. for ( const childNode of this.getChildren() ) {
  1053. childNode.traverse( callback );
  1054. }
  1055. }
  1056. /**
  1057. * Returns the cache key for this node.
  1058. *
  1059. * @param {boolean} [force=false] - When set to `true`, a recomputation of the cache key is forced.
  1060. * @return {number} The cache key of the node.
  1061. */
  1062. getCacheKey( force = false ) {
  1063. force = force || this.version !== this._cacheKeyVersion;
  1064. if ( force === true || this._cacheKey === null ) {
  1065. this._cacheKey = hash$1( getCacheKey$1( this, force ), this.customCacheKey() );
  1066. this._cacheKeyVersion = this.version;
  1067. }
  1068. return this._cacheKey;
  1069. }
  1070. /**
  1071. * Generate a custom cache key for this node.
  1072. *
  1073. * @return {number} The cache key of the node.
  1074. */
  1075. customCacheKey() {
  1076. return 0;
  1077. }
  1078. /**
  1079. * Returns the references to this node which is by default `this`.
  1080. *
  1081. * @return {Node} A reference to this node.
  1082. */
  1083. getScope() {
  1084. return this;
  1085. }
  1086. /**
  1087. * Returns the hash of the node which is used to identify the node. By default it's
  1088. * the {@link Node#uuid} however derived node classes might have to overwrite this method
  1089. * depending on their implementation.
  1090. *
  1091. * @param {NodeBuilder} builder - The current node builder.
  1092. * @return {string} The hash.
  1093. */
  1094. getHash( /*builder*/ ) {
  1095. return this.uuid;
  1096. }
  1097. /**
  1098. * Returns the update type of {@link Node#update}.
  1099. *
  1100. * @return {NodeUpdateType} The update type.
  1101. */
  1102. getUpdateType() {
  1103. return this.updateType;
  1104. }
  1105. /**
  1106. * Returns the update type of {@link Node#updateBefore}.
  1107. *
  1108. * @return {NodeUpdateType} The update type.
  1109. */
  1110. getUpdateBeforeType() {
  1111. return this.updateBeforeType;
  1112. }
  1113. /**
  1114. * Returns the update type of {@link Node#updateAfter}.
  1115. *
  1116. * @return {NodeUpdateType} The update type.
  1117. */
  1118. getUpdateAfterType() {
  1119. return this.updateAfterType;
  1120. }
  1121. /**
  1122. * Certain types are composed of multiple elements. For example a `vec3`
  1123. * is composed of three `float` values. This method returns the type of
  1124. * these elements.
  1125. *
  1126. * @param {NodeBuilder} builder - The current node builder.
  1127. * @return {string} The type of the node.
  1128. */
  1129. getElementType( builder ) {
  1130. const type = this.getNodeType( builder );
  1131. const elementType = builder.getElementType( type );
  1132. return elementType;
  1133. }
  1134. /**
  1135. * Returns the node member type for the given name.
  1136. *
  1137. * @param {NodeBuilder} builder - The current node builder.
  1138. * @param {string} name - The name of the member.
  1139. * @return {string} The type of the node.
  1140. */
  1141. getMemberType( /*builder, name*/ ) {
  1142. return 'void';
  1143. }
  1144. /**
  1145. * Returns the node's type.
  1146. *
  1147. * @param {NodeBuilder} builder - The current node builder.
  1148. * @return {string} The type of the node.
  1149. */
  1150. getNodeType( builder ) {
  1151. const nodeProperties = builder.getNodeProperties( this );
  1152. if ( nodeProperties.outputNode ) {
  1153. return nodeProperties.outputNode.getNodeType( builder );
  1154. }
  1155. return this.nodeType;
  1156. }
  1157. /**
  1158. * This method is used during the build process of a node and ensures
  1159. * equal nodes are not built multiple times but just once. For example if
  1160. * `attribute( 'uv' )` is used multiple times by the user, the build
  1161. * process makes sure to process just the first node.
  1162. *
  1163. * @param {NodeBuilder} builder - The current node builder.
  1164. * @return {Node} The shared node if possible. Otherwise `this` is returned.
  1165. */
  1166. getShared( builder ) {
  1167. const hash = this.getHash( builder );
  1168. const nodeFromHash = builder.getNodeFromHash( hash );
  1169. return nodeFromHash || this;
  1170. }
  1171. /**
  1172. * Represents the setup stage which is the first step of the build process, see {@link Node#build} method.
  1173. * This method is often overwritten in derived modules to prepare the node which is used as the output/result.
  1174. * The output node must be returned in the `return` statement.
  1175. *
  1176. * @param {NodeBuilder} builder - The current node builder.
  1177. * @return {?Node} The output node.
  1178. */
  1179. setup( builder ) {
  1180. const nodeProperties = builder.getNodeProperties( this );
  1181. let index = 0;
  1182. for ( const childNode of this.getChildren() ) {
  1183. nodeProperties[ 'node' + index ++ ] = childNode;
  1184. }
  1185. // return a outputNode if exists or null
  1186. return nodeProperties.outputNode || null;
  1187. }
  1188. /**
  1189. * Represents the analyze stage which is the second step of the build process, see {@link Node#build} method.
  1190. * This stage analyzes the node hierarchy and ensures descendent nodes are built.
  1191. *
  1192. * @param {NodeBuilder} builder - The current node builder.
  1193. * @param {?Node} output - The target output node.
  1194. */
  1195. analyze( builder, output = null ) {
  1196. const usageCount = builder.increaseUsage( this );
  1197. if ( this.parents === true ) {
  1198. const nodeData = builder.getDataFromNode( this, 'any' );
  1199. nodeData.stages = nodeData.stages || {};
  1200. nodeData.stages[ builder.shaderStage ] = nodeData.stages[ builder.shaderStage ] || [];
  1201. nodeData.stages[ builder.shaderStage ].push( output );
  1202. }
  1203. if ( usageCount === 1 ) {
  1204. // node flow children
  1205. const nodeProperties = builder.getNodeProperties( this );
  1206. for ( const childNode of Object.values( nodeProperties ) ) {
  1207. if ( childNode && childNode.isNode === true ) {
  1208. childNode.build( builder, this );
  1209. }
  1210. }
  1211. }
  1212. }
  1213. /**
  1214. * Represents the generate stage which is the third step of the build process, see {@link Node#build} method.
  1215. * This state builds the output node and returns the resulting shader string.
  1216. *
  1217. * @param {NodeBuilder} builder - The current node builder.
  1218. * @param {?string} output - Can be used to define the output type.
  1219. * @return {?string} The generated shader string.
  1220. */
  1221. generate( builder, output ) {
  1222. const { outputNode } = builder.getNodeProperties( this );
  1223. if ( outputNode && outputNode.isNode === true ) {
  1224. return outputNode.build( builder, output );
  1225. }
  1226. }
  1227. /**
  1228. * The method can be implemented to update the node's internal state before it is used to render an object.
  1229. * The {@link Node#updateBeforeType} property defines how often the update is executed.
  1230. *
  1231. * @abstract
  1232. * @param {NodeFrame} frame - A reference to the current node frame.
  1233. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1234. */
  1235. updateBefore( /*frame*/ ) {
  1236. console.warn( 'Abstract function.' );
  1237. }
  1238. /**
  1239. * The method can be implemented to update the node's internal state after it was used to render an object.
  1240. * The {@link Node#updateAfterType} property defines how often the update is executed.
  1241. *
  1242. * @abstract
  1243. * @param {NodeFrame} frame - A reference to the current node frame.
  1244. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1245. */
  1246. updateAfter( /*frame*/ ) {
  1247. console.warn( 'Abstract function.' );
  1248. }
  1249. /**
  1250. * The method can be implemented to update the node's internal state when it is used to render an object.
  1251. * The {@link Node#updateType} property defines how often the update is executed.
  1252. *
  1253. * @abstract
  1254. * @param {NodeFrame} frame - A reference to the current node frame.
  1255. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1256. */
  1257. update( /*frame*/ ) {
  1258. console.warn( 'Abstract function.' );
  1259. }
  1260. /**
  1261. * This method performs the build of a node. The behavior and return value depend on the current build stage:
  1262. * - **setup**: Prepares the node and its children for the build process. This process can also create new nodes. Returns the node itself or a variant.
  1263. * - **analyze**: Analyzes the node hierarchy for optimizations in the code generation stage. Returns `null`.
  1264. * - **generate**: Generates the shader code for the node. Returns the generated shader string.
  1265. *
  1266. * @param {NodeBuilder} builder - The current node builder.
  1267. * @param {string|Node|null} [output=null] - Can be used to define the output type.
  1268. * @return {Node|string|null} The result of the build process, depending on the build stage.
  1269. */
  1270. build( builder, output = null ) {
  1271. const refNode = this.getShared( builder );
  1272. if ( this !== refNode ) {
  1273. return refNode.build( builder, output );
  1274. }
  1275. //
  1276. const nodeData = builder.getDataFromNode( this );
  1277. nodeData.buildStages = nodeData.buildStages || {};
  1278. nodeData.buildStages[ builder.buildStage ] = true;
  1279. const parentBuildStage = _parentBuildStage[ builder.buildStage ];
  1280. if ( parentBuildStage && nodeData.buildStages[ parentBuildStage ] !== true ) {
  1281. // force parent build stage (setup or analyze)
  1282. const previousBuildStage = builder.getBuildStage();
  1283. builder.setBuildStage( parentBuildStage );
  1284. this.build( builder );
  1285. builder.setBuildStage( previousBuildStage );
  1286. }
  1287. //
  1288. builder.addNode( this );
  1289. builder.addChain( this );
  1290. /* Build stages expected results:
  1291. - "setup" -> Node
  1292. - "analyze" -> null
  1293. - "generate" -> String
  1294. */
  1295. let result = null;
  1296. const buildStage = builder.getBuildStage();
  1297. if ( buildStage === 'setup' ) {
  1298. this.updateReference( builder );
  1299. const properties = builder.getNodeProperties( this );
  1300. if ( properties.initialized !== true ) {
  1301. //const stackNodesBeforeSetup = builder.stack.nodes.length;
  1302. properties.initialized = true;
  1303. properties.outputNode = this.setup( builder ) || properties.outputNode || null;
  1304. /*if ( isNodeOutput && builder.stack.nodes.length !== stackNodesBeforeSetup ) {
  1305. // !! no outputNode !!
  1306. //outputNode = builder.stack;
  1307. }*/
  1308. for ( const childNode of Object.values( properties ) ) {
  1309. if ( childNode && childNode.isNode === true ) {
  1310. if ( childNode.parents === true ) {
  1311. const childProperties = builder.getNodeProperties( childNode );
  1312. childProperties.parents = childProperties.parents || [];
  1313. childProperties.parents.push( this );
  1314. }
  1315. childNode.build( builder );
  1316. }
  1317. }
  1318. }
  1319. result = properties.outputNode;
  1320. } else if ( buildStage === 'analyze' ) {
  1321. this.analyze( builder, output );
  1322. } else if ( buildStage === 'generate' ) {
  1323. const isGenerateOnce = this.generate.length === 1;
  1324. if ( isGenerateOnce ) {
  1325. const type = this.getNodeType( builder );
  1326. const nodeData = builder.getDataFromNode( this );
  1327. result = nodeData.snippet;
  1328. if ( result === undefined ) {
  1329. if ( nodeData.generated === undefined ) {
  1330. nodeData.generated = true;
  1331. result = this.generate( builder ) || '';
  1332. nodeData.snippet = result;
  1333. } else {
  1334. console.warn( 'THREE.Node: Recursion detected.', this );
  1335. result = '/* Recursion detected. */';
  1336. }
  1337. } else if ( nodeData.flowCodes !== undefined && builder.context.nodeBlock !== undefined ) {
  1338. builder.addFlowCodeHierarchy( this, builder.context.nodeBlock );
  1339. }
  1340. result = builder.format( result, type, output );
  1341. } else {
  1342. result = this.generate( builder, output ) || '';
  1343. }
  1344. }
  1345. builder.removeChain( this );
  1346. builder.addSequentialNode( this );
  1347. return result;
  1348. }
  1349. /**
  1350. * Returns the child nodes as a JSON object.
  1351. *
  1352. * @return {Array<Object>} An iterable list of serialized child objects as JSON.
  1353. */
  1354. getSerializeChildren() {
  1355. return getNodeChildren( this );
  1356. }
  1357. /**
  1358. * Serializes the node to JSON.
  1359. *
  1360. * @param {Object} json - The output JSON object.
  1361. */
  1362. serialize( json ) {
  1363. const nodeChildren = this.getSerializeChildren();
  1364. const inputNodes = {};
  1365. for ( const { property, index, childNode } of nodeChildren ) {
  1366. if ( index !== undefined ) {
  1367. if ( inputNodes[ property ] === undefined ) {
  1368. inputNodes[ property ] = Number.isInteger( index ) ? [] : {};
  1369. }
  1370. inputNodes[ property ][ index ] = childNode.toJSON( json.meta ).uuid;
  1371. } else {
  1372. inputNodes[ property ] = childNode.toJSON( json.meta ).uuid;
  1373. }
  1374. }
  1375. if ( Object.keys( inputNodes ).length > 0 ) {
  1376. json.inputNodes = inputNodes;
  1377. }
  1378. }
  1379. /**
  1380. * Deserializes the node from the given JSON.
  1381. *
  1382. * @param {Object} json - The JSON object.
  1383. */
  1384. deserialize( json ) {
  1385. if ( json.inputNodes !== undefined ) {
  1386. const nodes = json.meta.nodes;
  1387. for ( const property in json.inputNodes ) {
  1388. if ( Array.isArray( json.inputNodes[ property ] ) ) {
  1389. const inputArray = [];
  1390. for ( const uuid of json.inputNodes[ property ] ) {
  1391. inputArray.push( nodes[ uuid ] );
  1392. }
  1393. this[ property ] = inputArray;
  1394. } else if ( typeof json.inputNodes[ property ] === 'object' ) {
  1395. const inputObject = {};
  1396. for ( const subProperty in json.inputNodes[ property ] ) {
  1397. const uuid = json.inputNodes[ property ][ subProperty ];
  1398. inputObject[ subProperty ] = nodes[ uuid ];
  1399. }
  1400. this[ property ] = inputObject;
  1401. } else {
  1402. const uuid = json.inputNodes[ property ];
  1403. this[ property ] = nodes[ uuid ];
  1404. }
  1405. }
  1406. }
  1407. }
  1408. /**
  1409. * Serializes the node into the three.js JSON Object/Scene format.
  1410. *
  1411. * @param {?Object} meta - An optional JSON object that already holds serialized data from other scene objects.
  1412. * @return {Object} The serialized node.
  1413. */
  1414. toJSON( meta ) {
  1415. const { uuid, type } = this;
  1416. const isRoot = ( meta === undefined || typeof meta === 'string' );
  1417. if ( isRoot ) {
  1418. meta = {
  1419. textures: {},
  1420. images: {},
  1421. nodes: {}
  1422. };
  1423. }
  1424. // serialize
  1425. let data = meta.nodes[ uuid ];
  1426. if ( data === undefined ) {
  1427. data = {
  1428. uuid,
  1429. type,
  1430. meta,
  1431. metadata: {
  1432. version: 4.7,
  1433. type: 'Node',
  1434. generator: 'Node.toJSON'
  1435. }
  1436. };
  1437. if ( isRoot !== true ) meta.nodes[ data.uuid ] = data;
  1438. this.serialize( data );
  1439. delete data.meta;
  1440. }
  1441. // TODO: Copied from Object3D.toJSON
  1442. function extractFromCache( cache ) {
  1443. const values = [];
  1444. for ( const key in cache ) {
  1445. const data = cache[ key ];
  1446. delete data.metadata;
  1447. values.push( data );
  1448. }
  1449. return values;
  1450. }
  1451. if ( isRoot ) {
  1452. const textures = extractFromCache( meta.textures );
  1453. const images = extractFromCache( meta.images );
  1454. const nodes = extractFromCache( meta.nodes );
  1455. if ( textures.length > 0 ) data.textures = textures;
  1456. if ( images.length > 0 ) data.images = images;
  1457. if ( nodes.length > 0 ) data.nodes = nodes;
  1458. }
  1459. return data;
  1460. }
  1461. }
  1462. /**
  1463. * Base class for representing element access on an array-like
  1464. * node data structures.
  1465. *
  1466. * @augments Node
  1467. */
  1468. class ArrayElementNode extends Node { // @TODO: If extending from TempNode it breaks webgpu_compute
  1469. static get type() {
  1470. return 'ArrayElementNode';
  1471. }
  1472. /**
  1473. * Constructs an array element node.
  1474. *
  1475. * @param {Node} node - The array-like node.
  1476. * @param {Node} indexNode - The index node that defines the element access.
  1477. */
  1478. constructor( node, indexNode ) {
  1479. super();
  1480. /**
  1481. * The array-like node.
  1482. *
  1483. * @type {Node}
  1484. */
  1485. this.node = node;
  1486. /**
  1487. * The index node that defines the element access.
  1488. *
  1489. * @type {Node}
  1490. */
  1491. this.indexNode = indexNode;
  1492. /**
  1493. * This flag can be used for type testing.
  1494. *
  1495. * @type {boolean}
  1496. * @readonly
  1497. * @default true
  1498. */
  1499. this.isArrayElementNode = true;
  1500. }
  1501. /**
  1502. * This method is overwritten since the node type is inferred from the array-like node.
  1503. *
  1504. * @param {NodeBuilder} builder - The current node builder.
  1505. * @return {string} The node type.
  1506. */
  1507. getNodeType( builder ) {
  1508. return this.node.getElementType( builder );
  1509. }
  1510. generate( builder ) {
  1511. const indexType = this.indexNode.getNodeType( builder );
  1512. const nodeSnippet = this.node.build( builder );
  1513. const indexSnippet = this.indexNode.build( builder, ! builder.isVector( indexType ) && builder.isInteger( indexType ) ? indexType : 'uint' );
  1514. return `${ nodeSnippet }[ ${ indexSnippet } ]`;
  1515. }
  1516. }
  1517. /**
  1518. * This module is part of the TSL core and usually not used in app level code.
  1519. * It represents a convert operation during the shader generation process
  1520. * meaning it converts the data type of a node to a target data type.
  1521. *
  1522. * @augments Node
  1523. */
  1524. class ConvertNode extends Node {
  1525. static get type() {
  1526. return 'ConvertNode';
  1527. }
  1528. /**
  1529. * Constructs a new convert node.
  1530. *
  1531. * @param {Node} node - The node which type should be converted.
  1532. * @param {string} convertTo - The target node type. Multiple types can be defined by separating them with a `|` sign.
  1533. */
  1534. constructor( node, convertTo ) {
  1535. super();
  1536. /**
  1537. * The node which type should be converted.
  1538. *
  1539. * @type {Node}
  1540. */
  1541. this.node = node;
  1542. /**
  1543. * The target node type. Multiple types can be defined by separating them with a `|` sign.
  1544. *
  1545. * @type {string}
  1546. */
  1547. this.convertTo = convertTo;
  1548. }
  1549. /**
  1550. * This method is overwritten since the implementation tries to infer the best
  1551. * matching type from the {@link ConvertNode#convertTo} property.
  1552. *
  1553. * @param {NodeBuilder} builder - The current node builder.
  1554. * @return {string} The node type.
  1555. */
  1556. getNodeType( builder ) {
  1557. const requestType = this.node.getNodeType( builder );
  1558. let convertTo = null;
  1559. for ( const overloadingType of this.convertTo.split( '|' ) ) {
  1560. if ( convertTo === null || builder.getTypeLength( requestType ) === builder.getTypeLength( overloadingType ) ) {
  1561. convertTo = overloadingType;
  1562. }
  1563. }
  1564. return convertTo;
  1565. }
  1566. serialize( data ) {
  1567. super.serialize( data );
  1568. data.convertTo = this.convertTo;
  1569. }
  1570. deserialize( data ) {
  1571. super.deserialize( data );
  1572. this.convertTo = data.convertTo;
  1573. }
  1574. generate( builder, output ) {
  1575. const node = this.node;
  1576. const type = this.getNodeType( builder );
  1577. const snippet = node.build( builder, type );
  1578. return builder.format( snippet, type, output );
  1579. }
  1580. }
  1581. /**
  1582. * This module uses cache management to create temporary variables
  1583. * if the node is used more than once to prevent duplicate calculations.
  1584. *
  1585. * The class acts as a base class for many other nodes types.
  1586. *
  1587. * @augments Node
  1588. */
  1589. class TempNode extends Node {
  1590. static get type() {
  1591. return 'TempNode';
  1592. }
  1593. /**
  1594. * Constructs a temp node.
  1595. *
  1596. * @param {?string} nodeType - The node type.
  1597. */
  1598. constructor( nodeType = null ) {
  1599. super( nodeType );
  1600. /**
  1601. * This flag can be used for type testing.
  1602. *
  1603. * @type {boolean}
  1604. * @readonly
  1605. * @default true
  1606. */
  1607. this.isTempNode = true;
  1608. }
  1609. /**
  1610. * Whether this node is used more than once in context of other nodes.
  1611. *
  1612. * @param {NodeBuilder} builder - The node builder.
  1613. * @return {boolean} A flag that indicates if there is more than one dependency to other nodes.
  1614. */
  1615. hasDependencies( builder ) {
  1616. return builder.getDataFromNode( this ).usageCount > 1;
  1617. }
  1618. build( builder, output ) {
  1619. const buildStage = builder.getBuildStage();
  1620. if ( buildStage === 'generate' ) {
  1621. const type = builder.getVectorType( this.getNodeType( builder, output ) );
  1622. const nodeData = builder.getDataFromNode( this );
  1623. if ( nodeData.propertyName !== undefined ) {
  1624. return builder.format( nodeData.propertyName, type, output );
  1625. } else if ( type !== 'void' && output !== 'void' && this.hasDependencies( builder ) ) {
  1626. const snippet = super.build( builder, type );
  1627. const nodeVar = builder.getVarFromNode( this, null, type );
  1628. const propertyName = builder.getPropertyName( nodeVar );
  1629. builder.addLineFlowCode( `${ propertyName } = ${ snippet }`, this );
  1630. nodeData.snippet = snippet;
  1631. nodeData.propertyName = propertyName;
  1632. return builder.format( nodeData.propertyName, type, output );
  1633. }
  1634. }
  1635. return super.build( builder, output );
  1636. }
  1637. }
  1638. /**
  1639. * This module is part of the TSL core and usually not used in app level code.
  1640. * It represents a join operation during the shader generation process.
  1641. * For example in can compose/join two single floats into a `vec2` type.
  1642. *
  1643. * @augments TempNode
  1644. */
  1645. class JoinNode extends TempNode {
  1646. static get type() {
  1647. return 'JoinNode';
  1648. }
  1649. /**
  1650. * Constructs a new join node.
  1651. *
  1652. * @param {Array<Node>} nodes - An array of nodes that should be joined.
  1653. * @param {?string} [nodeType=null] - The node type.
  1654. */
  1655. constructor( nodes = [], nodeType = null ) {
  1656. super( nodeType );
  1657. /**
  1658. * An array of nodes that should be joined.
  1659. *
  1660. * @type {Array<Node>}
  1661. */
  1662. this.nodes = nodes;
  1663. }
  1664. /**
  1665. * This method is overwritten since the node type must be inferred from the
  1666. * joined data length if not explicitly defined.
  1667. *
  1668. * @param {NodeBuilder} builder - The current node builder.
  1669. * @return {string} The node type.
  1670. */
  1671. getNodeType( builder ) {
  1672. if ( this.nodeType !== null ) {
  1673. return builder.getVectorType( this.nodeType );
  1674. }
  1675. return builder.getTypeFromLength( this.nodes.reduce( ( count, cur ) => count + builder.getTypeLength( cur.getNodeType( builder ) ), 0 ) );
  1676. }
  1677. generate( builder, output ) {
  1678. const type = this.getNodeType( builder );
  1679. const maxLength = builder.getTypeLength( type );
  1680. const nodes = this.nodes;
  1681. const primitiveType = builder.getComponentType( type );
  1682. const snippetValues = [];
  1683. let length = 0;
  1684. for ( const input of nodes ) {
  1685. if ( length >= maxLength ) {
  1686. console.error( `THREE.TSL: Length of parameters exceeds maximum length of function '${ type }()' type.` );
  1687. break;
  1688. }
  1689. let inputType = input.getNodeType( builder );
  1690. let inputTypeLength = builder.getTypeLength( inputType );
  1691. let inputSnippet;
  1692. if ( length + inputTypeLength > maxLength ) {
  1693. console.error( `THREE.TSL: Length of '${ type }()' data exceeds maximum length of output type.` );
  1694. inputTypeLength = maxLength - length;
  1695. inputType = builder.getTypeFromLength( inputTypeLength );
  1696. }
  1697. length += inputTypeLength;
  1698. inputSnippet = input.build( builder, inputType );
  1699. const inputPrimitiveType = builder.getComponentType( inputType );
  1700. if ( inputPrimitiveType !== primitiveType ) {
  1701. inputSnippet = builder.format( inputSnippet, inputPrimitiveType, primitiveType );
  1702. }
  1703. snippetValues.push( inputSnippet );
  1704. }
  1705. const snippet = `${ builder.getType( type ) }( ${ snippetValues.join( ', ' ) } )`;
  1706. return builder.format( snippet, type, output );
  1707. }
  1708. }
  1709. const _stringVectorComponents = vectorComponents.join( '' );
  1710. /**
  1711. * This module is part of the TSL core and usually not used in app level code.
  1712. * `SplitNode` represents a property access operation which means it is
  1713. * used to implement any `.xyzw`, `.rgba` and `stpq` usage on node objects.
  1714. * For example:
  1715. * ```js
  1716. * const redValue = color.r;
  1717. * ```
  1718. *
  1719. * @augments Node
  1720. */
  1721. class SplitNode extends Node {
  1722. static get type() {
  1723. return 'SplitNode';
  1724. }
  1725. /**
  1726. * Constructs a new split node.
  1727. *
  1728. * @param {Node} node - The node that should be accessed.
  1729. * @param {string} [components='x'] - The components that should be accessed.
  1730. */
  1731. constructor( node, components = 'x' ) {
  1732. super();
  1733. /**
  1734. * The node that should be accessed.
  1735. *
  1736. * @type {Node}
  1737. */
  1738. this.node = node;
  1739. /**
  1740. * The components that should be accessed.
  1741. *
  1742. * @type {string}
  1743. */
  1744. this.components = components;
  1745. /**
  1746. * This flag can be used for type testing.
  1747. *
  1748. * @type {boolean}
  1749. * @readonly
  1750. * @default true
  1751. */
  1752. this.isSplitNode = true;
  1753. }
  1754. /**
  1755. * Returns the vector length which is computed based on the requested components.
  1756. *
  1757. * @return {number} The vector length.
  1758. */
  1759. getVectorLength() {
  1760. let vectorLength = this.components.length;
  1761. for ( const c of this.components ) {
  1762. vectorLength = Math.max( vectorComponents.indexOf( c ) + 1, vectorLength );
  1763. }
  1764. return vectorLength;
  1765. }
  1766. /**
  1767. * Returns the component type of the node's type.
  1768. *
  1769. * @param {NodeBuilder} builder - The current node builder.
  1770. * @return {string} The component type.
  1771. */
  1772. getComponentType( builder ) {
  1773. return builder.getComponentType( this.node.getNodeType( builder ) );
  1774. }
  1775. /**
  1776. * This method is overwritten since the node type is inferred from requested components.
  1777. *
  1778. * @param {NodeBuilder} builder - The current node builder.
  1779. * @return {string} The node type.
  1780. */
  1781. getNodeType( builder ) {
  1782. return builder.getTypeFromLength( this.components.length, this.getComponentType( builder ) );
  1783. }
  1784. generate( builder, output ) {
  1785. const node = this.node;
  1786. const nodeTypeLength = builder.getTypeLength( node.getNodeType( builder ) );
  1787. let snippet = null;
  1788. if ( nodeTypeLength > 1 ) {
  1789. let type = null;
  1790. const componentsLength = this.getVectorLength();
  1791. if ( componentsLength >= nodeTypeLength ) {
  1792. // needed expand the input node
  1793. type = builder.getTypeFromLength( this.getVectorLength(), this.getComponentType( builder ) );
  1794. }
  1795. const nodeSnippet = node.build( builder, type );
  1796. if ( this.components.length === nodeTypeLength && this.components === _stringVectorComponents.slice( 0, this.components.length ) ) {
  1797. // unnecessary swizzle
  1798. snippet = builder.format( nodeSnippet, type, output );
  1799. } else {
  1800. snippet = builder.format( `${nodeSnippet}.${this.components}`, this.getNodeType( builder ), output );
  1801. }
  1802. } else {
  1803. // ignore .components if .node returns float/integer
  1804. snippet = node.build( builder, output );
  1805. }
  1806. return snippet;
  1807. }
  1808. serialize( data ) {
  1809. super.serialize( data );
  1810. data.components = this.components;
  1811. }
  1812. deserialize( data ) {
  1813. super.deserialize( data );
  1814. this.components = data.components;
  1815. }
  1816. }
  1817. /**
  1818. * This module is part of the TSL core and usually not used in app level code.
  1819. * `SetNode` represents a set operation which means it is used to implement any
  1820. * `setXYZW()`, `setRGBA()` and `setSTPQ()` method invocations on node objects.
  1821. * For example:
  1822. * ```js
  1823. * materialLine.colorNode = color( 0, 0, 0 ).setR( float( 1 ) );
  1824. * ```
  1825. *
  1826. * @augments TempNode
  1827. */
  1828. class SetNode extends TempNode {
  1829. static get type() {
  1830. return 'SetNode';
  1831. }
  1832. /**
  1833. * Constructs a new set node.
  1834. *
  1835. * @param {Node} sourceNode - The node that should be updated.
  1836. * @param {string} components - The components that should be updated.
  1837. * @param {Node} targetNode - The value node.
  1838. */
  1839. constructor( sourceNode, components, targetNode ) {
  1840. super();
  1841. /**
  1842. * The node that should be updated.
  1843. *
  1844. * @type {Node}
  1845. */
  1846. this.sourceNode = sourceNode;
  1847. /**
  1848. * The components that should be updated.
  1849. *
  1850. * @type {string}
  1851. */
  1852. this.components = components;
  1853. /**
  1854. * The value node.
  1855. *
  1856. * @type {Node}
  1857. */
  1858. this.targetNode = targetNode;
  1859. }
  1860. /**
  1861. * This method is overwritten since the node type is inferred from {@link SetNode#sourceNode}.
  1862. *
  1863. * @param {NodeBuilder} builder - The current node builder.
  1864. * @return {string} The node type.
  1865. */
  1866. getNodeType( builder ) {
  1867. return this.sourceNode.getNodeType( builder );
  1868. }
  1869. generate( builder ) {
  1870. const { sourceNode, components, targetNode } = this;
  1871. const sourceType = this.getNodeType( builder );
  1872. const componentType = builder.getComponentType( targetNode.getNodeType( builder ) );
  1873. const targetType = builder.getTypeFromLength( components.length, componentType );
  1874. const targetSnippet = targetNode.build( builder, targetType );
  1875. const sourceSnippet = sourceNode.build( builder, sourceType );
  1876. const length = builder.getTypeLength( sourceType );
  1877. const snippetValues = [];
  1878. for ( let i = 0; i < length; i ++ ) {
  1879. const component = vectorComponents[ i ];
  1880. if ( component === components[ 0 ] ) {
  1881. snippetValues.push( targetSnippet );
  1882. i += components.length - 1;
  1883. } else {
  1884. snippetValues.push( sourceSnippet + '.' + component );
  1885. }
  1886. }
  1887. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  1888. }
  1889. }
  1890. /**
  1891. * This module is part of the TSL core and usually not used in app level code.
  1892. * It represents a flip operation during the shader generation process
  1893. * meaning it flips normalized values with the following formula:
  1894. * ```
  1895. * x = 1 - x;
  1896. * ```
  1897. * `FlipNode` is internally used to implement any `flipXYZW()`, `flipRGBA()` and
  1898. * `flipSTPQ()` method invocations on node objects. For example:
  1899. * ```js
  1900. * uvNode = uvNode.flipY();
  1901. * ```
  1902. *
  1903. * @augments TempNode
  1904. */
  1905. class FlipNode extends TempNode {
  1906. static get type() {
  1907. return 'FlipNode';
  1908. }
  1909. /**
  1910. * Constructs a new flip node.
  1911. *
  1912. * @param {Node} sourceNode - The node which component(s) should be flipped.
  1913. * @param {string} components - The components that should be flipped e.g. `'x'` or `'xy'`.
  1914. */
  1915. constructor( sourceNode, components ) {
  1916. super();
  1917. /**
  1918. * The node which component(s) should be flipped.
  1919. *
  1920. * @type {Node}
  1921. */
  1922. this.sourceNode = sourceNode;
  1923. /**
  1924. * The components that should be flipped e.g. `'x'` or `'xy'`.
  1925. *
  1926. * @type {string}
  1927. */
  1928. this.components = components;
  1929. }
  1930. /**
  1931. * This method is overwritten since the node type is inferred from the source node.
  1932. *
  1933. * @param {NodeBuilder} builder - The current node builder.
  1934. * @return {string} The node type.
  1935. */
  1936. getNodeType( builder ) {
  1937. return this.sourceNode.getNodeType( builder );
  1938. }
  1939. generate( builder ) {
  1940. const { components, sourceNode } = this;
  1941. const sourceType = this.getNodeType( builder );
  1942. const sourceSnippet = sourceNode.build( builder );
  1943. const sourceCache = builder.getVarFromNode( this );
  1944. const sourceProperty = builder.getPropertyName( sourceCache );
  1945. builder.addLineFlowCode( sourceProperty + ' = ' + sourceSnippet, this );
  1946. const length = builder.getTypeLength( sourceType );
  1947. const snippetValues = [];
  1948. let componentIndex = 0;
  1949. for ( let i = 0; i < length; i ++ ) {
  1950. const component = vectorComponents[ i ];
  1951. if ( component === components[ componentIndex ] ) {
  1952. snippetValues.push( '1.0 - ' + ( sourceProperty + '.' + component ) );
  1953. componentIndex ++;
  1954. } else {
  1955. snippetValues.push( sourceProperty + '.' + component );
  1956. }
  1957. }
  1958. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  1959. }
  1960. }
  1961. /**
  1962. * Base class for representing data input nodes.
  1963. *
  1964. * @augments Node
  1965. */
  1966. class InputNode extends Node {
  1967. static get type() {
  1968. return 'InputNode';
  1969. }
  1970. /**
  1971. * Constructs a new input node.
  1972. *
  1973. * @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).
  1974. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  1975. */
  1976. constructor( value, nodeType = null ) {
  1977. super( nodeType );
  1978. /**
  1979. * This flag can be used for type testing.
  1980. *
  1981. * @type {boolean}
  1982. * @readonly
  1983. * @default true
  1984. */
  1985. this.isInputNode = true;
  1986. /**
  1987. * The value of this node. This can be any JS primitive, functions, array buffers or even three.js objects (vector, matrices, colors).
  1988. *
  1989. * @type {any}
  1990. */
  1991. this.value = value;
  1992. /**
  1993. * The precision of the value in the shader.
  1994. *
  1995. * @type {?('low'|'medium'|'high')}
  1996. * @default null
  1997. */
  1998. this.precision = null;
  1999. }
  2000. getNodeType( /*builder*/ ) {
  2001. if ( this.nodeType === null ) {
  2002. return getValueType( this.value );
  2003. }
  2004. return this.nodeType;
  2005. }
  2006. /**
  2007. * Returns the input type of the node which is by default the node type. Derived modules
  2008. * might overwrite this method and use a fixed type or compute one analytically.
  2009. *
  2010. * A typical example for different input and node types are textures. The input type of a
  2011. * normal RGBA texture is `texture` whereas its node type is `vec4`.
  2012. *
  2013. * @param {NodeBuilder} builder - The current node builder.
  2014. * @return {string} The input type.
  2015. */
  2016. getInputType( builder ) {
  2017. return this.getNodeType( builder );
  2018. }
  2019. /**
  2020. * Sets the precision to the given value. The method can be
  2021. * overwritten in derived classes if the final precision must be computed
  2022. * analytically.
  2023. *
  2024. * @param {('low'|'medium'|'high')} precision - The precision of the input value in the shader.
  2025. * @return {InputNode} A reference to this node.
  2026. */
  2027. setPrecision( precision ) {
  2028. this.precision = precision;
  2029. return this;
  2030. }
  2031. serialize( data ) {
  2032. super.serialize( data );
  2033. data.value = this.value;
  2034. if ( this.value && this.value.toArray ) data.value = this.value.toArray();
  2035. data.valueType = getValueType( this.value );
  2036. data.nodeType = this.nodeType;
  2037. if ( data.valueType === 'ArrayBuffer' ) data.value = arrayBufferToBase64( data.value );
  2038. data.precision = this.precision;
  2039. }
  2040. deserialize( data ) {
  2041. super.deserialize( data );
  2042. this.nodeType = data.nodeType;
  2043. this.value = Array.isArray( data.value ) ? getValueFromType( data.valueType, ...data.value ) : data.value;
  2044. this.precision = data.precision || null;
  2045. if ( this.value && this.value.fromArray ) this.value = this.value.fromArray( data.value );
  2046. }
  2047. generate( /*builder, output*/ ) {
  2048. console.warn( 'Abstract function.' );
  2049. }
  2050. }
  2051. const _regNum = /float|u?int/;
  2052. /**
  2053. * Class for representing a constant value in the shader.
  2054. *
  2055. * @augments InputNode
  2056. */
  2057. class ConstNode extends InputNode {
  2058. static get type() {
  2059. return 'ConstNode';
  2060. }
  2061. /**
  2062. * Constructs a new input node.
  2063. *
  2064. * @param {any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color).
  2065. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2066. */
  2067. constructor( value, nodeType = null ) {
  2068. super( value, nodeType );
  2069. /**
  2070. * This flag can be used for type testing.
  2071. *
  2072. * @type {boolean}
  2073. * @readonly
  2074. * @default true
  2075. */
  2076. this.isConstNode = true;
  2077. }
  2078. /**
  2079. * Generates the shader string of the value with the current node builder.
  2080. *
  2081. * @param {NodeBuilder} builder - The current node builder.
  2082. * @return {string} The generated value as a shader string.
  2083. */
  2084. generateConst( builder ) {
  2085. return builder.generateConst( this.getNodeType( builder ), this.value );
  2086. }
  2087. generate( builder, output ) {
  2088. const type = this.getNodeType( builder );
  2089. if ( _regNum.test( type ) && _regNum.test( output ) ) {
  2090. return builder.generateConst( output, this.value );
  2091. }
  2092. return builder.format( this.generateConst( builder ), type, output );
  2093. }
  2094. }
  2095. /**
  2096. * Base class for representing member access on an object-like
  2097. * node data structures.
  2098. *
  2099. * @augments Node
  2100. */
  2101. class MemberNode extends Node {
  2102. static get type() {
  2103. return 'MemberNode';
  2104. }
  2105. /**
  2106. * Constructs an array element node.
  2107. *
  2108. * @param {Node} node - The array-like node.
  2109. * @param {string} property - The property name.
  2110. */
  2111. constructor( node, property ) {
  2112. super();
  2113. /**
  2114. * The array-like node.
  2115. *
  2116. * @type {Node}
  2117. */
  2118. this.node = node;
  2119. /**
  2120. * The property name.
  2121. *
  2122. * @type {Node}
  2123. */
  2124. this.property = property;
  2125. /**
  2126. * This flag can be used for type testing.
  2127. *
  2128. * @type {boolean}
  2129. * @readonly
  2130. * @default true
  2131. */
  2132. this.isMemberNode = true;
  2133. }
  2134. getNodeType( builder ) {
  2135. return this.node.getMemberType( builder, this.property );
  2136. }
  2137. generate( builder ) {
  2138. const propertyName = this.node.build( builder );
  2139. return propertyName + '.' + this.property;
  2140. }
  2141. }
  2142. let currentStack = null;
  2143. const NodeElements = new Map();
  2144. function addMethodChaining( name, nodeElement ) {
  2145. if ( NodeElements.has( name ) ) {
  2146. console.warn( `THREE.TSL: Redefinition of method chaining '${ name }'.` );
  2147. return;
  2148. }
  2149. if ( typeof nodeElement !== 'function' ) throw new Error( `THREE.TSL: Node element ${ name } is not a function` );
  2150. NodeElements.set( name, nodeElement );
  2151. }
  2152. const parseSwizzle = ( props ) => props.replace( /r|s/g, 'x' ).replace( /g|t/g, 'y' ).replace( /b|p/g, 'z' ).replace( /a|q/g, 'w' );
  2153. const parseSwizzleAndSort = ( props ) => parseSwizzle( props ).split( '' ).sort().join( '' );
  2154. const shaderNodeHandler = {
  2155. setup( NodeClosure, params ) {
  2156. const inputs = params.shift();
  2157. return NodeClosure( nodeObjects( inputs ), ...params );
  2158. },
  2159. get( node, prop, nodeObj ) {
  2160. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  2161. if ( node.isStackNode !== true && prop === 'assign' ) {
  2162. return ( ...params ) => {
  2163. currentStack.assign( nodeObj, ...params );
  2164. return nodeObj;
  2165. };
  2166. } else if ( NodeElements.has( prop ) ) {
  2167. const nodeElement = NodeElements.get( prop );
  2168. return node.isStackNode ? ( ...params ) => nodeObj.add( nodeElement( ...params ) ) : ( ...params ) => nodeElement( nodeObj, ...params );
  2169. } else if ( prop === 'self' ) {
  2170. return node;
  2171. } else if ( prop.endsWith( 'Assign' ) && NodeElements.has( prop.slice( 0, prop.length - 'Assign'.length ) ) ) {
  2172. const nodeElement = NodeElements.get( prop.slice( 0, prop.length - 'Assign'.length ) );
  2173. return node.isStackNode ? ( ...params ) => nodeObj.assign( params[ 0 ], nodeElement( ...params ) ) : ( ...params ) => nodeObj.assign( nodeElement( nodeObj, ...params ) );
  2174. } else if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true ) {
  2175. // accessing properties ( swizzle )
  2176. prop = parseSwizzle( prop );
  2177. return nodeObject( new SplitNode( nodeObj, prop ) );
  2178. } else if ( /^set[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  2179. // set properties ( swizzle ) and sort to xyzw sequence
  2180. prop = parseSwizzleAndSort( prop.slice( 3 ).toLowerCase() );
  2181. return ( value ) => nodeObject( new SetNode( node, prop, nodeObject( value ) ) );
  2182. } else if ( /^flip[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  2183. // set properties ( swizzle ) and sort to xyzw sequence
  2184. prop = parseSwizzleAndSort( prop.slice( 4 ).toLowerCase() );
  2185. return () => nodeObject( new FlipNode( nodeObject( node ), prop ) );
  2186. } else if ( prop === 'width' || prop === 'height' || prop === 'depth' ) {
  2187. // accessing property
  2188. if ( prop === 'width' ) prop = 'x';
  2189. else if ( prop === 'height' ) prop = 'y';
  2190. else if ( prop === 'depth' ) prop = 'z';
  2191. return nodeObject( new SplitNode( node, prop ) );
  2192. } else if ( /^\d+$/.test( prop ) === true ) {
  2193. // accessing array
  2194. return nodeObject( new ArrayElementNode( nodeObj, new ConstNode( Number( prop ), 'uint' ) ) );
  2195. } else if ( /^get$/.test( prop ) === true ) {
  2196. // accessing properties
  2197. return ( value ) => nodeObject( new MemberNode( nodeObj, value ) );
  2198. }
  2199. }
  2200. return Reflect.get( node, prop, nodeObj );
  2201. },
  2202. set( node, prop, value, nodeObj ) {
  2203. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  2204. // setting properties
  2205. if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true || prop === 'width' || prop === 'height' || prop === 'depth' || /^\d+$/.test( prop ) === true ) {
  2206. nodeObj[ prop ].assign( value );
  2207. return true;
  2208. }
  2209. }
  2210. return Reflect.set( node, prop, value, nodeObj );
  2211. }
  2212. };
  2213. const nodeObjectsCacheMap = new WeakMap();
  2214. const nodeBuilderFunctionsCacheMap = new WeakMap();
  2215. const ShaderNodeObject = function ( obj, altType = null ) {
  2216. const type = getValueType( obj );
  2217. if ( type === 'node' ) {
  2218. let nodeObject = nodeObjectsCacheMap.get( obj );
  2219. if ( nodeObject === undefined ) {
  2220. nodeObject = new Proxy( obj, shaderNodeHandler );
  2221. nodeObjectsCacheMap.set( obj, nodeObject );
  2222. nodeObjectsCacheMap.set( nodeObject, nodeObject );
  2223. }
  2224. return nodeObject;
  2225. } else if ( ( altType === null && ( type === 'float' || type === 'boolean' ) ) || ( type && type !== 'shader' && type !== 'string' ) ) {
  2226. return nodeObject( getConstNode( obj, altType ) );
  2227. } else if ( type === 'shader' ) {
  2228. return obj.isFn ? obj : Fn( obj );
  2229. }
  2230. return obj;
  2231. };
  2232. const ShaderNodeObjects = function ( objects, altType = null ) {
  2233. for ( const name in objects ) {
  2234. objects[ name ] = nodeObject( objects[ name ], altType );
  2235. }
  2236. return objects;
  2237. };
  2238. const ShaderNodeArray = function ( array, altType = null ) {
  2239. const len = array.length;
  2240. for ( let i = 0; i < len; i ++ ) {
  2241. array[ i ] = nodeObject( array[ i ], altType );
  2242. }
  2243. return array;
  2244. };
  2245. const ShaderNodeProxy = function ( NodeClass, scope = null, factor = null, settings = null ) {
  2246. const assignNode = ( node ) => nodeObject( settings !== null ? Object.assign( node, settings ) : node );
  2247. let fn, name = scope, minParams, maxParams;
  2248. function verifyParamsLimit( params ) {
  2249. let tslName;
  2250. if ( name ) tslName = /[a-z]/i.test( name ) ? name + '()' : name;
  2251. else tslName = NodeClass.type;
  2252. if ( minParams !== undefined && params.length < minParams ) {
  2253. console.error( `THREE.TSL: "${ tslName }" parameter length is less than minimum required.` );
  2254. return params.concat( new Array( minParams - params.length ).fill( 0 ) );
  2255. } else if ( maxParams !== undefined && params.length > maxParams ) {
  2256. console.error( `THREE.TSL: "${ tslName }" parameter length exceeds limit.` );
  2257. return params.slice( 0, maxParams );
  2258. }
  2259. return params;
  2260. }
  2261. if ( scope === null ) {
  2262. fn = ( ...params ) => {
  2263. return assignNode( new NodeClass( ...nodeArray( verifyParamsLimit( params ) ) ) );
  2264. };
  2265. } else if ( factor !== null ) {
  2266. factor = nodeObject( factor );
  2267. fn = ( ...params ) => {
  2268. return assignNode( new NodeClass( scope, ...nodeArray( verifyParamsLimit( params ) ), factor ) );
  2269. };
  2270. } else {
  2271. fn = ( ...params ) => {
  2272. return assignNode( new NodeClass( scope, ...nodeArray( verifyParamsLimit( params ) ) ) );
  2273. };
  2274. }
  2275. fn.setParameterLength = ( ...params ) => {
  2276. if ( params.length === 1 ) minParams = maxParams = params[ 0 ];
  2277. else if ( params.length === 2 ) [ minParams, maxParams ] = params;
  2278. return fn;
  2279. };
  2280. fn.setName = ( value ) => {
  2281. name = value;
  2282. return fn;
  2283. };
  2284. return fn;
  2285. };
  2286. const ShaderNodeImmutable = function ( NodeClass, ...params ) {
  2287. return nodeObject( new NodeClass( ...nodeArray( params ) ) );
  2288. };
  2289. class ShaderCallNodeInternal extends Node {
  2290. constructor( shaderNode, inputNodes ) {
  2291. super();
  2292. this.shaderNode = shaderNode;
  2293. this.inputNodes = inputNodes;
  2294. this.isShaderCallNodeInternal = true;
  2295. }
  2296. getNodeType( builder ) {
  2297. return this.shaderNode.nodeType || this.getOutputNode( builder ).getNodeType( builder );
  2298. }
  2299. getMemberType( builder, name ) {
  2300. return this.getOutputNode( builder ).getMemberType( builder, name );
  2301. }
  2302. call( builder ) {
  2303. const { shaderNode, inputNodes } = this;
  2304. const properties = builder.getNodeProperties( shaderNode );
  2305. const subBuild = builder.getClosestSubBuild( shaderNode.subBuilds ) || '';
  2306. const subBuildProperty = subBuild || 'default';
  2307. if ( properties[ subBuildProperty ] ) {
  2308. return properties[ subBuildProperty ];
  2309. }
  2310. //
  2311. const previousSubBuildFn = builder.subBuildFn;
  2312. builder.subBuildFn = subBuild;
  2313. let result = null;
  2314. if ( shaderNode.layout ) {
  2315. let functionNodesCacheMap = nodeBuilderFunctionsCacheMap.get( builder.constructor );
  2316. if ( functionNodesCacheMap === undefined ) {
  2317. functionNodesCacheMap = new WeakMap();
  2318. nodeBuilderFunctionsCacheMap.set( builder.constructor, functionNodesCacheMap );
  2319. }
  2320. let functionNode = functionNodesCacheMap.get( shaderNode );
  2321. if ( functionNode === undefined ) {
  2322. functionNode = nodeObject( builder.buildFunctionNode( shaderNode ) );
  2323. functionNodesCacheMap.set( shaderNode, functionNode );
  2324. }
  2325. builder.addInclude( functionNode );
  2326. result = nodeObject( functionNode.call( inputNodes ) );
  2327. } else {
  2328. const jsFunc = shaderNode.jsFunc;
  2329. const outputNode = inputNodes !== null || jsFunc.length > 1 ? jsFunc( inputNodes || [], builder ) : jsFunc( builder );
  2330. result = nodeObject( outputNode );
  2331. }
  2332. builder.subBuildFn = previousSubBuildFn;
  2333. if ( shaderNode.once ) {
  2334. properties[ subBuildProperty ] = result;
  2335. }
  2336. return result;
  2337. }
  2338. setupOutput( builder ) {
  2339. builder.addStack();
  2340. builder.stack.outputNode = this.call( builder );
  2341. return builder.removeStack();
  2342. }
  2343. getOutputNode( builder ) {
  2344. const properties = builder.getNodeProperties( this );
  2345. const subBuildOutput = builder.getSubBuildOutput( this );
  2346. properties[ subBuildOutput ] = properties[ subBuildOutput ] || this.setupOutput( builder );
  2347. properties[ subBuildOutput ].subBuild = builder.getClosestSubBuild( this );
  2348. return properties[ subBuildOutput ];
  2349. }
  2350. build( builder, output = null ) {
  2351. let result = null;
  2352. const buildStage = builder.getBuildStage();
  2353. const properties = builder.getNodeProperties( this );
  2354. const subBuildOutput = builder.getSubBuildOutput( this );
  2355. const outputNode = this.getOutputNode( builder );
  2356. if ( buildStage === 'setup' ) {
  2357. const subBuildInitialized = builder.getSubBuildProperty( 'initialized', this );
  2358. if ( properties[ subBuildInitialized ] !== true ) {
  2359. properties[ subBuildInitialized ] = true;
  2360. properties[ subBuildOutput ] = this.getOutputNode( builder );
  2361. properties[ subBuildOutput ].build( builder );
  2362. // If the shaderNode has subBuilds, add them to the chaining nodes
  2363. // so they can be built later in the build process.
  2364. if ( this.shaderNode.subBuilds ) {
  2365. for ( const node of builder.chaining ) {
  2366. const nodeData = builder.getDataFromNode( node, 'any' );
  2367. nodeData.subBuilds = nodeData.subBuilds || new Set();
  2368. for ( const subBuild of this.shaderNode.subBuilds ) {
  2369. nodeData.subBuilds.add( subBuild );
  2370. }
  2371. //builder.getDataFromNode( node ).subBuilds = nodeData.subBuilds;
  2372. }
  2373. }
  2374. }
  2375. result = properties[ subBuildOutput ];
  2376. } else if ( buildStage === 'analyze' ) {
  2377. outputNode.build( builder, output );
  2378. } else if ( buildStage === 'generate' ) {
  2379. result = outputNode.build( builder, output ) || '';
  2380. }
  2381. return result;
  2382. }
  2383. }
  2384. class ShaderNodeInternal extends Node {
  2385. constructor( jsFunc, nodeType ) {
  2386. super( nodeType );
  2387. this.jsFunc = jsFunc;
  2388. this.layout = null;
  2389. this.global = true;
  2390. this.once = false;
  2391. }
  2392. setLayout( layout ) {
  2393. this.layout = layout;
  2394. return this;
  2395. }
  2396. call( inputs = null ) {
  2397. nodeObjects( inputs );
  2398. return nodeObject( new ShaderCallNodeInternal( this, inputs ) );
  2399. }
  2400. setup() {
  2401. return this.call();
  2402. }
  2403. }
  2404. const bools = [ false, true ];
  2405. const uints = [ 0, 1, 2, 3 ];
  2406. const ints = [ -1, -2 ];
  2407. 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 ];
  2408. const boolsCacheMap = new Map();
  2409. for ( const bool of bools ) boolsCacheMap.set( bool, new ConstNode( bool ) );
  2410. const uintsCacheMap = new Map();
  2411. for ( const uint of uints ) uintsCacheMap.set( uint, new ConstNode( uint, 'uint' ) );
  2412. const intsCacheMap = new Map( [ ...uintsCacheMap ].map( el => new ConstNode( el.value, 'int' ) ) );
  2413. for ( const int of ints ) intsCacheMap.set( int, new ConstNode( int, 'int' ) );
  2414. const floatsCacheMap = new Map( [ ...intsCacheMap ].map( el => new ConstNode( el.value ) ) );
  2415. for ( const float of floats ) floatsCacheMap.set( float, new ConstNode( float ) );
  2416. for ( const float of floats ) floatsCacheMap.set( - float, new ConstNode( - float ) );
  2417. const cacheMaps = { bool: boolsCacheMap, uint: uintsCacheMap, ints: intsCacheMap, float: floatsCacheMap };
  2418. const constNodesCacheMap = new Map( [ ...boolsCacheMap, ...floatsCacheMap ] );
  2419. const getConstNode = ( value, type ) => {
  2420. if ( constNodesCacheMap.has( value ) ) {
  2421. return constNodesCacheMap.get( value );
  2422. } else if ( value.isNode === true ) {
  2423. return value;
  2424. } else {
  2425. return new ConstNode( value, type );
  2426. }
  2427. };
  2428. const ConvertType = function ( type, cacheMap = null ) {
  2429. return ( ...params ) => {
  2430. if ( params.length === 0 || ( ! [ 'bool', 'float', 'int', 'uint' ].includes( type ) && params.every( param => typeof param !== 'object' ) ) ) {
  2431. params = [ getValueFromType( type, ...params ) ];
  2432. }
  2433. if ( params.length === 1 && cacheMap !== null && cacheMap.has( params[ 0 ] ) ) {
  2434. return nodeObject( cacheMap.get( params[ 0 ] ) );
  2435. }
  2436. if ( params.length === 1 ) {
  2437. const node = getConstNode( params[ 0 ], type );
  2438. if ( node.nodeType === type ) return nodeObject( node );
  2439. return nodeObject( new ConvertNode( node, type ) );
  2440. }
  2441. const nodes = params.map( param => getConstNode( param ) );
  2442. return nodeObject( new JoinNode( nodes, type ) );
  2443. };
  2444. };
  2445. // exports
  2446. const defined = ( v ) => typeof v === 'object' && v !== null ? v.value : v; // TODO: remove boolean conversion and defined function
  2447. // utils
  2448. const getConstNodeType = ( value ) => ( value !== undefined && value !== null ) ? ( value.nodeType || value.convertTo || ( typeof value === 'string' ? value : null ) ) : null;
  2449. // shader node base
  2450. function ShaderNode( jsFunc, nodeType ) {
  2451. return new Proxy( new ShaderNodeInternal( jsFunc, nodeType ), shaderNodeHandler );
  2452. }
  2453. const nodeObject = ( val, altType = null ) => /* new */ ShaderNodeObject( val, altType );
  2454. const nodeObjects = ( val, altType = null ) => new ShaderNodeObjects( val, altType );
  2455. const nodeArray = ( val, altType = null ) => new ShaderNodeArray( val, altType );
  2456. const nodeProxy = ( ...params ) => new ShaderNodeProxy( ...params );
  2457. const nodeImmutable = ( ...params ) => new ShaderNodeImmutable( ...params );
  2458. let fnId = 0;
  2459. const Fn = ( jsFunc, layout = null ) => {
  2460. let nodeType = null;
  2461. if ( layout !== null ) {
  2462. if ( typeof layout === 'object' ) {
  2463. nodeType = layout.return;
  2464. } else {
  2465. if ( typeof layout === 'string' ) {
  2466. nodeType = layout;
  2467. } else {
  2468. console.error( 'THREE.TSL: Invalid layout type.' );
  2469. }
  2470. layout = null;
  2471. }
  2472. }
  2473. const shaderNode = new ShaderNode( jsFunc, nodeType );
  2474. const fn = ( ...params ) => {
  2475. let inputs;
  2476. nodeObjects( params );
  2477. const isArrayAsParameter = params[ 0 ] && ( params[ 0 ].isNode || Object.getPrototypeOf( params[ 0 ] ) !== Object.prototype );
  2478. if ( isArrayAsParameter ) {
  2479. inputs = [ ...params ];
  2480. } else {
  2481. inputs = params[ 0 ];
  2482. }
  2483. const fnCall = shaderNode.call( inputs );
  2484. if ( nodeType === 'void' ) fnCall.toStack();
  2485. return fnCall;
  2486. };
  2487. fn.shaderNode = shaderNode;
  2488. fn.id = shaderNode.id;
  2489. fn.isFn = true;
  2490. fn.getNodeType = ( ...params ) => shaderNode.getNodeType( ...params );
  2491. fn.getCacheKey = ( ...params ) => shaderNode.getCacheKey( ...params );
  2492. fn.setLayout = ( layout ) => {
  2493. shaderNode.setLayout( layout );
  2494. return fn;
  2495. };
  2496. fn.once = ( subBuilds = null ) => {
  2497. shaderNode.once = true;
  2498. shaderNode.subBuilds = subBuilds;
  2499. return fn;
  2500. };
  2501. if ( layout !== null ) {
  2502. if ( typeof layout.inputs !== 'object' ) {
  2503. const fullLayout = {
  2504. name: 'fn' + fnId ++,
  2505. type: nodeType,
  2506. inputs: []
  2507. };
  2508. for ( const name in layout ) {
  2509. if ( name === 'return' ) continue;
  2510. fullLayout.inputs.push( {
  2511. name: name,
  2512. type: layout[ name ]
  2513. } );
  2514. }
  2515. layout = fullLayout;
  2516. }
  2517. fn.setLayout( layout );
  2518. }
  2519. return fn;
  2520. };
  2521. //
  2522. const setCurrentStack = ( stack ) => {
  2523. currentStack = stack;
  2524. };
  2525. const getCurrentStack = () => currentStack;
  2526. /**
  2527. * Represent a conditional node using if/else statements.
  2528. *
  2529. * ```js
  2530. * If( condition, function )
  2531. * .ElseIf( condition, function )
  2532. * .Else( function )
  2533. * ```
  2534. * @tsl
  2535. * @function
  2536. * @param {...any} params - The parameters for the conditional node.
  2537. * @returns {StackNode} The conditional node.
  2538. */
  2539. const If = ( ...params ) => currentStack.If( ...params );
  2540. /**
  2541. * Represent a conditional node using switch/case statements.
  2542. *
  2543. * ```js
  2544. * Switch( value )
  2545. * .Case( 1, function )
  2546. * .Case( 2, 3, 4, function )
  2547. * .Default( function )
  2548. * ```
  2549. * @tsl
  2550. * @function
  2551. * @param {...any} params - The parameters for the conditional node.
  2552. * @returns {StackNode} The conditional node.
  2553. */
  2554. const Switch = ( ...params ) => currentStack.Switch( ...params );
  2555. /**
  2556. * Add the given node to the current stack.
  2557. *
  2558. * @param {Node} node - The node to add.
  2559. * @returns {Node} The node that was added to the stack.
  2560. */
  2561. function Stack( node ) {
  2562. if ( currentStack ) currentStack.add( node );
  2563. return node;
  2564. }
  2565. addMethodChaining( 'toStack', Stack );
  2566. // types
  2567. const color = new ConvertType( 'color' );
  2568. const float = new ConvertType( 'float', cacheMaps.float );
  2569. const int = new ConvertType( 'int', cacheMaps.ints );
  2570. const uint = new ConvertType( 'uint', cacheMaps.uint );
  2571. const bool = new ConvertType( 'bool', cacheMaps.bool );
  2572. const vec2 = new ConvertType( 'vec2' );
  2573. const ivec2 = new ConvertType( 'ivec2' );
  2574. const uvec2 = new ConvertType( 'uvec2' );
  2575. const bvec2 = new ConvertType( 'bvec2' );
  2576. const vec3 = new ConvertType( 'vec3' );
  2577. const ivec3 = new ConvertType( 'ivec3' );
  2578. const uvec3 = new ConvertType( 'uvec3' );
  2579. const bvec3 = new ConvertType( 'bvec3' );
  2580. const vec4 = new ConvertType( 'vec4' );
  2581. const ivec4 = new ConvertType( 'ivec4' );
  2582. const uvec4 = new ConvertType( 'uvec4' );
  2583. const bvec4 = new ConvertType( 'bvec4' );
  2584. const mat2 = new ConvertType( 'mat2' );
  2585. const mat3 = new ConvertType( 'mat3' );
  2586. const mat4 = new ConvertType( 'mat4' );
  2587. const string = ( value = '' ) => nodeObject( new ConstNode( value, 'string' ) );
  2588. const arrayBuffer = ( value ) => nodeObject( new ConstNode( value, 'ArrayBuffer' ) );
  2589. addMethodChaining( 'toColor', color );
  2590. addMethodChaining( 'toFloat', float );
  2591. addMethodChaining( 'toInt', int );
  2592. addMethodChaining( 'toUint', uint );
  2593. addMethodChaining( 'toBool', bool );
  2594. addMethodChaining( 'toVec2', vec2 );
  2595. addMethodChaining( 'toIVec2', ivec2 );
  2596. addMethodChaining( 'toUVec2', uvec2 );
  2597. addMethodChaining( 'toBVec2', bvec2 );
  2598. addMethodChaining( 'toVec3', vec3 );
  2599. addMethodChaining( 'toIVec3', ivec3 );
  2600. addMethodChaining( 'toUVec3', uvec3 );
  2601. addMethodChaining( 'toBVec3', bvec3 );
  2602. addMethodChaining( 'toVec4', vec4 );
  2603. addMethodChaining( 'toIVec4', ivec4 );
  2604. addMethodChaining( 'toUVec4', uvec4 );
  2605. addMethodChaining( 'toBVec4', bvec4 );
  2606. addMethodChaining( 'toMat2', mat2 );
  2607. addMethodChaining( 'toMat3', mat3 );
  2608. addMethodChaining( 'toMat4', mat4 );
  2609. // basic nodes
  2610. const element = /*@__PURE__*/ nodeProxy( ArrayElementNode ).setParameterLength( 2 );
  2611. const convert = ( node, types ) => nodeObject( new ConvertNode( nodeObject( node ), types ) );
  2612. const split = ( node, channels ) => nodeObject( new SplitNode( nodeObject( node ), channels ) );
  2613. addMethodChaining( 'element', element );
  2614. addMethodChaining( 'convert', convert );
  2615. // deprecated
  2616. /**
  2617. * @tsl
  2618. * @function
  2619. * @deprecated since r176. Use {@link Stack} instead.
  2620. *
  2621. * @param {Node} node - The node to add.
  2622. * @returns {Function}
  2623. */
  2624. const append = ( node ) => { // @deprecated, r176
  2625. console.warn( 'THREE.TSL: append() has been renamed to Stack().' );
  2626. return Stack( node );
  2627. };
  2628. addMethodChaining( 'append', ( node ) => { // @deprecated, r176
  2629. console.warn( 'THREE.TSL: .append() has been renamed to .toStack().' );
  2630. return Stack( node );
  2631. } );
  2632. /**
  2633. * This class represents a shader property. It can be used
  2634. * to explicitly define a property and assign a value to it.
  2635. *
  2636. * ```js
  2637. * const threshold = property( 'float', 'threshold' ).assign( THRESHOLD );
  2638. *```
  2639. * `PropertyNode` is used by the engine to predefined common material properties
  2640. * for TSL code.
  2641. *
  2642. * @augments Node
  2643. */
  2644. class PropertyNode extends Node {
  2645. static get type() {
  2646. return 'PropertyNode';
  2647. }
  2648. /**
  2649. * Constructs a new property node.
  2650. *
  2651. * @param {string} nodeType - The type of the node.
  2652. * @param {?string} [name=null] - The name of the property in the shader.
  2653. * @param {boolean} [varying=false] - Whether this property is a varying or not.
  2654. */
  2655. constructor( nodeType, name = null, varying = false ) {
  2656. super( nodeType );
  2657. /**
  2658. * The name of the property in the shader. If no name is defined,
  2659. * the node system auto-generates one.
  2660. *
  2661. * @type {?string}
  2662. * @default null
  2663. */
  2664. this.name = name;
  2665. /**
  2666. * Whether this property is a varying or not.
  2667. *
  2668. * @type {boolean}
  2669. * @default false
  2670. */
  2671. this.varying = varying;
  2672. /**
  2673. * This flag can be used for type testing.
  2674. *
  2675. * @type {boolean}
  2676. * @readonly
  2677. * @default true
  2678. */
  2679. this.isPropertyNode = true;
  2680. /**
  2681. * This flag is used for global cache.
  2682. *
  2683. * @type {boolean}
  2684. * @default true
  2685. */
  2686. this.global = true;
  2687. }
  2688. getHash( builder ) {
  2689. return this.name || super.getHash( builder );
  2690. }
  2691. generate( builder ) {
  2692. let nodeVar;
  2693. if ( this.varying === true ) {
  2694. nodeVar = builder.getVaryingFromNode( this, this.name );
  2695. nodeVar.needsInterpolation = true;
  2696. } else {
  2697. nodeVar = builder.getVarFromNode( this, this.name );
  2698. }
  2699. return builder.getPropertyName( nodeVar );
  2700. }
  2701. }
  2702. /**
  2703. * TSL function for creating a property node.
  2704. *
  2705. * @tsl
  2706. * @function
  2707. * @param {string} type - The type of the node.
  2708. * @param {?string} [name=null] - The name of the property in the shader.
  2709. * @returns {PropertyNode}
  2710. */
  2711. const property = ( type, name ) => nodeObject( new PropertyNode( type, name ) );
  2712. /**
  2713. * TSL function for creating a varying property node.
  2714. *
  2715. * @tsl
  2716. * @function
  2717. * @param {string} type - The type of the node.
  2718. * @param {?string} [name=null] - The name of the varying in the shader.
  2719. * @returns {PropertyNode}
  2720. */
  2721. const varyingProperty = ( type, name ) => nodeObject( new PropertyNode( type, name, true ) );
  2722. /**
  2723. * TSL object that represents the shader variable `DiffuseColor`.
  2724. *
  2725. * @tsl
  2726. * @type {PropertyNode<vec4>}
  2727. */
  2728. const diffuseColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'DiffuseColor' );
  2729. /**
  2730. * TSL object that represents the shader variable `EmissiveColor`.
  2731. *
  2732. * @tsl
  2733. * @type {PropertyNode<vec3>}
  2734. */
  2735. const emissive = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'EmissiveColor' );
  2736. /**
  2737. * TSL object that represents the shader variable `Roughness`.
  2738. *
  2739. * @tsl
  2740. * @type {PropertyNode<float>}
  2741. */
  2742. const roughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Roughness' );
  2743. /**
  2744. * TSL object that represents the shader variable `Metalness`.
  2745. *
  2746. * @tsl
  2747. * @type {PropertyNode<float>}
  2748. */
  2749. const metalness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Metalness' );
  2750. /**
  2751. * TSL object that represents the shader variable `Clearcoat`.
  2752. *
  2753. * @tsl
  2754. * @type {PropertyNode<float>}
  2755. */
  2756. const clearcoat = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Clearcoat' );
  2757. /**
  2758. * TSL object that represents the shader variable `ClearcoatRoughness`.
  2759. *
  2760. * @tsl
  2761. * @type {PropertyNode<float>}
  2762. */
  2763. const clearcoatRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'ClearcoatRoughness' );
  2764. /**
  2765. * TSL object that represents the shader variable `Sheen`.
  2766. *
  2767. * @tsl
  2768. * @type {PropertyNode<vec3>}
  2769. */
  2770. const sheen = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'Sheen' );
  2771. /**
  2772. * TSL object that represents the shader variable `SheenRoughness`.
  2773. *
  2774. * @tsl
  2775. * @type {PropertyNode<float>}
  2776. */
  2777. const sheenRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SheenRoughness' );
  2778. /**
  2779. * TSL object that represents the shader variable `Iridescence`.
  2780. *
  2781. * @tsl
  2782. * @type {PropertyNode<float>}
  2783. */
  2784. const iridescence = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Iridescence' );
  2785. /**
  2786. * TSL object that represents the shader variable `IridescenceIOR`.
  2787. *
  2788. * @tsl
  2789. * @type {PropertyNode<float>}
  2790. */
  2791. const iridescenceIOR = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceIOR' );
  2792. /**
  2793. * TSL object that represents the shader variable `IridescenceThickness`.
  2794. *
  2795. * @tsl
  2796. * @type {PropertyNode<float>}
  2797. */
  2798. const iridescenceThickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceThickness' );
  2799. /**
  2800. * TSL object that represents the shader variable `AlphaT`.
  2801. *
  2802. * @tsl
  2803. * @type {PropertyNode<float>}
  2804. */
  2805. const alphaT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AlphaT' );
  2806. /**
  2807. * TSL object that represents the shader variable `Anisotropy`.
  2808. *
  2809. * @tsl
  2810. * @type {PropertyNode<float>}
  2811. */
  2812. const anisotropy = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Anisotropy' );
  2813. /**
  2814. * TSL object that represents the shader variable `AnisotropyT`.
  2815. *
  2816. * @tsl
  2817. * @type {PropertyNode<vec3>}
  2818. */
  2819. const anisotropyT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyT' );
  2820. /**
  2821. * TSL object that represents the shader variable `AnisotropyB`.
  2822. *
  2823. * @tsl
  2824. * @type {PropertyNode<vec3>}
  2825. */
  2826. const anisotropyB = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyB' );
  2827. /**
  2828. * TSL object that represents the shader variable `SpecularColor`.
  2829. *
  2830. * @tsl
  2831. * @type {PropertyNode<color>}
  2832. */
  2833. const specularColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'SpecularColor' );
  2834. /**
  2835. * TSL object that represents the shader variable `SpecularF90`.
  2836. *
  2837. * @tsl
  2838. * @type {PropertyNode<float>}
  2839. */
  2840. const specularF90 = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SpecularF90' );
  2841. /**
  2842. * TSL object that represents the shader variable `Shininess`.
  2843. *
  2844. * @tsl
  2845. * @type {PropertyNode<float>}
  2846. */
  2847. const shininess = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Shininess' );
  2848. /**
  2849. * TSL object that represents the shader variable `Output`.
  2850. *
  2851. * @tsl
  2852. * @type {PropertyNode<vec4>}
  2853. */
  2854. const output = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'Output' );
  2855. /**
  2856. * TSL object that represents the shader variable `dashSize`.
  2857. *
  2858. * @tsl
  2859. * @type {PropertyNode<float>}
  2860. */
  2861. const dashSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'dashSize' );
  2862. /**
  2863. * TSL object that represents the shader variable `gapSize`.
  2864. *
  2865. * @tsl
  2866. * @type {PropertyNode<float>}
  2867. */
  2868. const gapSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'gapSize' );
  2869. /**
  2870. * TSL object that represents the shader variable `pointWidth`.
  2871. *
  2872. * @tsl
  2873. * @type {PropertyNode<float>}
  2874. */
  2875. const pointWidth = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'pointWidth' );
  2876. /**
  2877. * TSL object that represents the shader variable `IOR`.
  2878. *
  2879. * @tsl
  2880. * @type {PropertyNode<float>}
  2881. */
  2882. const ior = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IOR' );
  2883. /**
  2884. * TSL object that represents the shader variable `Transmission`.
  2885. *
  2886. * @tsl
  2887. * @type {PropertyNode<float>}
  2888. */
  2889. const transmission = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Transmission' );
  2890. /**
  2891. * TSL object that represents the shader variable `Thickness`.
  2892. *
  2893. * @tsl
  2894. * @type {PropertyNode<float>}
  2895. */
  2896. const thickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Thickness' );
  2897. /**
  2898. * TSL object that represents the shader variable `AttenuationDistance`.
  2899. *
  2900. * @tsl
  2901. * @type {PropertyNode<float>}
  2902. */
  2903. const attenuationDistance = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AttenuationDistance' );
  2904. /**
  2905. * TSL object that represents the shader variable `AttenuationColor`.
  2906. *
  2907. * @tsl
  2908. * @type {PropertyNode<color>}
  2909. */
  2910. const attenuationColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'AttenuationColor' );
  2911. /**
  2912. * TSL object that represents the shader variable `Dispersion`.
  2913. *
  2914. * @tsl
  2915. * @type {PropertyNode<float>}
  2916. */
  2917. const dispersion = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Dispersion' );
  2918. /**
  2919. * This node can be used to group single instances of {@link UniformNode}
  2920. * and manage them as a uniform buffer.
  2921. *
  2922. * In most cases, the predefined nodes `objectGroup`, `renderGroup` and `frameGroup`
  2923. * will be used when defining the {@link UniformNode#groupNode} property.
  2924. *
  2925. * - `objectGroup`: Uniform buffer per object.
  2926. * - `renderGroup`: Shared uniform buffer, updated once per render call.
  2927. * - `frameGroup`: Shared uniform buffer, updated once per frame.
  2928. *
  2929. * @augments Node
  2930. */
  2931. class UniformGroupNode extends Node {
  2932. static get type() {
  2933. return 'UniformGroupNode';
  2934. }
  2935. /**
  2936. * Constructs a new uniform group node.
  2937. *
  2938. * @param {string} name - The name of the uniform group node.
  2939. * @param {boolean} [shared=false] - Whether this uniform group node is shared or not.
  2940. * @param {number} [order=1] - Influences the internal sorting.
  2941. */
  2942. constructor( name, shared = false, order = 1 ) {
  2943. super( 'string' );
  2944. /**
  2945. * The name of the uniform group node.
  2946. *
  2947. * @type {string}
  2948. */
  2949. this.name = name;
  2950. /**
  2951. * Whether this uniform group node is shared or not.
  2952. *
  2953. * @type {boolean}
  2954. * @default false
  2955. */
  2956. this.shared = shared;
  2957. /**
  2958. * Influences the internal sorting.
  2959. * TODO: Add details when this property should be changed.
  2960. *
  2961. * @type {number}
  2962. * @default 1
  2963. */
  2964. this.order = order;
  2965. /**
  2966. * This flag can be used for type testing.
  2967. *
  2968. * @type {boolean}
  2969. * @readonly
  2970. * @default true
  2971. */
  2972. this.isUniformGroup = true;
  2973. }
  2974. serialize( data ) {
  2975. super.serialize( data );
  2976. data.name = this.name;
  2977. data.version = this.version;
  2978. data.shared = this.shared;
  2979. }
  2980. deserialize( data ) {
  2981. super.deserialize( data );
  2982. this.name = data.name;
  2983. this.version = data.version;
  2984. this.shared = data.shared;
  2985. }
  2986. }
  2987. /**
  2988. * TSL function for creating a uniform group node with the given name.
  2989. *
  2990. * @tsl
  2991. * @function
  2992. * @param {string} name - The name of the uniform group node.
  2993. * @returns {UniformGroupNode}
  2994. */
  2995. const uniformGroup = ( name ) => new UniformGroupNode( name );
  2996. /**
  2997. * TSL function for creating a shared uniform group node with the given name and order.
  2998. *
  2999. * @tsl
  3000. * @function
  3001. * @param {string} name - The name of the uniform group node.
  3002. * @param {number} [order=0] - Influences the internal sorting.
  3003. * @returns {UniformGroupNode}
  3004. */
  3005. const sharedUniformGroup = ( name, order = 0 ) => new UniformGroupNode( name, true, order );
  3006. /**
  3007. * TSL object that represents a shared uniform group node which is updated once per frame.
  3008. *
  3009. * @tsl
  3010. * @type {UniformGroupNode}
  3011. */
  3012. const frameGroup = /*@__PURE__*/ sharedUniformGroup( 'frame' );
  3013. /**
  3014. * TSL object that represents a shared uniform group node which is updated once per render.
  3015. *
  3016. * @tsl
  3017. * @type {UniformGroupNode}
  3018. */
  3019. const renderGroup = /*@__PURE__*/ sharedUniformGroup( 'render' );
  3020. /**
  3021. * TSL object that represents a uniform group node which is updated once per object.
  3022. *
  3023. * @tsl
  3024. * @type {UniformGroupNode}
  3025. */
  3026. const objectGroup = /*@__PURE__*/ uniformGroup( 'object' );
  3027. /**
  3028. * Class for representing a uniform.
  3029. *
  3030. * @augments InputNode
  3031. */
  3032. class UniformNode extends InputNode {
  3033. static get type() {
  3034. return 'UniformNode';
  3035. }
  3036. /**
  3037. * Constructs a new uniform node.
  3038. *
  3039. * @param {any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  3040. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  3041. */
  3042. constructor( value, nodeType = null ) {
  3043. super( value, nodeType );
  3044. /**
  3045. * This flag can be used for type testing.
  3046. *
  3047. * @type {boolean}
  3048. * @readonly
  3049. * @default true
  3050. */
  3051. this.isUniformNode = true;
  3052. /**
  3053. * The name or label of the uniform.
  3054. *
  3055. * @type {string}
  3056. * @default ''
  3057. */
  3058. this.name = '';
  3059. /**
  3060. * The uniform group of this uniform. By default, uniforms are
  3061. * managed per object but they might belong to a shared group
  3062. * which is updated per frame or render call.
  3063. *
  3064. * @type {UniformGroupNode}
  3065. */
  3066. this.groupNode = objectGroup;
  3067. }
  3068. /**
  3069. * Sets the {@link UniformNode#name} property.
  3070. *
  3071. * @param {string} name - The name of the uniform.
  3072. * @return {UniformNode} A reference to this node.
  3073. */
  3074. label( name ) {
  3075. this.name = name;
  3076. return this;
  3077. }
  3078. /**
  3079. * Sets the {@link UniformNode#groupNode} property.
  3080. *
  3081. * @param {UniformGroupNode} group - The uniform group.
  3082. * @return {UniformNode} A reference to this node.
  3083. */
  3084. setGroup( group ) {
  3085. this.groupNode = group;
  3086. return this;
  3087. }
  3088. /**
  3089. * Returns the {@link UniformNode#groupNode}.
  3090. *
  3091. * @return {UniformGroupNode} The uniform group.
  3092. */
  3093. getGroup() {
  3094. return this.groupNode;
  3095. }
  3096. /**
  3097. * By default, this method returns the result of {@link Node#getHash} but derived
  3098. * classes might overwrite this method with a different implementation.
  3099. *
  3100. * @param {NodeBuilder} builder - The current node builder.
  3101. * @return {string} The uniform hash.
  3102. */
  3103. getUniformHash( builder ) {
  3104. return this.getHash( builder );
  3105. }
  3106. onUpdate( callback, updateType ) {
  3107. const self = this.getSelf();
  3108. callback = callback.bind( self );
  3109. return super.onUpdate( ( frame ) => {
  3110. const value = callback( frame, self );
  3111. if ( value !== undefined ) {
  3112. this.value = value;
  3113. }
  3114. }, updateType );
  3115. }
  3116. generate( builder, output ) {
  3117. const type = this.getNodeType( builder );
  3118. const hash = this.getUniformHash( builder );
  3119. let sharedNode = builder.getNodeFromHash( hash );
  3120. if ( sharedNode === undefined ) {
  3121. builder.setHashNode( this, hash );
  3122. sharedNode = this;
  3123. }
  3124. const sharedNodeType = sharedNode.getInputType( builder );
  3125. const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, this.name || builder.context.label );
  3126. const propertyName = builder.getPropertyName( nodeUniform );
  3127. if ( builder.context.label !== undefined ) delete builder.context.label;
  3128. return builder.format( propertyName, type, output );
  3129. }
  3130. }
  3131. /**
  3132. * TSL function for creating a uniform node.
  3133. *
  3134. * @tsl
  3135. * @function
  3136. * @param {any} arg1 - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  3137. * @param {string} [arg2] - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  3138. * @returns {UniformNode}
  3139. */
  3140. const uniform = ( arg1, arg2 ) => {
  3141. const nodeType = getConstNodeType( arg2 || arg1 );
  3142. // @TODO: get ConstNode from .traverse() in the future
  3143. const value = ( arg1 && arg1.isNode === true ) ? ( arg1.node && arg1.node.value ) || arg1.value : arg1;
  3144. return nodeObject( new UniformNode( value, nodeType ) );
  3145. };
  3146. /**
  3147. * ArrayNode represents a collection of nodes, typically created using the {@link array} function.
  3148. * ```js
  3149. * const colors = array( [
  3150. * vec3( 1, 0, 0 ),
  3151. * vec3( 0, 1, 0 ),
  3152. * vec3( 0, 0, 1 )
  3153. * ] );
  3154. *
  3155. * const redColor = tintColors.element( 0 );
  3156. *
  3157. * @augments TempNode
  3158. */
  3159. class ArrayNode extends TempNode {
  3160. static get type() {
  3161. return 'ArrayNode';
  3162. }
  3163. /**
  3164. * Constructs a new array node.
  3165. *
  3166. * @param {?string} nodeType - The data type of the elements.
  3167. * @param {number} count - Size of the array.
  3168. * @param {?Array<Node>} [values=null] - Array default values.
  3169. */
  3170. constructor( nodeType, count, values = null ) {
  3171. super( nodeType );
  3172. /**
  3173. * Array size.
  3174. *
  3175. * @type {number}
  3176. */
  3177. this.count = count;
  3178. /**
  3179. * Array default values.
  3180. *
  3181. * @type {?Array<Node>}
  3182. */
  3183. this.values = values;
  3184. /**
  3185. * This flag can be used for type testing.
  3186. *
  3187. * @type {boolean}
  3188. * @readonly
  3189. * @default true
  3190. */
  3191. this.isArrayNode = true;
  3192. }
  3193. /**
  3194. * Returns the node's type.
  3195. *
  3196. * @param {NodeBuilder} builder - The current node builder.
  3197. * @return {string} The type of the node.
  3198. */
  3199. getNodeType( builder ) {
  3200. if ( this.nodeType === null ) {
  3201. this.nodeType = this.values[ 0 ].getNodeType( builder );
  3202. }
  3203. return this.nodeType;
  3204. }
  3205. /**
  3206. * Returns the node's type.
  3207. *
  3208. * @param {NodeBuilder} builder - The current node builder.
  3209. * @return {string} The type of the node.
  3210. */
  3211. getElementType( builder ) {
  3212. return this.getNodeType( builder );
  3213. }
  3214. /**
  3215. * This method builds the output node and returns the resulting array as a shader string.
  3216. *
  3217. * @param {NodeBuilder} builder - The current node builder.
  3218. * @return {string} The generated shader string.
  3219. */
  3220. generate( builder ) {
  3221. const type = this.getNodeType( builder );
  3222. return builder.generateArray( type, this.count, this.values );
  3223. }
  3224. }
  3225. /**
  3226. * TSL function for creating an array node.
  3227. *
  3228. * @tsl
  3229. * @function
  3230. * @param {string|Array<Node>} nodeTypeOrValues - A string representing the element type (e.g., 'vec3')
  3231. * or an array containing the default values (e.g., [ vec3() ]).
  3232. * @param {?number} [count] - Size of the array.
  3233. * @returns {ArrayNode}
  3234. */
  3235. const array = ( ...params ) => {
  3236. let node;
  3237. if ( params.length === 1 ) {
  3238. const values = params[ 0 ];
  3239. node = new ArrayNode( null, values.length, values );
  3240. } else {
  3241. const nodeType = params[ 0 ];
  3242. const count = params[ 1 ];
  3243. node = new ArrayNode( nodeType, count );
  3244. }
  3245. return nodeObject( node );
  3246. };
  3247. addMethodChaining( 'toArray', ( node, count ) => array( Array( count ).fill( node ) ) );
  3248. /**
  3249. * These node represents an assign operation. Meaning a node is assigned
  3250. * to another node.
  3251. *
  3252. * @augments TempNode
  3253. */
  3254. class AssignNode extends TempNode {
  3255. static get type() {
  3256. return 'AssignNode';
  3257. }
  3258. /**
  3259. * Constructs a new assign node.
  3260. *
  3261. * @param {Node} targetNode - The target node.
  3262. * @param {Node} sourceNode - The source type.
  3263. */
  3264. constructor( targetNode, sourceNode ) {
  3265. super();
  3266. /**
  3267. * The target node.
  3268. *
  3269. * @type {Node}
  3270. */
  3271. this.targetNode = targetNode;
  3272. /**
  3273. * The source node.
  3274. *
  3275. * @type {Node}
  3276. */
  3277. this.sourceNode = sourceNode;
  3278. /**
  3279. * This flag can be used for type testing.
  3280. *
  3281. * @type {boolean}
  3282. * @readonly
  3283. * @default true
  3284. */
  3285. this.isAssignNode = true;
  3286. }
  3287. /**
  3288. * Whether this node is used more than once in context of other nodes. This method
  3289. * is overwritten since it always returns `false` (assigns are unique).
  3290. *
  3291. * @return {boolean} A flag that indicates if there is more than one dependency to other nodes. Always `false`.
  3292. */
  3293. hasDependencies() {
  3294. return false;
  3295. }
  3296. getNodeType( builder, output ) {
  3297. return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void';
  3298. }
  3299. /**
  3300. * Whether a split is required when assigning source to target. This can happen when the component length of
  3301. * target and source data type does not match.
  3302. *
  3303. * @param {NodeBuilder} builder - The current node builder.
  3304. * @return {boolean} Whether a split is required when assigning source to target.
  3305. */
  3306. needsSplitAssign( builder ) {
  3307. const { targetNode } = this;
  3308. if ( builder.isAvailable( 'swizzleAssign' ) === false && targetNode.isSplitNode && targetNode.components.length > 1 ) {
  3309. const targetLength = builder.getTypeLength( targetNode.node.getNodeType( builder ) );
  3310. const assignDifferentVector = vectorComponents.join( '' ).slice( 0, targetLength ) !== targetNode.components;
  3311. return assignDifferentVector;
  3312. }
  3313. return false;
  3314. }
  3315. setup( builder ) {
  3316. const { targetNode, sourceNode } = this;
  3317. const properties = builder.getNodeProperties( this );
  3318. properties.sourceNode = sourceNode;
  3319. properties.targetNode = targetNode.context( { assign: true } );
  3320. }
  3321. generate( builder, output ) {
  3322. const { targetNode, sourceNode } = builder.getNodeProperties( this );
  3323. const needsSplitAssign = this.needsSplitAssign( builder );
  3324. const targetType = targetNode.getNodeType( builder );
  3325. const target = targetNode.build( builder );
  3326. const source = sourceNode.build( builder, targetType );
  3327. const sourceType = sourceNode.getNodeType( builder );
  3328. const nodeData = builder.getDataFromNode( this );
  3329. //
  3330. let snippet;
  3331. if ( nodeData.initialized === true ) {
  3332. if ( output !== 'void' ) {
  3333. snippet = target;
  3334. }
  3335. } else if ( needsSplitAssign ) {
  3336. const sourceVar = builder.getVarFromNode( this, null, targetType );
  3337. const sourceProperty = builder.getPropertyName( sourceVar );
  3338. builder.addLineFlowCode( `${ sourceProperty } = ${ source }`, this );
  3339. const splitNode = targetNode.node;
  3340. const splitTargetNode = splitNode.node.context( { assign: true } );
  3341. const targetRoot = splitTargetNode.build( builder );
  3342. for ( let i = 0; i < splitNode.components.length; i ++ ) {
  3343. const component = splitNode.components[ i ];
  3344. builder.addLineFlowCode( `${ targetRoot }.${ component } = ${ sourceProperty }[ ${ i } ]`, this );
  3345. }
  3346. if ( output !== 'void' ) {
  3347. snippet = target;
  3348. }
  3349. } else {
  3350. snippet = `${ target } = ${ source }`;
  3351. if ( output === 'void' || sourceType === 'void' ) {
  3352. builder.addLineFlowCode( snippet, this );
  3353. if ( output !== 'void' ) {
  3354. snippet = target;
  3355. }
  3356. }
  3357. }
  3358. nodeData.initialized = true;
  3359. return builder.format( snippet, targetType, output );
  3360. }
  3361. }
  3362. /**
  3363. * TSL function for creating an assign node.
  3364. *
  3365. * @tsl
  3366. * @function
  3367. * @param {Node} targetNode - The target node.
  3368. * @param {Node} sourceNode - The source type.
  3369. * @returns {AssignNode}
  3370. */
  3371. const assign = /*@__PURE__*/ nodeProxy( AssignNode ).setParameterLength( 2 );
  3372. addMethodChaining( 'assign', assign );
  3373. /**
  3374. * This module represents the call of a {@link FunctionNode}. Developers are usually not confronted
  3375. * with this module since they use the predefined TSL syntax `wgslFn` and `glslFn` which encapsulate
  3376. * this logic.
  3377. *
  3378. * @augments TempNode
  3379. */
  3380. class FunctionCallNode extends TempNode {
  3381. static get type() {
  3382. return 'FunctionCallNode';
  3383. }
  3384. /**
  3385. * Constructs a new function call node.
  3386. *
  3387. * @param {?FunctionNode} functionNode - The function node.
  3388. * @param {Object<string, Node>} [parameters={}] - The parameters for the function call.
  3389. */
  3390. constructor( functionNode = null, parameters = {} ) {
  3391. super();
  3392. /**
  3393. * The function node.
  3394. *
  3395. * @type {?FunctionNode}
  3396. * @default null
  3397. */
  3398. this.functionNode = functionNode;
  3399. /**
  3400. * The parameters of the function call.
  3401. *
  3402. * @type {Object<string, Node>}
  3403. * @default {}
  3404. */
  3405. this.parameters = parameters;
  3406. }
  3407. /**
  3408. * Sets the parameters of the function call node.
  3409. *
  3410. * @param {Object<string, Node>} parameters - The parameters to set.
  3411. * @return {FunctionCallNode} A reference to this node.
  3412. */
  3413. setParameters( parameters ) {
  3414. this.parameters = parameters;
  3415. return this;
  3416. }
  3417. /**
  3418. * Returns the parameters of the function call node.
  3419. *
  3420. * @return {Object<string, Node>} The parameters of this node.
  3421. */
  3422. getParameters() {
  3423. return this.parameters;
  3424. }
  3425. getNodeType( builder ) {
  3426. return this.functionNode.getNodeType( builder );
  3427. }
  3428. generate( builder ) {
  3429. const params = [];
  3430. const functionNode = this.functionNode;
  3431. const inputs = functionNode.getInputs( builder );
  3432. const parameters = this.parameters;
  3433. const generateInput = ( node, inputNode ) => {
  3434. const type = inputNode.type;
  3435. const pointer = type === 'pointer';
  3436. let output;
  3437. if ( pointer ) output = '&' + node.build( builder );
  3438. else output = node.build( builder, type );
  3439. return output;
  3440. };
  3441. if ( Array.isArray( parameters ) ) {
  3442. if ( parameters.length > inputs.length ) {
  3443. console.error( 'THREE.TSL: The number of provided parameters exceeds the expected number of inputs in \'Fn()\'.' );
  3444. parameters.length = inputs.length;
  3445. } else if ( parameters.length < inputs.length ) {
  3446. console.error( 'THREE.TSL: The number of provided parameters is less than the expected number of inputs in \'Fn()\'.' );
  3447. while ( parameters.length < inputs.length ) {
  3448. parameters.push( float( 0 ) );
  3449. }
  3450. }
  3451. for ( let i = 0; i < parameters.length; i ++ ) {
  3452. params.push( generateInput( parameters[ i ], inputs[ i ] ) );
  3453. }
  3454. } else {
  3455. for ( const inputNode of inputs ) {
  3456. const node = parameters[ inputNode.name ];
  3457. if ( node !== undefined ) {
  3458. params.push( generateInput( node, inputNode ) );
  3459. } else {
  3460. console.error( `THREE.TSL: Input '${ inputNode.name }' not found in \'Fn()\'.` );
  3461. params.push( generateInput( float( 0 ), inputNode ) );
  3462. }
  3463. }
  3464. }
  3465. const functionName = functionNode.build( builder, 'property' );
  3466. return `${ functionName }( ${ params.join( ', ' ) } )`;
  3467. }
  3468. }
  3469. const call = ( func, ...params ) => {
  3470. params = params.length > 1 || ( params[ 0 ] && params[ 0 ].isNode === true ) ? nodeArray( params ) : nodeObjects( params[ 0 ] );
  3471. return nodeObject( new FunctionCallNode( nodeObject( func ), params ) );
  3472. };
  3473. addMethodChaining( 'call', call );
  3474. const _vectorOperators = {
  3475. '==': 'equal',
  3476. '!=': 'notEqual',
  3477. '<': 'lessThan',
  3478. '>': 'greaterThan',
  3479. '<=': 'lessThanEqual',
  3480. '>=': 'greaterThanEqual',
  3481. '%': 'mod'
  3482. };
  3483. /**
  3484. * This node represents basic mathematical and logical operations like addition,
  3485. * subtraction or comparisons (e.g. `equal()`).
  3486. *
  3487. * @augments TempNode
  3488. */
  3489. class OperatorNode extends TempNode {
  3490. static get type() {
  3491. return 'OperatorNode';
  3492. }
  3493. /**
  3494. * Constructs a new operator node.
  3495. *
  3496. * @param {string} op - The operator.
  3497. * @param {Node} aNode - The first input.
  3498. * @param {Node} bNode - The second input.
  3499. * @param {...Node} params - Additional input parameters.
  3500. */
  3501. constructor( op, aNode, bNode, ...params ) {
  3502. super();
  3503. if ( params.length > 0 ) {
  3504. let finalOp = new OperatorNode( op, aNode, bNode );
  3505. for ( let i = 0; i < params.length - 1; i ++ ) {
  3506. finalOp = new OperatorNode( op, finalOp, params[ i ] );
  3507. }
  3508. aNode = finalOp;
  3509. bNode = params[ params.length - 1 ];
  3510. }
  3511. /**
  3512. * The operator.
  3513. *
  3514. * @type {string}
  3515. */
  3516. this.op = op;
  3517. /**
  3518. * The first input.
  3519. *
  3520. * @type {Node}
  3521. */
  3522. this.aNode = aNode;
  3523. /**
  3524. * The second input.
  3525. *
  3526. * @type {Node}
  3527. */
  3528. this.bNode = bNode;
  3529. /**
  3530. * This flag can be used for type testing.
  3531. *
  3532. * @type {boolean}
  3533. * @readonly
  3534. * @default true
  3535. */
  3536. this.isOperatorNode = true;
  3537. }
  3538. /**
  3539. * Returns the operator method name.
  3540. *
  3541. * @param {NodeBuilder} builder - The current node builder.
  3542. * @param {string} output - The output type.
  3543. * @returns {string} The operator method name.
  3544. */
  3545. getOperatorMethod( builder, output ) {
  3546. return builder.getMethod( _vectorOperators[ this.op ], output );
  3547. }
  3548. /**
  3549. * This method is overwritten since the node type is inferred from the operator
  3550. * and the input node types.
  3551. *
  3552. * @param {NodeBuilder} builder - The current node builder.
  3553. * @return {string} The node type.
  3554. */
  3555. getNodeType( builder ) {
  3556. const op = this.op;
  3557. const aNode = this.aNode;
  3558. const bNode = this.bNode;
  3559. const typeA = aNode.getNodeType( builder );
  3560. const typeB = bNode ? bNode.getNodeType( builder ) : null;
  3561. if ( typeA === 'void' || typeB === 'void' ) {
  3562. return 'void';
  3563. } else if ( op === '%' ) {
  3564. return typeA;
  3565. } else if ( op === '~' || op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) {
  3566. return builder.getIntegerType( typeA );
  3567. } else if ( op === '!' || op === '&&' || op === '||' || op === '^^' ) {
  3568. return 'bool';
  3569. } else if ( op === '==' || op === '!=' || op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  3570. const typeLength = Math.max( builder.getTypeLength( typeA ), builder.getTypeLength( typeB ) );
  3571. return typeLength > 1 ? `bvec${ typeLength }` : 'bool';
  3572. } else {
  3573. // Handle matrix operations
  3574. if ( builder.isMatrix( typeA ) ) {
  3575. if ( typeB === 'float' ) {
  3576. return typeA; // matrix * scalar = matrix
  3577. } else if ( builder.isVector( typeB ) ) {
  3578. return builder.getVectorFromMatrix( typeA ); // matrix * vector
  3579. } else if ( builder.isMatrix( typeB ) ) {
  3580. return typeA; // matrix * matrix
  3581. }
  3582. } else if ( builder.isMatrix( typeB ) ) {
  3583. if ( typeA === 'float' ) {
  3584. return typeB; // scalar * matrix = matrix
  3585. } else if ( builder.isVector( typeA ) ) {
  3586. return builder.getVectorFromMatrix( typeB ); // vector * matrix
  3587. }
  3588. }
  3589. // Handle non-matrix cases
  3590. if ( builder.getTypeLength( typeB ) > builder.getTypeLength( typeA ) ) {
  3591. // anytype x anytype: use the greater length vector
  3592. return typeB;
  3593. }
  3594. return typeA;
  3595. }
  3596. }
  3597. generate( builder, output ) {
  3598. const op = this.op;
  3599. const { aNode, bNode } = this;
  3600. const type = this.getNodeType( builder );
  3601. let typeA = null;
  3602. let typeB = null;
  3603. if ( type !== 'void' ) {
  3604. typeA = aNode.getNodeType( builder );
  3605. typeB = bNode ? bNode.getNodeType( builder ) : null;
  3606. if ( op === '<' || op === '>' || op === '<=' || op === '>=' || op === '==' || op === '!=' ) {
  3607. if ( builder.isVector( typeA ) ) {
  3608. typeB = typeA;
  3609. } else if ( builder.isVector( typeB ) ) {
  3610. typeA = typeB;
  3611. } else if ( typeA !== typeB ) {
  3612. typeA = typeB = 'float';
  3613. }
  3614. } else if ( op === '>>' || op === '<<' ) {
  3615. typeA = type;
  3616. typeB = builder.changeComponentType( typeB, 'uint' );
  3617. } else if ( op === '%' ) {
  3618. typeA = type;
  3619. typeB = builder.isInteger( typeA ) && builder.isInteger( typeB ) ? typeB : typeA;
  3620. } else if ( builder.isMatrix( typeA ) ) {
  3621. if ( typeB === 'float' ) {
  3622. // Keep matrix type for typeA, but ensure typeB stays float
  3623. typeB = 'float';
  3624. } else if ( builder.isVector( typeB ) ) {
  3625. // matrix x vector
  3626. typeB = builder.getVectorFromMatrix( typeA );
  3627. } else if ( builder.isMatrix( typeB ) ) ; else {
  3628. typeA = typeB = type;
  3629. }
  3630. } else if ( builder.isMatrix( typeB ) ) {
  3631. if ( typeA === 'float' ) {
  3632. // Keep matrix type for typeB, but ensure typeA stays float
  3633. typeA = 'float';
  3634. } else if ( builder.isVector( typeA ) ) {
  3635. // vector x matrix
  3636. typeA = builder.getVectorFromMatrix( typeB );
  3637. } else {
  3638. typeA = typeB = type;
  3639. }
  3640. } else {
  3641. // anytype x anytype
  3642. typeA = typeB = type;
  3643. }
  3644. } else {
  3645. typeA = typeB = type;
  3646. }
  3647. const a = aNode.build( builder, typeA );
  3648. const b = bNode ? bNode.build( builder, typeB ) : null;
  3649. const fnOpSnippet = builder.getFunctionOperator( op );
  3650. if ( output !== 'void' ) {
  3651. const isGLSL = builder.renderer.coordinateSystem === WebGLCoordinateSystem;
  3652. if ( op === '==' || op === '!=' || op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  3653. if ( isGLSL ) {
  3654. if ( builder.isVector( typeA ) ) {
  3655. return builder.format( `${ this.getOperatorMethod( builder, output ) }( ${ a }, ${ b } )`, type, output );
  3656. } else {
  3657. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  3658. }
  3659. } else {
  3660. // WGSL
  3661. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  3662. }
  3663. } else if ( op === '%' ) {
  3664. if ( builder.isInteger( typeB ) ) {
  3665. return builder.format( `( ${ a } % ${ b } )`, type, output );
  3666. } else {
  3667. return builder.format( `${ this.getOperatorMethod( builder, type ) }( ${ a }, ${ b } )`, type, output );
  3668. }
  3669. } else if ( op === '!' || op === '~' ) {
  3670. return builder.format( `(${op}${a})`, typeA, output );
  3671. } else if ( fnOpSnippet ) {
  3672. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  3673. } else {
  3674. // Handle matrix operations
  3675. if ( builder.isMatrix( typeA ) && typeB === 'float' ) {
  3676. return builder.format( `( ${ b } ${ op } ${ a } )`, type, output );
  3677. } else if ( typeA === 'float' && builder.isMatrix( typeB ) ) {
  3678. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  3679. } else {
  3680. let snippet = `( ${ a } ${ op } ${ b } )`;
  3681. if ( ! isGLSL && type === 'bool' && builder.isVector( typeA ) && builder.isVector( typeB ) ) {
  3682. snippet = `all${ snippet }`;
  3683. }
  3684. return builder.format( snippet, type, output );
  3685. }
  3686. }
  3687. } else if ( typeA !== 'void' ) {
  3688. if ( fnOpSnippet ) {
  3689. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  3690. } else {
  3691. if ( builder.isMatrix( typeA ) && typeB === 'float' ) {
  3692. return builder.format( `${ b } ${ op } ${ a }`, type, output );
  3693. } else {
  3694. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  3695. }
  3696. }
  3697. }
  3698. }
  3699. serialize( data ) {
  3700. super.serialize( data );
  3701. data.op = this.op;
  3702. }
  3703. deserialize( data ) {
  3704. super.deserialize( data );
  3705. this.op = data.op;
  3706. }
  3707. }
  3708. /**
  3709. * Returns the addition of two or more value.
  3710. *
  3711. * @tsl
  3712. * @function
  3713. * @param {Node} a - The first input.
  3714. * @param {Node} b - The second input.
  3715. * @param {...Node} params - Additional input parameters.
  3716. * @returns {OperatorNode}
  3717. */
  3718. const add = /*@__PURE__*/ nodeProxy( OperatorNode, '+' ).setParameterLength( 2, Infinity ).setName( 'add' );
  3719. /**
  3720. * Returns the subtraction of two or more value.
  3721. *
  3722. * @tsl
  3723. * @function
  3724. * @param {Node} a - The first input.
  3725. * @param {Node} b - The second input.
  3726. * @param {...Node} params - Additional input parameters.
  3727. * @returns {OperatorNode}
  3728. */
  3729. const sub = /*@__PURE__*/ nodeProxy( OperatorNode, '-' ).setParameterLength( 2, Infinity ).setName( 'sub' );
  3730. /**
  3731. * Returns the multiplication of two or more value.
  3732. *
  3733. * @tsl
  3734. * @function
  3735. * @param {Node} a - The first input.
  3736. * @param {Node} b - The second input.
  3737. * @param {...Node} params - Additional input parameters.
  3738. * @returns {OperatorNode}
  3739. */
  3740. const mul = /*@__PURE__*/ nodeProxy( OperatorNode, '*' ).setParameterLength( 2, Infinity ).setName( 'mul' );
  3741. /**
  3742. * Returns the division of two or more value.
  3743. *
  3744. * @tsl
  3745. * @function
  3746. * @param {Node} a - The first input.
  3747. * @param {Node} b - The second input.
  3748. * @param {...Node} params - Additional input parameters.
  3749. * @returns {OperatorNode}
  3750. */
  3751. const div = /*@__PURE__*/ nodeProxy( OperatorNode, '/' ).setParameterLength( 2, Infinity ).setName( 'div' );
  3752. /**
  3753. * Computes the remainder of dividing the first node by the second one.
  3754. *
  3755. * @tsl
  3756. * @function
  3757. * @param {Node} a - The first input.
  3758. * @param {Node} b - The second input.
  3759. * @returns {OperatorNode}
  3760. */
  3761. const mod = /*@__PURE__*/ nodeProxy( OperatorNode, '%' ).setParameterLength( 2 ).setName( 'mod' );
  3762. /**
  3763. * Checks if two nodes are equal.
  3764. *
  3765. * @tsl
  3766. * @function
  3767. * @param {Node} a - The first input.
  3768. * @param {Node} b - The second input.
  3769. * @returns {OperatorNode}
  3770. */
  3771. const equal = /*@__PURE__*/ nodeProxy( OperatorNode, '==' ).setParameterLength( 2 ).setName( 'equal' );
  3772. /**
  3773. * Checks if two nodes are not equal.
  3774. *
  3775. * @tsl
  3776. * @function
  3777. * @param {Node} a - The first input.
  3778. * @param {Node} b - The second input.
  3779. * @returns {OperatorNode}
  3780. */
  3781. const notEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '!=' ).setParameterLength( 2 ).setName( 'notEqual' );
  3782. /**
  3783. * Checks if the first node is less than the second.
  3784. *
  3785. * @tsl
  3786. * @function
  3787. * @param {Node} a - The first input.
  3788. * @param {Node} b - The second input.
  3789. * @returns {OperatorNode}
  3790. */
  3791. const lessThan = /*@__PURE__*/ nodeProxy( OperatorNode, '<' ).setParameterLength( 2 ).setName( 'lessThan' );
  3792. /**
  3793. * Checks if the first node is greater than the second.
  3794. *
  3795. * @tsl
  3796. * @function
  3797. * @param {Node} a - The first input.
  3798. * @param {Node} b - The second input.
  3799. * @returns {OperatorNode}
  3800. */
  3801. const greaterThan = /*@__PURE__*/ nodeProxy( OperatorNode, '>' ).setParameterLength( 2 ).setName( 'greaterThan' );
  3802. /**
  3803. * Checks if the first node is less than or equal to the second.
  3804. *
  3805. * @tsl
  3806. * @function
  3807. * @param {Node} a - The first input.
  3808. * @param {Node} b - The second input.
  3809. * @returns {OperatorNode}
  3810. */
  3811. const lessThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '<=' ).setParameterLength( 2 ).setName( 'lessThanEqual' );
  3812. /**
  3813. * Checks if the first node is greater than or equal to the second.
  3814. *
  3815. * @tsl
  3816. * @function
  3817. * @param {Node} a - The first input.
  3818. * @param {Node} b - The second input.
  3819. * @returns {OperatorNode}
  3820. */
  3821. const greaterThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '>=' ).setParameterLength( 2 ).setName( 'greaterThanEqual' );
  3822. /**
  3823. * Performs a logical AND operation on multiple nodes.
  3824. *
  3825. * @tsl
  3826. * @function
  3827. * @param {...Node} nodes - The input nodes to be combined using AND.
  3828. * @returns {OperatorNode}
  3829. */
  3830. const and = /*@__PURE__*/ nodeProxy( OperatorNode, '&&' ).setParameterLength( 2, Infinity ).setName( 'and' );
  3831. /**
  3832. * Performs a logical OR operation on multiple nodes.
  3833. *
  3834. * @tsl
  3835. * @function
  3836. * @param {...Node} nodes - The input nodes to be combined using OR.
  3837. * @returns {OperatorNode}
  3838. */
  3839. const or = /*@__PURE__*/ nodeProxy( OperatorNode, '||' ).setParameterLength( 2, Infinity ).setName( 'or' );
  3840. /**
  3841. * Performs logical NOT on a node.
  3842. *
  3843. * @tsl
  3844. * @function
  3845. * @param {Node} value - The value.
  3846. * @returns {OperatorNode}
  3847. */
  3848. const not = /*@__PURE__*/ nodeProxy( OperatorNode, '!' ).setParameterLength( 1 ).setName( 'not' );
  3849. /**
  3850. * Performs logical XOR on two nodes.
  3851. *
  3852. * @tsl
  3853. * @function
  3854. * @param {Node} a - The first input.
  3855. * @param {Node} b - The second input.
  3856. * @returns {OperatorNode}
  3857. */
  3858. const xor = /*@__PURE__*/ nodeProxy( OperatorNode, '^^' ).setParameterLength( 2 ).setName( 'xor' );
  3859. /**
  3860. * Performs bitwise AND on two nodes.
  3861. *
  3862. * @tsl
  3863. * @function
  3864. * @param {Node} a - The first input.
  3865. * @param {Node} b - The second input.
  3866. * @returns {OperatorNode}
  3867. */
  3868. const bitAnd = /*@__PURE__*/ nodeProxy( OperatorNode, '&' ).setParameterLength( 2 ).setName( 'bitAnd' );
  3869. /**
  3870. * Performs bitwise NOT on a node.
  3871. *
  3872. * @tsl
  3873. * @function
  3874. * @param {Node} a - The first input.
  3875. * @param {Node} b - The second input.
  3876. * @returns {OperatorNode}
  3877. */
  3878. const bitNot = /*@__PURE__*/ nodeProxy( OperatorNode, '~' ).setParameterLength( 2 ).setName( 'bitNot' );
  3879. /**
  3880. * Performs bitwise OR on two nodes.
  3881. *
  3882. * @tsl
  3883. * @function
  3884. * @param {Node} a - The first input.
  3885. * @param {Node} b - The second input.
  3886. * @returns {OperatorNode}
  3887. */
  3888. const bitOr = /*@__PURE__*/ nodeProxy( OperatorNode, '|' ).setParameterLength( 2 ).setName( 'bitOr' );
  3889. /**
  3890. * Performs bitwise XOR on two nodes.
  3891. *
  3892. * @tsl
  3893. * @function
  3894. * @param {Node} a - The first input.
  3895. * @param {Node} b - The second input.
  3896. * @returns {OperatorNode}
  3897. */
  3898. const bitXor = /*@__PURE__*/ nodeProxy( OperatorNode, '^' ).setParameterLength( 2 ).setName( 'bitXor' );
  3899. /**
  3900. * Shifts a node to the left.
  3901. *
  3902. * @tsl
  3903. * @function
  3904. * @param {Node} a - The node to shift.
  3905. * @param {Node} b - The value to shift.
  3906. * @returns {OperatorNode}
  3907. */
  3908. const shiftLeft = /*@__PURE__*/ nodeProxy( OperatorNode, '<<' ).setParameterLength( 2 ).setName( 'shiftLeft' );
  3909. /**
  3910. * Shifts a node to the right.
  3911. *
  3912. * @tsl
  3913. * @function
  3914. * @param {Node} a - The node to shift.
  3915. * @param {Node} b - The value to shift.
  3916. * @returns {OperatorNode}
  3917. */
  3918. const shiftRight = /*@__PURE__*/ nodeProxy( OperatorNode, '>>' ).setParameterLength( 2 ).setName( 'shiftRight' );
  3919. /**
  3920. * Increments a node by 1.
  3921. *
  3922. * @tsl
  3923. * @function
  3924. * @param {Node} a - The node to increment.
  3925. * @returns {OperatorNode}
  3926. */
  3927. const incrementBefore = Fn( ( [ a ] ) => {
  3928. a.addAssign( 1 );
  3929. return a;
  3930. } );
  3931. /**
  3932. * Decrements a node by 1.
  3933. *
  3934. * @tsl
  3935. * @function
  3936. * @param {Node} a - The node to decrement.
  3937. * @returns {OperatorNode}
  3938. */
  3939. const decrementBefore = Fn( ( [ a ] ) => {
  3940. a.subAssign( 1 );
  3941. return a;
  3942. } );
  3943. /**
  3944. * Increments a node by 1 and returns the previous value.
  3945. *
  3946. * @tsl
  3947. * @function
  3948. * @param {Node} a - The node to increment.
  3949. * @returns {OperatorNode}
  3950. */
  3951. const increment = /*@__PURE__*/ Fn( ( [ a ] ) => {
  3952. const temp = int( a ).toConst();
  3953. a.addAssign( 1 );
  3954. return temp;
  3955. } );
  3956. /**
  3957. * Decrements a node by 1 and returns the previous value.
  3958. *
  3959. * @tsl
  3960. * @function
  3961. * @param {Node} a - The node to decrement.
  3962. * @returns {OperatorNode}
  3963. */
  3964. const decrement = /*@__PURE__*/ Fn( ( [ a ] ) => {
  3965. const temp = int( a ).toConst();
  3966. a.subAssign( 1 );
  3967. return temp;
  3968. } );
  3969. addMethodChaining( 'add', add );
  3970. addMethodChaining( 'sub', sub );
  3971. addMethodChaining( 'mul', mul );
  3972. addMethodChaining( 'div', div );
  3973. addMethodChaining( 'mod', mod );
  3974. addMethodChaining( 'equal', equal );
  3975. addMethodChaining( 'notEqual', notEqual );
  3976. addMethodChaining( 'lessThan', lessThan );
  3977. addMethodChaining( 'greaterThan', greaterThan );
  3978. addMethodChaining( 'lessThanEqual', lessThanEqual );
  3979. addMethodChaining( 'greaterThanEqual', greaterThanEqual );
  3980. addMethodChaining( 'and', and );
  3981. addMethodChaining( 'or', or );
  3982. addMethodChaining( 'not', not );
  3983. addMethodChaining( 'xor', xor );
  3984. addMethodChaining( 'bitAnd', bitAnd );
  3985. addMethodChaining( 'bitNot', bitNot );
  3986. addMethodChaining( 'bitOr', bitOr );
  3987. addMethodChaining( 'bitXor', bitXor );
  3988. addMethodChaining( 'shiftLeft', shiftLeft );
  3989. addMethodChaining( 'shiftRight', shiftRight );
  3990. addMethodChaining( 'incrementBefore', incrementBefore );
  3991. addMethodChaining( 'decrementBefore', decrementBefore );
  3992. addMethodChaining( 'increment', increment );
  3993. addMethodChaining( 'decrement', decrement );
  3994. /**
  3995. * @tsl
  3996. * @function
  3997. * @deprecated since r175. Use {@link mod} instead.
  3998. *
  3999. * @param {Node} a - The first input.
  4000. * @param {Node} b - The second input.
  4001. * @returns {OperatorNode}
  4002. */
  4003. const modInt = ( a, b ) => { // @deprecated, r175
  4004. console.warn( 'THREE.TSL: "modInt()" is deprecated. Use "mod( int( ... ) )" instead.' );
  4005. return mod( int( a ), int( b ) );
  4006. };
  4007. addMethodChaining( 'modInt', modInt );
  4008. /**
  4009. * This node represents a variety of mathematical methods available in shaders.
  4010. * They are divided into three categories:
  4011. *
  4012. * - Methods with one input like `sin`, `cos` or `normalize`.
  4013. * - Methods with two inputs like `dot`, `cross` or `pow`.
  4014. * - Methods with three inputs like `mix`, `clamp` or `smoothstep`.
  4015. *
  4016. * @augments TempNode
  4017. */
  4018. class MathNode extends TempNode {
  4019. static get type() {
  4020. return 'MathNode';
  4021. }
  4022. /**
  4023. * Constructs a new math node.
  4024. *
  4025. * @param {string} method - The method name.
  4026. * @param {Node} aNode - The first input.
  4027. * @param {?Node} [bNode=null] - The second input.
  4028. * @param {?Node} [cNode=null] - The third input.
  4029. */
  4030. constructor( method, aNode, bNode = null, cNode = null ) {
  4031. super();
  4032. // Allow the max() and min() functions to take an arbitrary number of arguments.
  4033. if ( ( method === MathNode.MAX || method === MathNode.MIN ) && arguments.length > 3 ) {
  4034. let finalOp = new MathNode( method, aNode, bNode );
  4035. for ( let i = 2; i < arguments.length - 1; i ++ ) {
  4036. finalOp = new MathNode( method, finalOp, arguments[ i ] );
  4037. }
  4038. aNode = finalOp;
  4039. bNode = arguments[ arguments.length - 1 ];
  4040. cNode = null;
  4041. }
  4042. /**
  4043. * The method name.
  4044. *
  4045. * @type {string}
  4046. */
  4047. this.method = method;
  4048. /**
  4049. * The first input.
  4050. *
  4051. * @type {Node}
  4052. */
  4053. this.aNode = aNode;
  4054. /**
  4055. * The second input.
  4056. *
  4057. * @type {?Node}
  4058. * @default null
  4059. */
  4060. this.bNode = bNode;
  4061. /**
  4062. * The third input.
  4063. *
  4064. * @type {?Node}
  4065. * @default null
  4066. */
  4067. this.cNode = cNode;
  4068. /**
  4069. * This flag can be used for type testing.
  4070. *
  4071. * @type {boolean}
  4072. * @readonly
  4073. * @default true
  4074. */
  4075. this.isMathNode = true;
  4076. }
  4077. /**
  4078. * The input type is inferred from the node types of the input nodes.
  4079. *
  4080. * @param {NodeBuilder} builder - The current node builder.
  4081. * @return {string} The input type.
  4082. */
  4083. getInputType( builder ) {
  4084. const aType = this.aNode.getNodeType( builder );
  4085. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  4086. const cType = this.cNode ? this.cNode.getNodeType( builder ) : null;
  4087. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  4088. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  4089. const cLen = builder.isMatrix( cType ) ? 0 : builder.getTypeLength( cType );
  4090. if ( aLen > bLen && aLen > cLen ) {
  4091. return aType;
  4092. } else if ( bLen > cLen ) {
  4093. return bType;
  4094. } else if ( cLen > aLen ) {
  4095. return cType;
  4096. }
  4097. return aType;
  4098. }
  4099. /**
  4100. * The selected method as well as the input type determine the node type of this node.
  4101. *
  4102. * @param {NodeBuilder} builder - The current node builder.
  4103. * @return {string} The node type.
  4104. */
  4105. getNodeType( builder ) {
  4106. const method = this.method;
  4107. if ( method === MathNode.LENGTH || method === MathNode.DISTANCE || method === MathNode.DOT ) {
  4108. return 'float';
  4109. } else if ( method === MathNode.CROSS ) {
  4110. return 'vec3';
  4111. } else if ( method === MathNode.ALL || method === MathNode.ANY ) {
  4112. return 'bool';
  4113. } else if ( method === MathNode.EQUALS ) {
  4114. return builder.changeComponentType( this.aNode.getNodeType( builder ), 'bool' );
  4115. } else {
  4116. return this.getInputType( builder );
  4117. }
  4118. }
  4119. setup( builder ) {
  4120. const { aNode, bNode, method } = this;
  4121. let outputNode = null;
  4122. if ( method === MathNode.ONE_MINUS ) {
  4123. outputNode = sub( 1.0, aNode );
  4124. } else if ( method === MathNode.RECIPROCAL ) {
  4125. outputNode = div( 1.0, aNode );
  4126. } else if ( method === MathNode.DIFFERENCE ) {
  4127. outputNode = abs( sub( aNode, bNode ) );
  4128. } else if ( method === MathNode.TRANSFORM_DIRECTION ) {
  4129. // dir can be either a direction vector or a normal vector
  4130. // upper-left 3x3 of matrix is assumed to be orthogonal
  4131. let tA = aNode;
  4132. let tB = bNode;
  4133. if ( builder.isMatrix( tA.getNodeType( builder ) ) ) {
  4134. tB = vec4( vec3( tB ), 0.0 );
  4135. } else {
  4136. tA = vec4( vec3( tA ), 0.0 );
  4137. }
  4138. const mulNode = mul( tA, tB ).xyz;
  4139. outputNode = normalize( mulNode );
  4140. }
  4141. if ( outputNode !== null ) {
  4142. return outputNode;
  4143. } else {
  4144. return super.setup( builder );
  4145. }
  4146. }
  4147. generate( builder, output ) {
  4148. const properties = builder.getNodeProperties( this );
  4149. if ( properties.outputNode ) {
  4150. return super.generate( builder, output );
  4151. }
  4152. let method = this.method;
  4153. const type = this.getNodeType( builder );
  4154. const inputType = this.getInputType( builder );
  4155. const a = this.aNode;
  4156. const b = this.bNode;
  4157. const c = this.cNode;
  4158. const coordinateSystem = builder.renderer.coordinateSystem;
  4159. if ( method === MathNode.NEGATE ) {
  4160. return builder.format( '( - ' + a.build( builder, inputType ) + ' )', type, output );
  4161. } else {
  4162. const params = [];
  4163. if ( method === MathNode.CROSS ) {
  4164. params.push(
  4165. a.build( builder, type ),
  4166. b.build( builder, type )
  4167. );
  4168. } else if ( coordinateSystem === WebGLCoordinateSystem && method === MathNode.STEP ) {
  4169. params.push(
  4170. a.build( builder, builder.getTypeLength( a.getNodeType( builder ) ) === 1 ? 'float' : inputType ),
  4171. b.build( builder, inputType )
  4172. );
  4173. } else if ( coordinateSystem === WebGLCoordinateSystem && ( method === MathNode.MIN || method === MathNode.MAX ) ) {
  4174. params.push(
  4175. a.build( builder, inputType ),
  4176. b.build( builder, builder.getTypeLength( b.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  4177. );
  4178. } else if ( method === MathNode.REFRACT ) {
  4179. params.push(
  4180. a.build( builder, inputType ),
  4181. b.build( builder, inputType ),
  4182. c.build( builder, 'float' )
  4183. );
  4184. } else if ( method === MathNode.MIX ) {
  4185. params.push(
  4186. a.build( builder, inputType ),
  4187. b.build( builder, inputType ),
  4188. c.build( builder, builder.getTypeLength( c.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  4189. );
  4190. } else {
  4191. if ( coordinateSystem === WebGPUCoordinateSystem && method === MathNode.ATAN && b !== null ) {
  4192. method = 'atan2';
  4193. }
  4194. if ( builder.shaderStage !== 'fragment' && ( method === MathNode.DFDX || method === MathNode.DFDY ) ) {
  4195. console.warn( `THREE.TSL: '${ method }' is not supported in the ${ builder.shaderStage } stage.` );
  4196. method = '/*' + method + '*/';
  4197. }
  4198. params.push( a.build( builder, inputType ) );
  4199. if ( b !== null ) params.push( b.build( builder, inputType ) );
  4200. if ( c !== null ) params.push( c.build( builder, inputType ) );
  4201. }
  4202. return builder.format( `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`, type, output );
  4203. }
  4204. }
  4205. serialize( data ) {
  4206. super.serialize( data );
  4207. data.method = this.method;
  4208. }
  4209. deserialize( data ) {
  4210. super.deserialize( data );
  4211. this.method = data.method;
  4212. }
  4213. }
  4214. // 1 input
  4215. MathNode.ALL = 'all';
  4216. MathNode.ANY = 'any';
  4217. MathNode.RADIANS = 'radians';
  4218. MathNode.DEGREES = 'degrees';
  4219. MathNode.EXP = 'exp';
  4220. MathNode.EXP2 = 'exp2';
  4221. MathNode.LOG = 'log';
  4222. MathNode.LOG2 = 'log2';
  4223. MathNode.SQRT = 'sqrt';
  4224. MathNode.INVERSE_SQRT = 'inversesqrt';
  4225. MathNode.FLOOR = 'floor';
  4226. MathNode.CEIL = 'ceil';
  4227. MathNode.NORMALIZE = 'normalize';
  4228. MathNode.FRACT = 'fract';
  4229. MathNode.SIN = 'sin';
  4230. MathNode.COS = 'cos';
  4231. MathNode.TAN = 'tan';
  4232. MathNode.ASIN = 'asin';
  4233. MathNode.ACOS = 'acos';
  4234. MathNode.ATAN = 'atan';
  4235. MathNode.ABS = 'abs';
  4236. MathNode.SIGN = 'sign';
  4237. MathNode.LENGTH = 'length';
  4238. MathNode.NEGATE = 'negate';
  4239. MathNode.ONE_MINUS = 'oneMinus';
  4240. MathNode.DFDX = 'dFdx';
  4241. MathNode.DFDY = 'dFdy';
  4242. MathNode.ROUND = 'round';
  4243. MathNode.RECIPROCAL = 'reciprocal';
  4244. MathNode.TRUNC = 'trunc';
  4245. MathNode.FWIDTH = 'fwidth';
  4246. MathNode.TRANSPOSE = 'transpose';
  4247. // 2 inputs
  4248. MathNode.BITCAST = 'bitcast';
  4249. MathNode.EQUALS = 'equals';
  4250. MathNode.MIN = 'min';
  4251. MathNode.MAX = 'max';
  4252. MathNode.STEP = 'step';
  4253. MathNode.REFLECT = 'reflect';
  4254. MathNode.DISTANCE = 'distance';
  4255. MathNode.DIFFERENCE = 'difference';
  4256. MathNode.DOT = 'dot';
  4257. MathNode.CROSS = 'cross';
  4258. MathNode.POW = 'pow';
  4259. MathNode.TRANSFORM_DIRECTION = 'transformDirection';
  4260. // 3 inputs
  4261. MathNode.MIX = 'mix';
  4262. MathNode.CLAMP = 'clamp';
  4263. MathNode.REFRACT = 'refract';
  4264. MathNode.SMOOTHSTEP = 'smoothstep';
  4265. MathNode.FACEFORWARD = 'faceforward';
  4266. // 1 inputs
  4267. /**
  4268. * A small value used to handle floating-point precision errors.
  4269. *
  4270. * @tsl
  4271. * @type {Node<float>}
  4272. */
  4273. const EPSILON = /*@__PURE__*/ float( 1e-6 );
  4274. /**
  4275. * Represents infinity.
  4276. *
  4277. * @tsl
  4278. * @type {Node<float>}
  4279. */
  4280. const INFINITY = /*@__PURE__*/ float( 1e6 );
  4281. /**
  4282. * Represents PI.
  4283. *
  4284. * @tsl
  4285. * @type {Node<float>}
  4286. */
  4287. const PI = /*@__PURE__*/ float( Math.PI );
  4288. /**
  4289. * Represents PI * 2.
  4290. *
  4291. * @tsl
  4292. * @type {Node<float>}
  4293. */
  4294. const PI2 = /*@__PURE__*/ float( Math.PI * 2 );
  4295. /**
  4296. * Returns `true` if all components of `x` are `true`.
  4297. *
  4298. * @tsl
  4299. * @function
  4300. * @param {Node | number} x - The parameter.
  4301. * @returns {Node<bool>}
  4302. */
  4303. const all = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ALL ).setParameterLength( 1 );
  4304. /**
  4305. * Returns `true` if any components of `x` are `true`.
  4306. *
  4307. * @tsl
  4308. * @function
  4309. * @param {Node | number} x - The parameter.
  4310. * @returns {Node<bool>}
  4311. */
  4312. const any = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ANY ).setParameterLength( 1 );
  4313. /**
  4314. * Converts a quantity in degrees to radians.
  4315. *
  4316. * @tsl
  4317. * @function
  4318. * @param {Node | number} x - The input in degrees.
  4319. * @returns {Node}
  4320. */
  4321. const radians = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RADIANS ).setParameterLength( 1 );
  4322. /**
  4323. * Convert a quantity in radians to degrees.
  4324. *
  4325. * @tsl
  4326. * @function
  4327. * @param {Node | number} x - The input in radians.
  4328. * @returns {Node}
  4329. */
  4330. const degrees = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DEGREES ).setParameterLength( 1 );
  4331. /**
  4332. * Returns the natural exponentiation of the parameter.
  4333. *
  4334. * @tsl
  4335. * @function
  4336. * @param {Node | number} x - The parameter.
  4337. * @returns {Node}
  4338. */
  4339. const exp = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP ).setParameterLength( 1 );
  4340. /**
  4341. * Returns 2 raised to the power of the parameter.
  4342. *
  4343. * @tsl
  4344. * @function
  4345. * @param {Node | number} x - The parameter.
  4346. * @returns {Node}
  4347. */
  4348. const exp2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP2 ).setParameterLength( 1 );
  4349. /**
  4350. * Returns the natural logarithm of the parameter.
  4351. *
  4352. * @tsl
  4353. * @function
  4354. * @param {Node | number} x - The parameter.
  4355. * @returns {Node}
  4356. */
  4357. const log = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG ).setParameterLength( 1 );
  4358. /**
  4359. * Returns the base 2 logarithm of the parameter.
  4360. *
  4361. * @tsl
  4362. * @function
  4363. * @param {Node | number} x - The parameter.
  4364. * @returns {Node}
  4365. */
  4366. const log2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG2 ).setParameterLength( 1 );
  4367. /**
  4368. * Returns the square root of the parameter.
  4369. *
  4370. * @tsl
  4371. * @function
  4372. * @param {Node | number} x - The parameter.
  4373. * @returns {Node}
  4374. */
  4375. const sqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SQRT ).setParameterLength( 1 );
  4376. /**
  4377. * Returns the inverse of the square root of the parameter.
  4378. *
  4379. * @tsl
  4380. * @function
  4381. * @param {Node | number} x - The parameter.
  4382. * @returns {Node}
  4383. */
  4384. const inverseSqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.INVERSE_SQRT ).setParameterLength( 1 );
  4385. /**
  4386. * Finds the nearest integer less than or equal to the parameter.
  4387. *
  4388. * @tsl
  4389. * @function
  4390. * @param {Node | number} x - The parameter.
  4391. * @returns {Node}
  4392. */
  4393. const floor = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FLOOR ).setParameterLength( 1 );
  4394. /**
  4395. * Finds the nearest integer that is greater than or equal to the parameter.
  4396. *
  4397. * @tsl
  4398. * @function
  4399. * @param {Node | number} x - The parameter.
  4400. * @returns {Node}
  4401. */
  4402. const ceil = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CEIL ).setParameterLength( 1 );
  4403. /**
  4404. * Calculates the unit vector in the same direction as the original vector.
  4405. *
  4406. * @tsl
  4407. * @function
  4408. * @param {Node} x - The input vector.
  4409. * @returns {Node}
  4410. */
  4411. const normalize = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NORMALIZE ).setParameterLength( 1 );
  4412. /**
  4413. * Computes the fractional part of the parameter.
  4414. *
  4415. * @tsl
  4416. * @function
  4417. * @param {Node | number} x - The parameter.
  4418. * @returns {Node}
  4419. */
  4420. const fract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FRACT ).setParameterLength( 1 );
  4421. /**
  4422. * Returns the sine of the parameter.
  4423. *
  4424. * @tsl
  4425. * @function
  4426. * @param {Node | number} x - The parameter.
  4427. * @returns {Node}
  4428. */
  4429. const sin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIN ).setParameterLength( 1 );
  4430. /**
  4431. * Returns the cosine of the parameter.
  4432. *
  4433. * @tsl
  4434. * @function
  4435. * @param {Node | number} x - The parameter.
  4436. * @returns {Node}
  4437. */
  4438. const cos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.COS ).setParameterLength( 1 );
  4439. /**
  4440. * Returns the tangent of the parameter.
  4441. *
  4442. * @tsl
  4443. * @function
  4444. * @param {Node | number} x - The parameter.
  4445. * @returns {Node}
  4446. */
  4447. const tan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TAN ).setParameterLength( 1 );
  4448. /**
  4449. * Returns the arcsine of the parameter.
  4450. *
  4451. * @tsl
  4452. * @function
  4453. * @param {Node | number} x - The parameter.
  4454. * @returns {Node}
  4455. */
  4456. const asin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ASIN ).setParameterLength( 1 );
  4457. /**
  4458. * Returns the arccosine of the parameter.
  4459. *
  4460. * @tsl
  4461. * @function
  4462. * @param {Node | number} x - The parameter.
  4463. * @returns {Node}
  4464. */
  4465. const acos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ACOS ).setParameterLength( 1 );
  4466. /**
  4467. * Returns the arc-tangent of the parameter.
  4468. * If two parameters are provided, the result is `atan2(y/x)`.
  4469. *
  4470. * @tsl
  4471. * @function
  4472. * @param {Node | number} y - The y parameter.
  4473. * @param {?(Node | number)} x - The x parameter.
  4474. * @returns {Node}
  4475. */
  4476. const atan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ATAN ).setParameterLength( 1, 2 );
  4477. /**
  4478. * Returns the absolute value of the parameter.
  4479. *
  4480. * @tsl
  4481. * @function
  4482. * @param {Node | number} x - The parameter.
  4483. * @returns {Node}
  4484. */
  4485. const abs = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ABS ).setParameterLength( 1 );
  4486. /**
  4487. * Extracts the sign of the parameter.
  4488. *
  4489. * @tsl
  4490. * @function
  4491. * @param {Node | number} x - The parameter.
  4492. * @returns {Node}
  4493. */
  4494. const sign = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIGN ).setParameterLength( 1 );
  4495. /**
  4496. * Calculates the length of a vector.
  4497. *
  4498. * @tsl
  4499. * @function
  4500. * @param {Node} x - The parameter.
  4501. * @returns {Node<float>}
  4502. */
  4503. const length = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LENGTH ).setParameterLength( 1 );
  4504. /**
  4505. * Negates the value of the parameter (-x).
  4506. *
  4507. * @tsl
  4508. * @function
  4509. * @param {Node | number} x - The parameter.
  4510. * @returns {Node}
  4511. */
  4512. const negate = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NEGATE ).setParameterLength( 1 );
  4513. /**
  4514. * Return `1` minus the parameter.
  4515. *
  4516. * @tsl
  4517. * @function
  4518. * @param {Node | number} x - The parameter.
  4519. * @returns {Node}
  4520. */
  4521. const oneMinus = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ONE_MINUS ).setParameterLength( 1 );
  4522. /**
  4523. * Returns the partial derivative of the parameter with respect to x.
  4524. *
  4525. * @tsl
  4526. * @function
  4527. * @param {Node | number} x - The parameter.
  4528. * @returns {Node}
  4529. */
  4530. const dFdx = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDX ).setParameterLength( 1 );
  4531. /**
  4532. * Returns the partial derivative of the parameter with respect to y.
  4533. *
  4534. * @tsl
  4535. * @function
  4536. * @param {Node | number} x - The parameter.
  4537. * @returns {Node}
  4538. */
  4539. const dFdy = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDY ).setParameterLength( 1 );
  4540. /**
  4541. * Rounds the parameter to the nearest integer.
  4542. *
  4543. * @tsl
  4544. * @function
  4545. * @param {Node | number} x - The parameter.
  4546. * @returns {Node}
  4547. */
  4548. const round = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ROUND ).setParameterLength( 1 );
  4549. /**
  4550. * Returns the reciprocal of the parameter `(1/x)`.
  4551. *
  4552. * @tsl
  4553. * @function
  4554. * @param {Node | number} x - The parameter.
  4555. * @returns {Node}
  4556. */
  4557. const reciprocal = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RECIPROCAL ).setParameterLength( 1 );
  4558. /**
  4559. * Truncates the parameter, removing the fractional part.
  4560. *
  4561. * @tsl
  4562. * @function
  4563. * @param {Node | number} x - The parameter.
  4564. * @returns {Node}
  4565. */
  4566. const trunc = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRUNC ).setParameterLength( 1 );
  4567. /**
  4568. * Returns the sum of the absolute derivatives in x and y.
  4569. *
  4570. * @tsl
  4571. * @function
  4572. * @param {Node | number} x - The parameter.
  4573. * @returns {Node}
  4574. */
  4575. const fwidth = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FWIDTH ).setParameterLength( 1 );
  4576. /**
  4577. * Returns the transpose of a matrix.
  4578. *
  4579. * @tsl
  4580. * @function
  4581. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  4582. * @returns {Node}
  4583. */
  4584. const transpose = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSPOSE ).setParameterLength( 1 );
  4585. // 2 inputs
  4586. /**
  4587. * Reinterpret the bit representation of a value in one type as a value in another type.
  4588. *
  4589. * @tsl
  4590. * @function
  4591. * @param {Node | number} x - The parameter.
  4592. * @param {string} y - The new type.
  4593. * @returns {Node}
  4594. */
  4595. const bitcast = /*@__PURE__*/ nodeProxy( MathNode, MathNode.BITCAST ).setParameterLength( 2 );
  4596. /**
  4597. * Returns `true` if `x` equals `y`.
  4598. *
  4599. * @tsl
  4600. * @function
  4601. * @param {Node | number} x - The first parameter.
  4602. * @param {Node | number} y - The second parameter.
  4603. * @deprecated since r175. Use {@link equal} instead.
  4604. * @returns {Node<bool>}
  4605. */
  4606. const equals = ( x, y ) => { // @deprecated, r172
  4607. console.warn( 'THREE.TSL: "equals" is deprecated. Use "equal" inside a vector instead, like: "bvec*( equal( ... ) )"' );
  4608. return equal( x, y );
  4609. };
  4610. /**
  4611. * Returns the least of the given values.
  4612. *
  4613. * @tsl
  4614. * @function
  4615. * @param {...(Node | number)} values - The values to compare.
  4616. * @returns {Node}
  4617. */
  4618. const min$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIN ).setParameterLength( 2, Infinity );
  4619. /**
  4620. * Returns the greatest of the given values.
  4621. *
  4622. * @tsl
  4623. * @function
  4624. * @param {...(Node | number)} values - The values to compare.
  4625. * @returns {Node}
  4626. */
  4627. const max$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MAX ).setParameterLength( 2, Infinity );
  4628. /**
  4629. * Generate a step function by comparing two values.
  4630. *
  4631. * @tsl
  4632. * @function
  4633. * @param {Node | number} x - The y parameter.
  4634. * @param {Node | number} y - The x parameter.
  4635. * @returns {Node}
  4636. */
  4637. const step = /*@__PURE__*/ nodeProxy( MathNode, MathNode.STEP ).setParameterLength( 2 );
  4638. /**
  4639. * Calculates the reflection direction for an incident vector.
  4640. *
  4641. * @tsl
  4642. * @function
  4643. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  4644. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  4645. * @returns {Node<vec2|vec3|vec4>}
  4646. */
  4647. const reflect = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFLECT ).setParameterLength( 2 );
  4648. /**
  4649. * Calculates the distance between two points.
  4650. *
  4651. * @tsl
  4652. * @function
  4653. * @param {Node<vec2|vec3|vec4>} x - The first point.
  4654. * @param {Node<vec2|vec3|vec4>} y - The second point.
  4655. * @returns {Node<float>}
  4656. */
  4657. const distance = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DISTANCE ).setParameterLength( 2 );
  4658. /**
  4659. * Calculates the absolute difference between two values.
  4660. *
  4661. * @tsl
  4662. * @function
  4663. * @param {Node | number} x - The first parameter.
  4664. * @param {Node | number} y - The second parameter.
  4665. * @returns {Node}
  4666. */
  4667. const difference = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DIFFERENCE ).setParameterLength( 2 );
  4668. /**
  4669. * Calculates the dot product of two vectors.
  4670. *
  4671. * @tsl
  4672. * @function
  4673. * @param {Node<vec2|vec3|vec4>} x - The first vector.
  4674. * @param {Node<vec2|vec3|vec4>} y - The second vector.
  4675. * @returns {Node<float>}
  4676. */
  4677. const dot = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DOT ).setParameterLength( 2 );
  4678. /**
  4679. * Calculates the cross product of two vectors.
  4680. *
  4681. * @tsl
  4682. * @function
  4683. * @param {Node<vec2|vec3|vec4>} x - The first vector.
  4684. * @param {Node<vec2|vec3|vec4>} y - The second vector.
  4685. * @returns {Node<vec2|vec3|vec4>}
  4686. */
  4687. const cross = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CROSS ).setParameterLength( 2 );
  4688. /**
  4689. * Return the value of the first parameter raised to the power of the second one.
  4690. *
  4691. * @tsl
  4692. * @function
  4693. * @param {Node | number} x - The first parameter.
  4694. * @param {Node | number} y - The second parameter.
  4695. * @returns {Node}
  4696. */
  4697. const pow = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW ).setParameterLength( 2 );
  4698. /**
  4699. * Returns the square of the parameter.
  4700. *
  4701. * @tsl
  4702. * @function
  4703. * @param {Node | number} x - The first parameter.
  4704. * @returns {Node}
  4705. */
  4706. const pow2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 2 ).setParameterLength( 1 );
  4707. /**
  4708. * Returns the cube of the parameter.
  4709. *
  4710. * @tsl
  4711. * @function
  4712. * @param {Node | number} x - The first parameter.
  4713. * @returns {Node}
  4714. */
  4715. const pow3 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 3 ).setParameterLength( 1 );
  4716. /**
  4717. * Returns the fourth power of the parameter.
  4718. *
  4719. * @tsl
  4720. * @function
  4721. * @param {Node | number} x - The first parameter.
  4722. * @returns {Node}
  4723. */
  4724. const pow4 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 4 ).setParameterLength( 1 );
  4725. /**
  4726. * Transforms the direction of a vector by a matrix and then normalizes the result.
  4727. *
  4728. * @tsl
  4729. * @function
  4730. * @param {Node<vec2|vec3|vec4>} direction - The direction vector.
  4731. * @param {Node<mat2|mat3|mat4>} matrix - The transformation matrix.
  4732. * @returns {Node}
  4733. */
  4734. const transformDirection = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSFORM_DIRECTION ).setParameterLength( 2 );
  4735. /**
  4736. * Returns the cube root of a number.
  4737. *
  4738. * @tsl
  4739. * @function
  4740. * @param {Node | number} a - The first parameter.
  4741. * @returns {Node}
  4742. */
  4743. const cbrt = ( a ) => mul( sign( a ), pow( abs( a ), 1.0 / 3.0 ) );
  4744. /**
  4745. * Calculate the squared length of a vector.
  4746. *
  4747. * @tsl
  4748. * @function
  4749. * @param {Node<vec2|vec3|vec4>} a - The vector.
  4750. * @returns {Node<float>}
  4751. */
  4752. const lengthSq = ( a ) => dot( a, a );
  4753. /**
  4754. * Linearly interpolates between two values.
  4755. *
  4756. * @tsl
  4757. * @function
  4758. * @param {Node | number} a - The first parameter.
  4759. * @param {Node | number} b - The second parameter.
  4760. * @param {Node | number} t - The interpolation value.
  4761. * @returns {Node}
  4762. */
  4763. const mix = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIX ).setParameterLength( 3 );
  4764. /**
  4765. * Constrains a value to lie between two further values.
  4766. *
  4767. * @tsl
  4768. * @function
  4769. * @param {Node | number} value - The value to constrain.
  4770. * @param {Node | number} [low=0] - The lower bound.
  4771. * @param {Node | number} [high=1] - The upper bound.
  4772. * @returns {Node}
  4773. */
  4774. const clamp = ( value, low = 0, high = 1 ) => nodeObject( new MathNode( MathNode.CLAMP, nodeObject( value ), nodeObject( low ), nodeObject( high ) ) );
  4775. /**
  4776. * Constrains a value between `0` and `1`.
  4777. *
  4778. * @tsl
  4779. * @function
  4780. * @param {Node | number} value - The value to constrain.
  4781. * @returns {Node}
  4782. */
  4783. const saturate = ( value ) => clamp( value );
  4784. /**
  4785. * Calculates the refraction direction for an incident vector.
  4786. *
  4787. * @tsl
  4788. * @function
  4789. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  4790. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  4791. * @param {Node<float>} eta - The ratio of indices of refraction.
  4792. * @returns {Node<vec2|vec3|vec4>}
  4793. */
  4794. const refract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFRACT ).setParameterLength( 3 );
  4795. /**
  4796. * Performs a Hermite interpolation between two values.
  4797. *
  4798. * @tsl
  4799. * @function
  4800. * @param {Node | number} low - The value of the lower edge of the Hermite function.
  4801. * @param {Node | number} high - The value of the upper edge of the Hermite function.
  4802. * @param {Node | number} x - The source value for interpolation.
  4803. * @returns {Node}
  4804. */
  4805. const smoothstep = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SMOOTHSTEP ).setParameterLength( 3 );
  4806. /**
  4807. * Returns a vector pointing in the same direction as another.
  4808. *
  4809. * @tsl
  4810. * @function
  4811. * @param {Node<vec2|vec3|vec4>} N - The vector to orient.
  4812. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  4813. * @param {Node<vec2|vec3|vec4>} Nref - The reference vector.
  4814. * @returns {Node<vec2|vec3|vec4>}
  4815. */
  4816. const faceForward = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FACEFORWARD ).setParameterLength( 3 );
  4817. /**
  4818. * Returns a random value for the given uv.
  4819. *
  4820. * @tsl
  4821. * @function
  4822. * @param {Node<vec2>} uv - The uv node.
  4823. * @returns {Node<float>}
  4824. */
  4825. const rand = /*@__PURE__*/ Fn( ( [ uv ] ) => {
  4826. const a = 12.9898, b = 78.233, c = 43758.5453;
  4827. const dt = dot( uv.xy, vec2( a, b ) ), sn = mod( dt, PI );
  4828. return fract( sin( sn ).mul( c ) );
  4829. } );
  4830. /**
  4831. * Alias for `mix()` with a different parameter order.
  4832. *
  4833. * @tsl
  4834. * @function
  4835. * @param {Node | number} t - The interpolation value.
  4836. * @param {Node | number} e1 - The first parameter.
  4837. * @param {Node | number} e2 - The second parameter.
  4838. * @returns {Node}
  4839. */
  4840. const mixElement = ( t, e1, e2 ) => mix( e1, e2, t );
  4841. /**
  4842. * Alias for `smoothstep()` with a different parameter order.
  4843. *
  4844. * @tsl
  4845. * @function
  4846. * @param {Node | number} x - The source value for interpolation.
  4847. * @param {Node | number} low - The value of the lower edge of the Hermite function.
  4848. * @param {Node | number} high - The value of the upper edge of the Hermite function.
  4849. * @returns {Node}
  4850. */
  4851. const smoothstepElement = ( x, low, high ) => smoothstep( low, high, x );
  4852. /**
  4853. * Alias for `step()` with a different parameter order.
  4854. *
  4855. * @tsl
  4856. * @function
  4857. * @param {Node | number} x - The source value for interpolation.
  4858. * @param {Node | number} edge - The edge value.
  4859. * @returns {Node}
  4860. */
  4861. const stepElement = ( x, edge ) => step( edge, x );
  4862. /**
  4863. * Returns the arc-tangent of the quotient of its parameters.
  4864. *
  4865. * @tsl
  4866. * @function
  4867. * @deprecated since r172. Use {@link atan} instead.
  4868. *
  4869. * @param {Node | number} y - The y parameter.
  4870. * @param {Node | number} x - The x parameter.
  4871. * @returns {Node}
  4872. */
  4873. const atan2 = ( y, x ) => { // @deprecated, r172
  4874. console.warn( 'THREE.TSL: "atan2" is overloaded. Use "atan" instead.' );
  4875. return atan( y, x );
  4876. };
  4877. // GLSL alias function
  4878. const faceforward = faceForward;
  4879. const inversesqrt = inverseSqrt;
  4880. // Method chaining
  4881. addMethodChaining( 'all', all );
  4882. addMethodChaining( 'any', any );
  4883. addMethodChaining( 'equals', equals );
  4884. addMethodChaining( 'radians', radians );
  4885. addMethodChaining( 'degrees', degrees );
  4886. addMethodChaining( 'exp', exp );
  4887. addMethodChaining( 'exp2', exp2 );
  4888. addMethodChaining( 'log', log );
  4889. addMethodChaining( 'log2', log2 );
  4890. addMethodChaining( 'sqrt', sqrt );
  4891. addMethodChaining( 'inverseSqrt', inverseSqrt );
  4892. addMethodChaining( 'floor', floor );
  4893. addMethodChaining( 'ceil', ceil );
  4894. addMethodChaining( 'normalize', normalize );
  4895. addMethodChaining( 'fract', fract );
  4896. addMethodChaining( 'sin', sin );
  4897. addMethodChaining( 'cos', cos );
  4898. addMethodChaining( 'tan', tan );
  4899. addMethodChaining( 'asin', asin );
  4900. addMethodChaining( 'acos', acos );
  4901. addMethodChaining( 'atan', atan );
  4902. addMethodChaining( 'abs', abs );
  4903. addMethodChaining( 'sign', sign );
  4904. addMethodChaining( 'length', length );
  4905. addMethodChaining( 'lengthSq', lengthSq );
  4906. addMethodChaining( 'negate', negate );
  4907. addMethodChaining( 'oneMinus', oneMinus );
  4908. addMethodChaining( 'dFdx', dFdx );
  4909. addMethodChaining( 'dFdy', dFdy );
  4910. addMethodChaining( 'round', round );
  4911. addMethodChaining( 'reciprocal', reciprocal );
  4912. addMethodChaining( 'trunc', trunc );
  4913. addMethodChaining( 'fwidth', fwidth );
  4914. addMethodChaining( 'atan2', atan2 );
  4915. addMethodChaining( 'min', min$1 );
  4916. addMethodChaining( 'max', max$1 );
  4917. addMethodChaining( 'step', stepElement );
  4918. addMethodChaining( 'reflect', reflect );
  4919. addMethodChaining( 'distance', distance );
  4920. addMethodChaining( 'dot', dot );
  4921. addMethodChaining( 'cross', cross );
  4922. addMethodChaining( 'pow', pow );
  4923. addMethodChaining( 'pow2', pow2 );
  4924. addMethodChaining( 'pow3', pow3 );
  4925. addMethodChaining( 'pow4', pow4 );
  4926. addMethodChaining( 'transformDirection', transformDirection );
  4927. addMethodChaining( 'mix', mixElement );
  4928. addMethodChaining( 'clamp', clamp );
  4929. addMethodChaining( 'refract', refract );
  4930. addMethodChaining( 'smoothstep', smoothstepElement );
  4931. addMethodChaining( 'faceForward', faceForward );
  4932. addMethodChaining( 'difference', difference );
  4933. addMethodChaining( 'saturate', saturate );
  4934. addMethodChaining( 'cbrt', cbrt );
  4935. addMethodChaining( 'transpose', transpose );
  4936. addMethodChaining( 'rand', rand );
  4937. /**
  4938. * Represents a logical `if/else` statement. Can be used as an alternative
  4939. * to the `If()`/`Else()` syntax.
  4940. *
  4941. * The corresponding TSL `select()` looks like so:
  4942. * ```js
  4943. * velocity = position.greaterThanEqual( limit ).select( velocity.negate(), velocity );
  4944. * ```
  4945. * The `select()` method is called in a chaining fashion on a condition. The parameter nodes of `select()`
  4946. * determine the outcome of the entire statement.
  4947. *
  4948. * @augments Node
  4949. */
  4950. class ConditionalNode extends Node {
  4951. static get type() {
  4952. return 'ConditionalNode';
  4953. }
  4954. /**
  4955. * Constructs a new conditional node.
  4956. *
  4957. * @param {Node} condNode - The node that defines the condition.
  4958. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  4959. * @param {?Node} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  4960. */
  4961. constructor( condNode, ifNode, elseNode = null ) {
  4962. super();
  4963. /**
  4964. * The node that defines the condition.
  4965. *
  4966. * @type {Node}
  4967. */
  4968. this.condNode = condNode;
  4969. /**
  4970. * The node that is evaluate when the condition ends up `true`.
  4971. *
  4972. * @type {Node}
  4973. */
  4974. this.ifNode = ifNode;
  4975. /**
  4976. * The node that is evaluate when the condition ends up `false`.
  4977. *
  4978. * @type {?Node}
  4979. * @default null
  4980. */
  4981. this.elseNode = elseNode;
  4982. }
  4983. /**
  4984. * This method is overwritten since the node type is inferred from the if/else
  4985. * nodes.
  4986. *
  4987. * @param {NodeBuilder} builder - The current node builder.
  4988. * @return {string} The node type.
  4989. */
  4990. getNodeType( builder ) {
  4991. const { ifNode, elseNode } = builder.getNodeProperties( this );
  4992. if ( ifNode === undefined ) {
  4993. // fallback setup
  4994. this.setup( builder );
  4995. return this.getNodeType( builder );
  4996. }
  4997. const ifType = ifNode.getNodeType( builder );
  4998. if ( elseNode !== null ) {
  4999. const elseType = elseNode.getNodeType( builder );
  5000. if ( builder.getTypeLength( elseType ) > builder.getTypeLength( ifType ) ) {
  5001. return elseType;
  5002. }
  5003. }
  5004. return ifType;
  5005. }
  5006. setup( builder ) {
  5007. const condNode = this.condNode.cache();
  5008. const ifNode = this.ifNode.cache();
  5009. const elseNode = this.elseNode ? this.elseNode.cache() : null;
  5010. //
  5011. const currentNodeBlock = builder.context.nodeBlock;
  5012. builder.getDataFromNode( ifNode ).parentNodeBlock = currentNodeBlock;
  5013. if ( elseNode !== null ) builder.getDataFromNode( elseNode ).parentNodeBlock = currentNodeBlock;
  5014. //
  5015. const properties = builder.getNodeProperties( this );
  5016. properties.condNode = condNode;
  5017. properties.ifNode = ifNode.context( { nodeBlock: ifNode } );
  5018. properties.elseNode = elseNode ? elseNode.context( { nodeBlock: elseNode } ) : null;
  5019. }
  5020. generate( builder, output ) {
  5021. const type = this.getNodeType( builder );
  5022. const nodeData = builder.getDataFromNode( this );
  5023. if ( nodeData.nodeProperty !== undefined ) {
  5024. return nodeData.nodeProperty;
  5025. }
  5026. const { condNode, ifNode, elseNode } = builder.getNodeProperties( this );
  5027. const functionNode = builder.currentFunctionNode;
  5028. const needsOutput = output !== 'void';
  5029. const nodeProperty = needsOutput ? property( type ).build( builder ) : '';
  5030. nodeData.nodeProperty = nodeProperty;
  5031. const nodeSnippet = condNode.build( builder, 'bool' );
  5032. builder.addFlowCode( `\n${ builder.tab }if ( ${ nodeSnippet } ) {\n\n` ).addFlowTab();
  5033. let ifSnippet = ifNode.build( builder, type );
  5034. if ( ifSnippet ) {
  5035. if ( needsOutput ) {
  5036. ifSnippet = nodeProperty + ' = ' + ifSnippet + ';';
  5037. } else {
  5038. ifSnippet = 'return ' + ifSnippet + ';';
  5039. if ( functionNode === null ) {
  5040. console.warn( 'THREE.TSL: Return statement used in an inline \'Fn()\'. Define a layout struct to allow return values.' );
  5041. ifSnippet = '// ' + ifSnippet;
  5042. }
  5043. }
  5044. }
  5045. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + ifSnippet + '\n\n' + builder.tab + '}' );
  5046. if ( elseNode !== null ) {
  5047. builder.addFlowCode( ' else {\n\n' ).addFlowTab();
  5048. let elseSnippet = elseNode.build( builder, type );
  5049. if ( elseSnippet ) {
  5050. if ( needsOutput ) {
  5051. elseSnippet = nodeProperty + ' = ' + elseSnippet + ';';
  5052. } else {
  5053. elseSnippet = 'return ' + elseSnippet + ';';
  5054. if ( functionNode === null ) {
  5055. console.warn( 'THREE.TSL: Return statement used in an inline \'Fn()\'. Define a layout struct to allow return values.' );
  5056. elseSnippet = '// ' + elseSnippet;
  5057. }
  5058. }
  5059. }
  5060. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + elseSnippet + '\n\n' + builder.tab + '}\n\n' );
  5061. } else {
  5062. builder.addFlowCode( '\n\n' );
  5063. }
  5064. return builder.format( nodeProperty, type, output );
  5065. }
  5066. }
  5067. /**
  5068. * TSL function for creating a conditional node.
  5069. *
  5070. * @tsl
  5071. * @function
  5072. * @param {Node} condNode - The node that defines the condition.
  5073. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  5074. * @param {?Node} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  5075. * @returns {ConditionalNode}
  5076. */
  5077. const select = /*@__PURE__*/ nodeProxy( ConditionalNode ).setParameterLength( 2, 3 );
  5078. addMethodChaining( 'select', select );
  5079. /**
  5080. * This node can be used as a context management component for another node.
  5081. * {@link NodeBuilder} performs its node building process in a specific context and
  5082. * this node allows the modify the context. A typical use case is to overwrite `getUV()` e.g.:
  5083. *
  5084. * ```js
  5085. *node.context( { getUV: () => customCoord } );
  5086. *```
  5087. * @augments Node
  5088. */
  5089. class ContextNode extends Node {
  5090. static get type() {
  5091. return 'ContextNode';
  5092. }
  5093. /**
  5094. * Constructs a new context node.
  5095. *
  5096. * @param {Node} node - The node whose context should be modified.
  5097. * @param {Object} [value={}] - The modified context data.
  5098. */
  5099. constructor( node, value = {} ) {
  5100. super();
  5101. /**
  5102. * This flag can be used for type testing.
  5103. *
  5104. * @type {boolean}
  5105. * @readonly
  5106. * @default true
  5107. */
  5108. this.isContextNode = true;
  5109. /**
  5110. * The node whose context should be modified.
  5111. *
  5112. * @type {Node}
  5113. */
  5114. this.node = node;
  5115. /**
  5116. * The modified context data.
  5117. *
  5118. * @type {Object}
  5119. * @default {}
  5120. */
  5121. this.value = value;
  5122. }
  5123. /**
  5124. * This method is overwritten to ensure it returns the reference to {@link ContextNode#node}.
  5125. *
  5126. * @return {Node} A reference to {@link ContextNode#node}.
  5127. */
  5128. getScope() {
  5129. return this.node.getScope();
  5130. }
  5131. /**
  5132. * This method is overwritten to ensure it returns the type of {@link ContextNode#node}.
  5133. *
  5134. * @param {NodeBuilder} builder - The current node builder.
  5135. * @return {string} The node type.
  5136. */
  5137. getNodeType( builder ) {
  5138. return this.node.getNodeType( builder );
  5139. }
  5140. analyze( builder ) {
  5141. const previousContext = builder.getContext();
  5142. builder.setContext( { ...builder.context, ...this.value } );
  5143. this.node.build( builder );
  5144. builder.setContext( previousContext );
  5145. }
  5146. setup( builder ) {
  5147. const previousContext = builder.getContext();
  5148. builder.setContext( { ...builder.context, ...this.value } );
  5149. this.node.build( builder );
  5150. builder.setContext( previousContext );
  5151. }
  5152. generate( builder, output ) {
  5153. const previousContext = builder.getContext();
  5154. builder.setContext( { ...builder.context, ...this.value } );
  5155. const snippet = this.node.build( builder, output );
  5156. builder.setContext( previousContext );
  5157. return snippet;
  5158. }
  5159. }
  5160. /**
  5161. * TSL function for creating a context node.
  5162. *
  5163. * @tsl
  5164. * @function
  5165. * @param {Node} node - The node whose context should be modified.
  5166. * @param {Object} [value={}] - The modified context data.
  5167. * @returns {ContextNode}
  5168. */
  5169. const context = /*@__PURE__*/ nodeProxy( ContextNode ).setParameterLength( 1, 2 );
  5170. /**
  5171. * TSL function for defining a label context value for a given node.
  5172. *
  5173. * @tsl
  5174. * @function
  5175. * @param {Node} node - The node whose context should be modified.
  5176. * @param {string} name - The name/label to set.
  5177. * @returns {ContextNode}
  5178. */
  5179. const label = ( node, name ) => context( node, { label: name } );
  5180. addMethodChaining( 'context', context );
  5181. addMethodChaining( 'label', label );
  5182. /**
  5183. * Class for representing shader variables as nodes. Variables are created from
  5184. * existing nodes like the following:
  5185. *
  5186. * ```js
  5187. * const depth = sampleDepth( uvNode ).toVar( 'depth' );
  5188. * ```
  5189. *
  5190. * @augments Node
  5191. */
  5192. class VarNode extends Node {
  5193. static get type() {
  5194. return 'VarNode';
  5195. }
  5196. /**
  5197. * Constructs a new variable node.
  5198. *
  5199. * @param {Node} node - The node for which a variable should be created.
  5200. * @param {?string} [name=null] - The name of the variable in the shader.
  5201. * @param {boolean} [readOnly=false] - The read-only flag.
  5202. */
  5203. constructor( node, name = null, readOnly = false ) {
  5204. super();
  5205. /**
  5206. * The node for which a variable should be created.
  5207. *
  5208. * @type {Node}
  5209. */
  5210. this.node = node;
  5211. /**
  5212. * The name of the variable in the shader. If no name is defined,
  5213. * the node system auto-generates one.
  5214. *
  5215. * @type {?string}
  5216. * @default null
  5217. */
  5218. this.name = name;
  5219. /**
  5220. * `VarNode` sets this property to `true` by default.
  5221. *
  5222. * @type {boolean}
  5223. * @default true
  5224. */
  5225. this.global = true;
  5226. /**
  5227. * This flag can be used for type testing.
  5228. *
  5229. * @type {boolean}
  5230. * @readonly
  5231. * @default true
  5232. */
  5233. this.isVarNode = true;
  5234. /**
  5235. *
  5236. * The read-only flag.
  5237. *
  5238. * @type {boolean}
  5239. * @default false
  5240. */
  5241. this.readOnly = readOnly;
  5242. /**
  5243. *
  5244. * Add this flag to the node system to indicate that this node require parents.
  5245. *
  5246. * @type {boolean}
  5247. * @default true
  5248. */
  5249. this.parents = true;
  5250. }
  5251. getMemberType( builder, name ) {
  5252. return this.node.getMemberType( builder, name );
  5253. }
  5254. getElementType( builder ) {
  5255. return this.node.getElementType( builder );
  5256. }
  5257. getNodeType( builder ) {
  5258. return this.node.getNodeType( builder );
  5259. }
  5260. generate( builder ) {
  5261. const { node, name, readOnly } = this;
  5262. const { renderer } = builder;
  5263. const isWebGPUBackend = renderer.backend.isWebGPUBackend === true;
  5264. let isDeterministic = false;
  5265. let shouldTreatAsReadOnly = false;
  5266. if ( readOnly ) {
  5267. isDeterministic = builder.isDeterministic( node );
  5268. shouldTreatAsReadOnly = isWebGPUBackend ? readOnly : isDeterministic;
  5269. }
  5270. const vectorType = builder.getVectorType( this.getNodeType( builder ) );
  5271. const snippet = node.build( builder, vectorType );
  5272. const nodeVar = builder.getVarFromNode( this, name, vectorType, undefined, shouldTreatAsReadOnly );
  5273. const propertyName = builder.getPropertyName( nodeVar );
  5274. let declarationPrefix = propertyName;
  5275. if ( shouldTreatAsReadOnly ) {
  5276. if ( isWebGPUBackend ) {
  5277. declarationPrefix = isDeterministic
  5278. ? `const ${ propertyName }`
  5279. : `let ${ propertyName }`;
  5280. } else {
  5281. const count = builder.getArrayCount( node );
  5282. declarationPrefix = `const ${ builder.getVar( nodeVar.type, propertyName, count ) }`;
  5283. }
  5284. }
  5285. builder.addLineFlowCode( `${ declarationPrefix } = ${ snippet }`, this );
  5286. return propertyName;
  5287. }
  5288. }
  5289. /**
  5290. * TSL function for creating a var node.
  5291. *
  5292. * @tsl
  5293. * @function
  5294. * @param {Node} node - The node for which a variable should be created.
  5295. * @param {?string} name - The name of the variable in the shader.
  5296. * @returns {VarNode}
  5297. */
  5298. const createVar = /*@__PURE__*/ nodeProxy( VarNode );
  5299. /**
  5300. * TSL function for creating a var node.
  5301. *
  5302. * @tsl
  5303. * @function
  5304. * @param {Node} node - The node for which a variable should be created.
  5305. * @param {?string} name - The name of the variable in the shader.
  5306. * @returns {VarNode}
  5307. */
  5308. const Var = ( node, name = null ) => createVar( node, name ).toStack();
  5309. /**
  5310. * TSL function for creating a const node.
  5311. *
  5312. * @tsl
  5313. * @function
  5314. * @param {Node} node - The node for which a constant should be created.
  5315. * @param {?string} name - The name of the constant in the shader.
  5316. * @returns {VarNode}
  5317. */
  5318. const Const = ( node, name = null ) => createVar( node, name, true ).toStack();
  5319. // Method chaining
  5320. addMethodChaining( 'toVar', Var );
  5321. addMethodChaining( 'toConst', Const );
  5322. // Deprecated
  5323. /**
  5324. * @tsl
  5325. * @function
  5326. * @deprecated since r170. Use `Var( node )` or `node.toVar()` instead.
  5327. *
  5328. * @param {any} node
  5329. * @returns {VarNode}
  5330. */
  5331. const temp = ( node ) => { // @deprecated, r170
  5332. console.warn( 'TSL: "temp( node )" is deprecated. Use "Var( node )" or "node.toVar()" instead.' );
  5333. return createVar( node );
  5334. };
  5335. addMethodChaining( 'temp', temp );
  5336. /**
  5337. * This node is used to build a sub-build in the node system.
  5338. *
  5339. * @augments Node
  5340. * @param {Node} node - The node to be built in the sub-build.
  5341. * @param {string} name - The name of the sub-build.
  5342. * @param {string|null} [nodeType=null] - The type of the node, if known.
  5343. */
  5344. class SubBuildNode extends Node {
  5345. static get type() {
  5346. return 'SubBuild';
  5347. }
  5348. constructor( node, name, nodeType = null ) {
  5349. super( nodeType );
  5350. /**
  5351. * The node to be built in the sub-build.
  5352. *
  5353. * @type {Node}
  5354. */
  5355. this.node = node;
  5356. /**
  5357. * The name of the sub-build.
  5358. *
  5359. * @type {string}
  5360. */
  5361. this.name = name;
  5362. /**
  5363. * This flag can be used for type testing.
  5364. *
  5365. * @type {boolean}
  5366. * @readonly
  5367. * @default true
  5368. */
  5369. this.isSubBuildNode = true;
  5370. }
  5371. getNodeType( builder ) {
  5372. if ( this.nodeType !== null ) return this.nodeType;
  5373. builder.addSubBuild( this.name );
  5374. const nodeType = this.node.getNodeType( builder );
  5375. builder.removeSubBuild();
  5376. return nodeType;
  5377. }
  5378. build( builder, ...params ) {
  5379. builder.addSubBuild( this.name );
  5380. const data = this.node.build( builder, ...params );
  5381. builder.removeSubBuild();
  5382. return data;
  5383. }
  5384. }
  5385. /**
  5386. * Creates a new sub-build node.
  5387. *
  5388. * @tsl
  5389. * @function
  5390. * @param {Node} node - The node to be built in the sub-build.
  5391. * @param {string} name - The name of the sub-build.
  5392. * @param {string|null} [type=null] - The type of the node, if known.
  5393. * @returns {Node} A node object wrapping the SubBuildNode instance.
  5394. */
  5395. const subBuild = ( node, name, type = null ) => nodeObject( new SubBuildNode( nodeObject( node ), name, type ) );
  5396. /**
  5397. * Class for representing shader varyings as nodes. Varyings are create from
  5398. * existing nodes like the following:
  5399. *
  5400. * ```js
  5401. * const positionLocal = positionGeometry.toVarying( 'vPositionLocal' );
  5402. * ```
  5403. *
  5404. * @augments Node
  5405. */
  5406. class VaryingNode extends Node {
  5407. static get type() {
  5408. return 'VaryingNode';
  5409. }
  5410. /**
  5411. * Constructs a new varying node.
  5412. *
  5413. * @param {Node} node - The node for which a varying should be created.
  5414. * @param {?string} name - The name of the varying in the shader.
  5415. */
  5416. constructor( node, name = null ) {
  5417. super();
  5418. /**
  5419. * The node for which a varying should be created.
  5420. *
  5421. * @type {Node}
  5422. */
  5423. this.node = node;
  5424. /**
  5425. * The name of the varying in the shader. If no name is defined,
  5426. * the node system auto-generates one.
  5427. *
  5428. * @type {?string}
  5429. * @default null
  5430. */
  5431. this.name = name;
  5432. /**
  5433. * This flag can be used for type testing.
  5434. *
  5435. * @type {boolean}
  5436. * @readonly
  5437. * @default true
  5438. */
  5439. this.isVaryingNode = true;
  5440. /**
  5441. * The interpolation type of the varying data.
  5442. *
  5443. * @type {?string}
  5444. * @default null
  5445. */
  5446. this.interpolationType = null;
  5447. /**
  5448. * The interpolation sampling type of varying data.
  5449. *
  5450. * @type {?string}
  5451. * @default null
  5452. */
  5453. this.interpolationSampling = null;
  5454. /**
  5455. * This flag is used for global cache.
  5456. *
  5457. * @type {boolean}
  5458. * @default true
  5459. */
  5460. this.global = true;
  5461. }
  5462. /**
  5463. * Defines the interpolation type of the varying.
  5464. *
  5465. * @param {string} type - The interpolation type.
  5466. * @param {?string} sampling - The interpolation sampling type
  5467. * @return {VaryingNode} A reference to this node.
  5468. */
  5469. setInterpolation( type, sampling = null ) {
  5470. this.interpolationType = type;
  5471. this.interpolationSampling = sampling;
  5472. return this;
  5473. }
  5474. getHash( builder ) {
  5475. return this.name || super.getHash( builder );
  5476. }
  5477. getNodeType( builder ) {
  5478. // VaryingNode is auto type
  5479. return this.node.getNodeType( builder );
  5480. }
  5481. /**
  5482. * This method performs the setup of a varying node with the current node builder.
  5483. *
  5484. * @param {NodeBuilder} builder - The current node builder.
  5485. * @return {NodeVarying} The node varying from the node builder.
  5486. */
  5487. setupVarying( builder ) {
  5488. const properties = builder.getNodeProperties( this );
  5489. let varying = properties.varying;
  5490. if ( varying === undefined ) {
  5491. const name = this.name;
  5492. const type = this.getNodeType( builder );
  5493. const interpolationType = this.interpolationType;
  5494. const interpolationSampling = this.interpolationSampling;
  5495. properties.varying = varying = builder.getVaryingFromNode( this, name, type, interpolationType, interpolationSampling );
  5496. properties.node = subBuild( this.node, 'VERTEX' );
  5497. }
  5498. // this property can be used to check if the varying can be optimized for a variable
  5499. varying.needsInterpolation || ( varying.needsInterpolation = ( builder.shaderStage === 'fragment' ) );
  5500. return varying;
  5501. }
  5502. setup( builder ) {
  5503. this.setupVarying( builder );
  5504. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node );
  5505. }
  5506. analyze( builder ) {
  5507. this.setupVarying( builder );
  5508. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node );
  5509. }
  5510. generate( builder ) {
  5511. const propertyKey = builder.getSubBuildProperty( 'property', builder.currentStack );
  5512. const properties = builder.getNodeProperties( this );
  5513. const varying = this.setupVarying( builder );
  5514. if ( properties[ propertyKey ] === undefined ) {
  5515. const type = this.getNodeType( builder );
  5516. const propertyName = builder.getPropertyName( varying, NodeShaderStage.VERTEX );
  5517. // force node run in vertex stage
  5518. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, properties.node, type, propertyName );
  5519. properties[ propertyKey ] = propertyName;
  5520. }
  5521. return builder.getPropertyName( varying );
  5522. }
  5523. }
  5524. /**
  5525. * TSL function for creating a varying node.
  5526. *
  5527. * @tsl
  5528. * @function
  5529. * @param {Node} node - The node for which a varying should be created.
  5530. * @param {?string} name - The name of the varying in the shader.
  5531. * @returns {VaryingNode}
  5532. */
  5533. const varying = /*@__PURE__*/ nodeProxy( VaryingNode ).setParameterLength( 1, 2 );
  5534. /**
  5535. * Computes a node in the vertex stage.
  5536. *
  5537. * @tsl
  5538. * @function
  5539. * @param {Node} node - The node which should be executed in the vertex stage.
  5540. * @returns {VaryingNode}
  5541. */
  5542. const vertexStage = ( node ) => varying( node );
  5543. addMethodChaining( 'toVarying', varying );
  5544. addMethodChaining( 'toVertexStage', vertexStage );
  5545. // Deprecated
  5546. addMethodChaining( 'varying', ( ...params ) => { // @deprecated, r173
  5547. console.warn( 'THREE.TSL: .varying() has been renamed to .toVarying().' );
  5548. return varying( ...params );
  5549. } );
  5550. addMethodChaining( 'vertexStage', ( ...params ) => { // @deprecated, r173
  5551. console.warn( 'THREE.TSL: .vertexStage() has been renamed to .toVertexStage().' );
  5552. return varying( ...params );
  5553. } );
  5554. /**
  5555. * Converts the given color value from sRGB to linear-sRGB color space.
  5556. *
  5557. * @tsl
  5558. * @function
  5559. * @param {Node<vec3>} color - The sRGB color.
  5560. * @return {Node<vec3>} The linear-sRGB color.
  5561. */
  5562. const sRGBTransferEOTF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  5563. const a = color.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 );
  5564. const b = color.mul( 0.0773993808 );
  5565. const factor = color.lessThanEqual( 0.04045 );
  5566. const rgbResult = mix( a, b, factor );
  5567. return rgbResult;
  5568. } ).setLayout( {
  5569. name: 'sRGBTransferEOTF',
  5570. type: 'vec3',
  5571. inputs: [
  5572. { name: 'color', type: 'vec3' }
  5573. ]
  5574. } );
  5575. /**
  5576. * Converts the given color value from linear-sRGB to sRGB color space.
  5577. *
  5578. * @tsl
  5579. * @function
  5580. * @param {Node<vec3>} color - The linear-sRGB color.
  5581. * @return {Node<vec3>} The sRGB color.
  5582. */
  5583. const sRGBTransferOETF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  5584. const a = color.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 );
  5585. const b = color.mul( 12.92 );
  5586. const factor = color.lessThanEqual( 0.0031308 );
  5587. const rgbResult = mix( a, b, factor );
  5588. return rgbResult;
  5589. } ).setLayout( {
  5590. name: 'sRGBTransferOETF',
  5591. type: 'vec3',
  5592. inputs: [
  5593. { name: 'color', type: 'vec3' }
  5594. ]
  5595. } );
  5596. const WORKING_COLOR_SPACE = 'WorkingColorSpace';
  5597. const OUTPUT_COLOR_SPACE = 'OutputColorSpace';
  5598. /**
  5599. * This node represents a color space conversion. Meaning it converts
  5600. * a color value from a source to a target color space.
  5601. *
  5602. * @augments TempNode
  5603. */
  5604. class ColorSpaceNode extends TempNode {
  5605. static get type() {
  5606. return 'ColorSpaceNode';
  5607. }
  5608. /**
  5609. * Constructs a new color space node.
  5610. *
  5611. * @param {Node} colorNode - Represents the color to convert.
  5612. * @param {string} source - The source color space.
  5613. * @param {string} target - The target color space.
  5614. */
  5615. constructor( colorNode, source, target ) {
  5616. super( 'vec4' );
  5617. /**
  5618. * Represents the color to convert.
  5619. *
  5620. * @type {Node}
  5621. */
  5622. this.colorNode = colorNode;
  5623. /**
  5624. * The source color space.
  5625. *
  5626. * @type {string}
  5627. */
  5628. this.source = source;
  5629. /**
  5630. * The target color space.
  5631. *
  5632. * @type {string}
  5633. */
  5634. this.target = target;
  5635. }
  5636. /**
  5637. * This method resolves the constants `WORKING_COLOR_SPACE` and
  5638. * `OUTPUT_COLOR_SPACE` based on the current configuration of the
  5639. * color management and renderer.
  5640. *
  5641. * @param {NodeBuilder} builder - The current node builder.
  5642. * @param {string} colorSpace - The color space to resolve.
  5643. * @return {string} The resolved color space.
  5644. */
  5645. resolveColorSpace( builder, colorSpace ) {
  5646. if ( colorSpace === WORKING_COLOR_SPACE ) {
  5647. return ColorManagement.workingColorSpace;
  5648. } else if ( colorSpace === OUTPUT_COLOR_SPACE ) {
  5649. return builder.context.outputColorSpace || builder.renderer.outputColorSpace;
  5650. }
  5651. return colorSpace;
  5652. }
  5653. setup( builder ) {
  5654. const { colorNode } = this;
  5655. const source = this.resolveColorSpace( builder, this.source );
  5656. const target = this.resolveColorSpace( builder, this.target );
  5657. let outputNode = colorNode;
  5658. if ( ColorManagement.enabled === false || source === target || ! source || ! target ) {
  5659. return outputNode;
  5660. }
  5661. if ( ColorManagement.getTransfer( source ) === SRGBTransfer ) {
  5662. outputNode = vec4( sRGBTransferEOTF( outputNode.rgb ), outputNode.a );
  5663. }
  5664. if ( ColorManagement.getPrimaries( source ) !== ColorManagement.getPrimaries( target ) ) {
  5665. outputNode = vec4(
  5666. mat3( ColorManagement._getMatrix( new Matrix3(), source, target ) ).mul( outputNode.rgb ),
  5667. outputNode.a
  5668. );
  5669. }
  5670. if ( ColorManagement.getTransfer( target ) === SRGBTransfer ) {
  5671. outputNode = vec4( sRGBTransferOETF( outputNode.rgb ), outputNode.a );
  5672. }
  5673. return outputNode;
  5674. }
  5675. }
  5676. /**
  5677. * TSL function for converting a given color node from the current working color space to the given color space.
  5678. *
  5679. * @tsl
  5680. * @function
  5681. * @param {Node} node - Represents the node to convert.
  5682. * @param {string} targetColorSpace - The target color space.
  5683. * @returns {ColorSpaceNode}
  5684. */
  5685. const workingToColorSpace = ( node, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, targetColorSpace ) );
  5686. /**
  5687. * TSL function for converting a given color node from the given color space to the current working color space.
  5688. *
  5689. * @tsl
  5690. * @function
  5691. * @param {Node} node - Represents the node to convert.
  5692. * @param {string} sourceColorSpace - The source color space.
  5693. * @returns {ColorSpaceNode}
  5694. */
  5695. const colorSpaceToWorking = ( node, sourceColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, WORKING_COLOR_SPACE ) );
  5696. /**
  5697. * TSL function for converting a given color node from one color space to another one.
  5698. *
  5699. * @tsl
  5700. * @function
  5701. * @param {Node} node - Represents the node to convert.
  5702. * @param {string} sourceColorSpace - The source color space.
  5703. * @param {string} targetColorSpace - The target color space.
  5704. * @returns {ColorSpaceNode}
  5705. */
  5706. const convertColorSpace = ( node, sourceColorSpace, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, targetColorSpace ) );
  5707. addMethodChaining( 'workingToColorSpace', workingToColorSpace );
  5708. addMethodChaining( 'colorSpaceToWorking', colorSpaceToWorking );
  5709. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  5710. /**
  5711. * This class is only relevant if the referenced property is array-like.
  5712. * In this case, `ReferenceElementNode` allows to refer to a specific
  5713. * element inside the data structure via an index.
  5714. *
  5715. * @augments ArrayElementNode
  5716. */
  5717. let ReferenceElementNode$1 = class ReferenceElementNode extends ArrayElementNode {
  5718. static get type() {
  5719. return 'ReferenceElementNode';
  5720. }
  5721. /**
  5722. * Constructs a new reference element node.
  5723. *
  5724. * @param {ReferenceBaseNode} referenceNode - The reference node.
  5725. * @param {Node} indexNode - The index node that defines the element access.
  5726. */
  5727. constructor( referenceNode, indexNode ) {
  5728. super( referenceNode, indexNode );
  5729. /**
  5730. * Similar to {@link ReferenceBaseNode#reference}, an additional
  5731. * property references to the current node.
  5732. *
  5733. * @type {?ReferenceBaseNode}
  5734. * @default null
  5735. */
  5736. this.referenceNode = referenceNode;
  5737. /**
  5738. * This flag can be used for type testing.
  5739. *
  5740. * @type {boolean}
  5741. * @readonly
  5742. * @default true
  5743. */
  5744. this.isReferenceElementNode = true;
  5745. }
  5746. /**
  5747. * This method is overwritten since the node type is inferred from
  5748. * the uniform type of the reference node.
  5749. *
  5750. * @return {string} The node type.
  5751. */
  5752. getNodeType() {
  5753. return this.referenceNode.uniformType;
  5754. }
  5755. generate( builder ) {
  5756. const snippet = super.generate( builder );
  5757. const arrayType = this.referenceNode.getNodeType();
  5758. const elementType = this.getNodeType();
  5759. return builder.format( snippet, arrayType, elementType );
  5760. }
  5761. };
  5762. /**
  5763. * Base class for nodes which establishes a reference to a property of another object.
  5764. * In this way, the value of the node is automatically linked to the value of
  5765. * referenced object. Reference nodes internally represent the linked value
  5766. * as a uniform.
  5767. *
  5768. * @augments Node
  5769. */
  5770. class ReferenceBaseNode extends Node {
  5771. static get type() {
  5772. return 'ReferenceBaseNode';
  5773. }
  5774. /**
  5775. * Constructs a new reference base node.
  5776. *
  5777. * @param {string} property - The name of the property the node refers to.
  5778. * @param {string} uniformType - The uniform type that should be used to represent the property value.
  5779. * @param {?Object} [object=null] - The object the property belongs to.
  5780. * @param {?number} [count=null] - When the linked property is an array-like, this parameter defines its length.
  5781. */
  5782. constructor( property, uniformType, object = null, count = null ) {
  5783. super();
  5784. /**
  5785. * The name of the property the node refers to.
  5786. *
  5787. * @type {string}
  5788. */
  5789. this.property = property;
  5790. /**
  5791. * The uniform type that should be used to represent the property value.
  5792. *
  5793. * @type {string}
  5794. */
  5795. this.uniformType = uniformType;
  5796. /**
  5797. * The object the property belongs to.
  5798. *
  5799. * @type {?Object}
  5800. * @default null
  5801. */
  5802. this.object = object;
  5803. /**
  5804. * When the linked property is an array, this parameter defines its length.
  5805. *
  5806. * @type {?number}
  5807. * @default null
  5808. */
  5809. this.count = count;
  5810. /**
  5811. * The property name might have dots so nested properties can be referred.
  5812. * The hierarchy of the names is stored inside this array.
  5813. *
  5814. * @type {Array<string>}
  5815. */
  5816. this.properties = property.split( '.' );
  5817. /**
  5818. * Points to the current referred object. This property exists next to {@link ReferenceNode#object}
  5819. * since the final reference might be updated from calling code.
  5820. *
  5821. * @type {?Object}
  5822. * @default null
  5823. */
  5824. this.reference = object;
  5825. /**
  5826. * The uniform node that holds the value of the reference node.
  5827. *
  5828. * @type {UniformNode}
  5829. * @default null
  5830. */
  5831. this.node = null;
  5832. /**
  5833. * The uniform group of the internal uniform.
  5834. *
  5835. * @type {UniformGroupNode}
  5836. * @default null
  5837. */
  5838. this.group = null;
  5839. /**
  5840. * Overwritten since reference nodes are updated per object.
  5841. *
  5842. * @type {string}
  5843. * @default 'object'
  5844. */
  5845. this.updateType = NodeUpdateType.OBJECT;
  5846. }
  5847. /**
  5848. * Sets the uniform group for this reference node.
  5849. *
  5850. * @param {UniformGroupNode} group - The uniform group to set.
  5851. * @return {ReferenceBaseNode} A reference to this node.
  5852. */
  5853. setGroup( group ) {
  5854. this.group = group;
  5855. return this;
  5856. }
  5857. /**
  5858. * When the referred property is array-like, this method can be used
  5859. * to access elements via an index node.
  5860. *
  5861. * @param {IndexNode} indexNode - indexNode.
  5862. * @return {ReferenceElementNode} A reference to an element.
  5863. */
  5864. element( indexNode ) {
  5865. return nodeObject( new ReferenceElementNode$1( this, nodeObject( indexNode ) ) );
  5866. }
  5867. /**
  5868. * Sets the node type which automatically defines the internal
  5869. * uniform type.
  5870. *
  5871. * @param {string} uniformType - The type to set.
  5872. */
  5873. setNodeType( uniformType ) {
  5874. const node = uniform( null, uniformType ).getSelf();
  5875. if ( this.group !== null ) {
  5876. node.setGroup( this.group );
  5877. }
  5878. this.node = node;
  5879. }
  5880. /**
  5881. * This method is overwritten since the node type is inferred from
  5882. * the type of the reference node.
  5883. *
  5884. * @param {NodeBuilder} builder - The current node builder.
  5885. * @return {string} The node type.
  5886. */
  5887. getNodeType( builder ) {
  5888. if ( this.node === null ) {
  5889. this.updateReference( builder );
  5890. this.updateValue();
  5891. }
  5892. return this.node.getNodeType( builder );
  5893. }
  5894. /**
  5895. * Returns the property value from the given referred object.
  5896. *
  5897. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  5898. * @return {any} The value.
  5899. */
  5900. getValueFromReference( object = this.reference ) {
  5901. const { properties } = this;
  5902. let value = object[ properties[ 0 ] ];
  5903. for ( let i = 1; i < properties.length; i ++ ) {
  5904. value = value[ properties[ i ] ];
  5905. }
  5906. return value;
  5907. }
  5908. /**
  5909. * Allows to update the reference based on the given state. The state is only
  5910. * evaluated {@link ReferenceBaseNode#object} is not set.
  5911. *
  5912. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  5913. * @return {Object} The updated reference.
  5914. */
  5915. updateReference( state ) {
  5916. this.reference = this.object !== null ? this.object : state.object;
  5917. return this.reference;
  5918. }
  5919. /**
  5920. * The output of the reference node is the internal uniform node.
  5921. *
  5922. * @return {UniformNode} The output node.
  5923. */
  5924. setup() {
  5925. this.updateValue();
  5926. return this.node;
  5927. }
  5928. /**
  5929. * Overwritten to update the internal uniform value.
  5930. *
  5931. * @param {NodeFrame} frame - A reference to the current node frame.
  5932. */
  5933. update( /*frame*/ ) {
  5934. this.updateValue();
  5935. }
  5936. /**
  5937. * Retrieves the value from the referred object property and uses it
  5938. * to updated the internal uniform.
  5939. */
  5940. updateValue() {
  5941. if ( this.node === null ) this.setNodeType( this.uniformType );
  5942. const value = this.getValueFromReference();
  5943. if ( Array.isArray( value ) ) {
  5944. this.node.array = value;
  5945. } else {
  5946. this.node.value = value;
  5947. }
  5948. }
  5949. }
  5950. /**
  5951. * TSL function for creating a reference base node.
  5952. *
  5953. * @tsl
  5954. * @function
  5955. * @param {string} name - The name of the property the node refers to.
  5956. * @param {string} type - The uniform type that should be used to represent the property value.
  5957. * @param {Object} object - The object the property belongs to.
  5958. * @returns {ReferenceBaseNode}
  5959. */
  5960. const reference$1 = ( name, type, object ) => nodeObject( new ReferenceBaseNode( name, type, object ) );
  5961. /**
  5962. * This node is a special type of reference node which is intended
  5963. * for linking renderer properties with node values.
  5964. * ```js
  5965. * const exposureNode = rendererReference( 'toneMappingExposure', 'float', renderer );
  5966. * ```
  5967. * When changing `renderer.toneMappingExposure`, the node value of `exposureNode` will
  5968. * automatically be updated.
  5969. *
  5970. * @augments ReferenceBaseNode
  5971. */
  5972. class RendererReferenceNode extends ReferenceBaseNode {
  5973. static get type() {
  5974. return 'RendererReferenceNode';
  5975. }
  5976. /**
  5977. * Constructs a new renderer reference node.
  5978. *
  5979. * @param {string} property - The name of the property the node refers to.
  5980. * @param {string} inputType - The uniform type that should be used to represent the property value.
  5981. * @param {?Renderer} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  5982. * the node refers to the renderer of the current state.
  5983. */
  5984. constructor( property, inputType, renderer = null ) {
  5985. super( property, inputType, renderer );
  5986. /**
  5987. * The renderer the property belongs to. When no renderer is set,
  5988. * the node refers to the renderer of the current state.
  5989. *
  5990. * @type {?Renderer}
  5991. * @default null
  5992. */
  5993. this.renderer = renderer;
  5994. this.setGroup( renderGroup );
  5995. }
  5996. /**
  5997. * Updates the reference based on the given state. The state is only evaluated
  5998. * {@link RendererReferenceNode#renderer} is not set.
  5999. *
  6000. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  6001. * @return {Object} The updated reference.
  6002. */
  6003. updateReference( state ) {
  6004. this.reference = this.renderer !== null ? this.renderer : state.renderer;
  6005. return this.reference;
  6006. }
  6007. }
  6008. /**
  6009. * TSL function for creating a renderer reference node.
  6010. *
  6011. * @tsl
  6012. * @function
  6013. * @param {string} name - The name of the property the node refers to.
  6014. * @param {string} type - The uniform type that should be used to represent the property value.
  6015. * @param {?Renderer} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  6016. * the node refers to the renderer of the current state.
  6017. * @returns {RendererReferenceNode}
  6018. */
  6019. const rendererReference = ( name, type, renderer = null ) => nodeObject( new RendererReferenceNode( name, type, renderer ) );
  6020. /**
  6021. * This node represents a tone mapping operation.
  6022. *
  6023. * @augments TempNode
  6024. */
  6025. class ToneMappingNode extends TempNode {
  6026. static get type() {
  6027. return 'ToneMappingNode';
  6028. }
  6029. /**
  6030. * Constructs a new tone mapping node.
  6031. *
  6032. * @param {number} toneMapping - The tone mapping type.
  6033. * @param {Node} exposureNode - The tone mapping exposure.
  6034. * @param {Node} [colorNode=null] - The color node to process.
  6035. */
  6036. constructor( toneMapping, exposureNode = toneMappingExposure, colorNode = null ) {
  6037. super( 'vec3' );
  6038. /**
  6039. * The tone mapping type.
  6040. *
  6041. * @type {number}
  6042. */
  6043. this.toneMapping = toneMapping;
  6044. /**
  6045. * The tone mapping exposure.
  6046. *
  6047. * @type {Node}
  6048. * @default null
  6049. */
  6050. this.exposureNode = exposureNode;
  6051. /**
  6052. * Represents the color to process.
  6053. *
  6054. * @type {?Node}
  6055. * @default null
  6056. */
  6057. this.colorNode = colorNode;
  6058. }
  6059. /**
  6060. * Overwrites the default `customCacheKey()` implementation by including the tone
  6061. * mapping type into the cache key.
  6062. *
  6063. * @return {number} The hash.
  6064. */
  6065. customCacheKey() {
  6066. return hash$1( this.toneMapping );
  6067. }
  6068. setup( builder ) {
  6069. const colorNode = this.colorNode || builder.context.color;
  6070. const toneMapping = this.toneMapping;
  6071. if ( toneMapping === NoToneMapping ) return colorNode;
  6072. let outputNode = null;
  6073. const toneMappingFn = builder.renderer.library.getToneMappingFunction( toneMapping );
  6074. if ( toneMappingFn !== null ) {
  6075. outputNode = vec4( toneMappingFn( colorNode.rgb, this.exposureNode ), colorNode.a );
  6076. } else {
  6077. console.error( 'ToneMappingNode: Unsupported Tone Mapping configuration.', toneMapping );
  6078. outputNode = colorNode;
  6079. }
  6080. return outputNode;
  6081. }
  6082. }
  6083. /**
  6084. * TSL function for creating a tone mapping node.
  6085. *
  6086. * @tsl
  6087. * @function
  6088. * @param {number} mapping - The tone mapping type.
  6089. * @param {Node<float> | number} exposure - The tone mapping exposure.
  6090. * @param {Node<vec3> | Color} color - The color node to process.
  6091. * @returns {ToneMappingNode<vec3>}
  6092. */
  6093. const toneMapping = ( mapping, exposure, color ) => nodeObject( new ToneMappingNode( mapping, nodeObject( exposure ), nodeObject( color ) ) );
  6094. /**
  6095. * TSL object that represents the global tone mapping exposure of the renderer.
  6096. *
  6097. * @tsl
  6098. * @type {RendererReferenceNode<vec3>}
  6099. */
  6100. const toneMappingExposure = /*@__PURE__*/ rendererReference( 'toneMappingExposure', 'float' );
  6101. addMethodChaining( 'toneMapping', ( color, mapping, exposure ) => toneMapping( mapping, exposure, color ) );
  6102. /**
  6103. * In earlier `three.js` versions it was only possible to define attribute data
  6104. * on geometry level. With `BufferAttributeNode`, it is also possible to do this
  6105. * on the node level.
  6106. * ```js
  6107. * const geometry = new THREE.PlaneGeometry();
  6108. * const positionAttribute = geometry.getAttribute( 'position' );
  6109. *
  6110. * const colors = [];
  6111. * for ( let i = 0; i < position.count; i ++ ) {
  6112. * colors.push( 1, 0, 0 );
  6113. * }
  6114. *
  6115. * material.colorNode = bufferAttribute( new THREE.Float32BufferAttribute( colors, 3 ) );
  6116. * ```
  6117. * This new approach is especially interesting when geometry data are generated via
  6118. * compute shaders. The below line converts a storage buffer into an attribute node.
  6119. * ```js
  6120. * material.positionNode = positionBuffer.toAttribute();
  6121. * ```
  6122. * @augments InputNode
  6123. */
  6124. class BufferAttributeNode extends InputNode {
  6125. static get type() {
  6126. return 'BufferAttributeNode';
  6127. }
  6128. /**
  6129. * Constructs a new buffer attribute node.
  6130. *
  6131. * @param {BufferAttribute|InterleavedBuffer|TypedArray} value - The attribute data.
  6132. * @param {?string} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  6133. * @param {number} [bufferStride=0] - The buffer stride.
  6134. * @param {number} [bufferOffset=0] - The buffer offset.
  6135. */
  6136. constructor( value, bufferType = null, bufferStride = 0, bufferOffset = 0 ) {
  6137. super( value, bufferType );
  6138. /**
  6139. * This flag can be used for type testing.
  6140. *
  6141. * @type {boolean}
  6142. * @readonly
  6143. * @default true
  6144. */
  6145. this.isBufferNode = true;
  6146. /**
  6147. * The buffer type (e.g. `'vec3'`).
  6148. *
  6149. * @type {?string}
  6150. * @default null
  6151. */
  6152. this.bufferType = bufferType;
  6153. /**
  6154. * The buffer stride.
  6155. *
  6156. * @type {number}
  6157. * @default 0
  6158. */
  6159. this.bufferStride = bufferStride;
  6160. /**
  6161. * The buffer offset.
  6162. *
  6163. * @type {number}
  6164. * @default 0
  6165. */
  6166. this.bufferOffset = bufferOffset;
  6167. /**
  6168. * The usage property. Set this to `THREE.DynamicDrawUsage` via `.setUsage()`,
  6169. * if you are planning to update the attribute data per frame.
  6170. *
  6171. * @type {number}
  6172. * @default StaticDrawUsage
  6173. */
  6174. this.usage = StaticDrawUsage;
  6175. /**
  6176. * Whether the attribute is instanced or not.
  6177. *
  6178. * @type {boolean}
  6179. * @default false
  6180. */
  6181. this.instanced = false;
  6182. /**
  6183. * A reference to the buffer attribute.
  6184. *
  6185. * @type {?BufferAttribute}
  6186. * @default null
  6187. */
  6188. this.attribute = null;
  6189. /**
  6190. * `BufferAttributeNode` sets this property to `true` by default.
  6191. *
  6192. * @type {boolean}
  6193. * @default true
  6194. */
  6195. this.global = true;
  6196. if ( value && value.isBufferAttribute === true ) {
  6197. this.attribute = value;
  6198. this.usage = value.usage;
  6199. this.instanced = value.isInstancedBufferAttribute;
  6200. }
  6201. }
  6202. /**
  6203. * This method is overwritten since the attribute data might be shared
  6204. * and thus the hash should be shared as well.
  6205. *
  6206. * @param {NodeBuilder} builder - The current node builder.
  6207. * @return {string} The hash.
  6208. */
  6209. getHash( builder ) {
  6210. if ( this.bufferStride === 0 && this.bufferOffset === 0 ) {
  6211. let bufferData = builder.globalCache.getData( this.value );
  6212. if ( bufferData === undefined ) {
  6213. bufferData = {
  6214. node: this
  6215. };
  6216. builder.globalCache.setData( this.value, bufferData );
  6217. }
  6218. return bufferData.node.uuid;
  6219. }
  6220. return this.uuid;
  6221. }
  6222. /**
  6223. * This method is overwritten since the node type is inferred from
  6224. * the buffer attribute.
  6225. *
  6226. * @param {NodeBuilder} builder - The current node builder.
  6227. * @return {string} The node type.
  6228. */
  6229. getNodeType( builder ) {
  6230. if ( this.bufferType === null ) {
  6231. this.bufferType = builder.getTypeFromAttribute( this.attribute );
  6232. }
  6233. return this.bufferType;
  6234. }
  6235. /**
  6236. * Depending on which value was passed to the node, `setup()` behaves
  6237. * differently. If no instance of `BufferAttribute` was passed, the method
  6238. * creates an internal attribute and configures it respectively.
  6239. *
  6240. * @param {NodeBuilder} builder - The current node builder.
  6241. */
  6242. setup( builder ) {
  6243. if ( this.attribute !== null ) return;
  6244. const type = this.getNodeType( builder );
  6245. const array = this.value;
  6246. const itemSize = builder.getTypeLength( type );
  6247. const stride = this.bufferStride || itemSize;
  6248. const offset = this.bufferOffset;
  6249. const buffer = array.isInterleavedBuffer === true ? array : new InterleavedBuffer( array, stride );
  6250. const bufferAttribute = new InterleavedBufferAttribute( buffer, itemSize, offset );
  6251. buffer.setUsage( this.usage );
  6252. this.attribute = bufferAttribute;
  6253. this.attribute.isInstancedBufferAttribute = this.instanced; // @TODO: Add a possible: InstancedInterleavedBufferAttribute
  6254. }
  6255. /**
  6256. * Generates the code snippet of the buffer attribute node.
  6257. *
  6258. * @param {NodeBuilder} builder - The current node builder.
  6259. * @return {string} The generated code snippet.
  6260. */
  6261. generate( builder ) {
  6262. const nodeType = this.getNodeType( builder );
  6263. const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType );
  6264. const propertyName = builder.getPropertyName( nodeAttribute );
  6265. let output = null;
  6266. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  6267. this.name = propertyName;
  6268. output = propertyName;
  6269. } else {
  6270. const nodeVarying = varying( this );
  6271. output = nodeVarying.build( builder, nodeType );
  6272. }
  6273. return output;
  6274. }
  6275. /**
  6276. * Overwrites the default implementation to return a fixed value `'bufferAttribute'`.
  6277. *
  6278. * @param {NodeBuilder} builder - The current node builder.
  6279. * @return {string} The input type.
  6280. */
  6281. getInputType( /*builder*/ ) {
  6282. return 'bufferAttribute';
  6283. }
  6284. /**
  6285. * Sets the `usage` property to the given value.
  6286. *
  6287. * @param {number} value - The usage to set.
  6288. * @return {BufferAttributeNode} A reference to this node.
  6289. */
  6290. setUsage( value ) {
  6291. this.usage = value;
  6292. if ( this.attribute && this.attribute.isBufferAttribute === true ) {
  6293. this.attribute.usage = value;
  6294. }
  6295. return this;
  6296. }
  6297. /**
  6298. * Sets the `instanced` property to the given value.
  6299. *
  6300. * @param {boolean} value - The value to set.
  6301. * @return {BufferAttributeNode} A reference to this node.
  6302. */
  6303. setInstanced( value ) {
  6304. this.instanced = value;
  6305. return this;
  6306. }
  6307. }
  6308. /**
  6309. * TSL function for creating a buffer attribute node.
  6310. *
  6311. * @tsl
  6312. * @function
  6313. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6314. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6315. * @param {number} [stride=0] - The buffer stride.
  6316. * @param {number} [offset=0] - The buffer offset.
  6317. * @returns {BufferAttributeNode}
  6318. */
  6319. const bufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => nodeObject( new BufferAttributeNode( array, type, stride, offset ) );
  6320. /**
  6321. * TSL function for creating a buffer attribute node but with dynamic draw usage.
  6322. * Use this function if attribute data are updated per frame.
  6323. *
  6324. * @tsl
  6325. * @function
  6326. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6327. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6328. * @param {number} [stride=0] - The buffer stride.
  6329. * @param {number} [offset=0] - The buffer offset.
  6330. * @returns {BufferAttributeNode}
  6331. */
  6332. const dynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => bufferAttribute( array, type, stride, offset ).setUsage( DynamicDrawUsage );
  6333. /**
  6334. * TSL function for creating a buffer attribute node but with enabled instancing
  6335. *
  6336. * @tsl
  6337. * @function
  6338. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6339. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6340. * @param {number} [stride=0] - The buffer stride.
  6341. * @param {number} [offset=0] - The buffer offset.
  6342. * @returns {BufferAttributeNode}
  6343. */
  6344. const instancedBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => bufferAttribute( array, type, stride, offset ).setInstanced( true );
  6345. /**
  6346. * TSL function for creating a buffer attribute node but with dynamic draw usage and enabled instancing
  6347. *
  6348. * @tsl
  6349. * @function
  6350. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6351. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6352. * @param {number} [stride=0] - The buffer stride.
  6353. * @param {number} [offset=0] - The buffer offset.
  6354. * @returns {BufferAttributeNode}
  6355. */
  6356. const instancedDynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => dynamicBufferAttribute( array, type, stride, offset ).setInstanced( true );
  6357. addMethodChaining( 'toAttribute', ( bufferNode ) => bufferAttribute( bufferNode.value ) );
  6358. /**
  6359. * TODO
  6360. *
  6361. * @augments Node
  6362. */
  6363. class ComputeNode extends Node {
  6364. static get type() {
  6365. return 'ComputeNode';
  6366. }
  6367. /**
  6368. * Constructs a new compute node.
  6369. *
  6370. * @param {Node} computeNode - TODO
  6371. * @param {Array<number>} workgroupSize - TODO.
  6372. */
  6373. constructor( computeNode, workgroupSize ) {
  6374. super( 'void' );
  6375. /**
  6376. * This flag can be used for type testing.
  6377. *
  6378. * @type {boolean}
  6379. * @readonly
  6380. * @default true
  6381. */
  6382. this.isComputeNode = true;
  6383. /**
  6384. * TODO
  6385. *
  6386. * @type {Node}
  6387. */
  6388. this.computeNode = computeNode;
  6389. /**
  6390. * TODO
  6391. *
  6392. * @type {Array<number>}
  6393. * @default [ 64 ]
  6394. */
  6395. this.workgroupSize = workgroupSize;
  6396. /**
  6397. * TODO
  6398. *
  6399. * @type {number}
  6400. */
  6401. this.count = null;
  6402. /**
  6403. * TODO
  6404. *
  6405. * @type {number}
  6406. */
  6407. this.version = 1;
  6408. /**
  6409. * The name or label of the uniform.
  6410. *
  6411. * @type {string}
  6412. * @default ''
  6413. */
  6414. this.name = '';
  6415. /**
  6416. * The `updateBeforeType` is set to `NodeUpdateType.OBJECT` since {@link ComputeNode#updateBefore}
  6417. * is executed once per object by default.
  6418. *
  6419. * @type {string}
  6420. * @default 'object'
  6421. */
  6422. this.updateBeforeType = NodeUpdateType.OBJECT;
  6423. /**
  6424. * TODO
  6425. *
  6426. * @type {?Function}
  6427. */
  6428. this.onInitFunction = null;
  6429. }
  6430. setCount( count ) {
  6431. this.count = count;
  6432. return this;
  6433. }
  6434. getCount() {
  6435. return this.count;
  6436. }
  6437. /**
  6438. * Executes the `dispose` event for this node.
  6439. */
  6440. dispose() {
  6441. this.dispatchEvent( { type: 'dispose' } );
  6442. }
  6443. /**
  6444. * Sets the {@link ComputeNode#name} property.
  6445. *
  6446. * @param {string} name - The name of the uniform.
  6447. * @return {ComputeNode} A reference to this node.
  6448. */
  6449. label( name ) {
  6450. this.name = name;
  6451. return this;
  6452. }
  6453. /**
  6454. * TODO
  6455. *
  6456. * @param {Function} callback - TODO.
  6457. * @return {ComputeNode} A reference to this node.
  6458. */
  6459. onInit( callback ) {
  6460. this.onInitFunction = callback;
  6461. return this;
  6462. }
  6463. /**
  6464. * The method execute the compute for this node.
  6465. *
  6466. * @param {NodeFrame} frame - A reference to the current node frame.
  6467. */
  6468. updateBefore( { renderer } ) {
  6469. renderer.compute( this );
  6470. }
  6471. setup( builder ) {
  6472. const result = this.computeNode.build( builder );
  6473. if ( result ) {
  6474. const properties = builder.getNodeProperties( this );
  6475. properties.outputComputeNode = result.outputNode;
  6476. result.outputNode = null;
  6477. }
  6478. return result;
  6479. }
  6480. generate( builder, output ) {
  6481. const { shaderStage } = builder;
  6482. if ( shaderStage === 'compute' ) {
  6483. const snippet = this.computeNode.build( builder, 'void' );
  6484. if ( snippet !== '' ) {
  6485. builder.addLineFlowCode( snippet, this );
  6486. }
  6487. } else {
  6488. const properties = builder.getNodeProperties( this );
  6489. const outputComputeNode = properties.outputComputeNode;
  6490. if ( outputComputeNode ) {
  6491. return outputComputeNode.build( builder, output );
  6492. }
  6493. }
  6494. }
  6495. }
  6496. /**
  6497. * TSL function for creating a compute kernel node.
  6498. *
  6499. * @tsl
  6500. * @function
  6501. * @param {Node} node - TODO
  6502. * @param {Array<number>} [workgroupSize=[64]] - TODO.
  6503. * @returns {AtomicFunctionNode}
  6504. */
  6505. const computeKernel = ( node, workgroupSize = [ 64 ] ) => {
  6506. if ( workgroupSize.length === 0 || workgroupSize.length > 3 ) {
  6507. console.error( 'THREE.TSL: compute() workgroupSize must have 1, 2, or 3 elements' );
  6508. }
  6509. for ( let i = 0; i < workgroupSize.length; i ++ ) {
  6510. const val = workgroupSize[ i ];
  6511. if ( typeof val !== 'number' || val <= 0 || ! Number.isInteger( val ) ) {
  6512. console.error( `THREE.TSL: compute() workgroupSize element at index [ ${ i } ] must be a positive integer` );
  6513. }
  6514. }
  6515. // Implicit fill-up to [ x, y, z ] with 1s, just like WGSL treats @workgroup_size when fewer dimensions are specified
  6516. while ( workgroupSize.length < 3 ) workgroupSize.push( 1 );
  6517. //
  6518. return nodeObject( new ComputeNode( nodeObject( node ), workgroupSize ) );
  6519. };
  6520. /**
  6521. * TSL function for creating a compute node.
  6522. *
  6523. * @tsl
  6524. * @function
  6525. * @param {Node} node - TODO
  6526. * @param {number} count - TODO.
  6527. * @param {Array<number>} [workgroupSize=[64]] - TODO.
  6528. * @returns {AtomicFunctionNode}
  6529. */
  6530. const compute = ( node, count, workgroupSize ) => computeKernel( node, workgroupSize ).setCount( count );
  6531. addMethodChaining( 'compute', compute );
  6532. addMethodChaining( 'computeKernel', computeKernel );
  6533. /**
  6534. * This node can be used as a cache management component for another node.
  6535. * Caching is in general used by default in {@link NodeBuilder} but this node
  6536. * allows the usage of a shared parent cache during the build process.
  6537. *
  6538. * @augments Node
  6539. */
  6540. class CacheNode extends Node {
  6541. static get type() {
  6542. return 'CacheNode';
  6543. }
  6544. /**
  6545. * Constructs a new cache node.
  6546. *
  6547. * @param {Node} node - The node that should be cached.
  6548. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  6549. */
  6550. constructor( node, parent = true ) {
  6551. super();
  6552. /**
  6553. * The node that should be cached.
  6554. *
  6555. * @type {Node}
  6556. */
  6557. this.node = node;
  6558. /**
  6559. * Whether this node refers to a shared parent cache or not.
  6560. *
  6561. * @type {boolean}
  6562. * @default true
  6563. */
  6564. this.parent = parent;
  6565. /**
  6566. * This flag can be used for type testing.
  6567. *
  6568. * @type {boolean}
  6569. * @readonly
  6570. * @default true
  6571. */
  6572. this.isCacheNode = true;
  6573. }
  6574. getNodeType( builder ) {
  6575. const previousCache = builder.getCache();
  6576. const cache = builder.getCacheFromNode( this, this.parent );
  6577. builder.setCache( cache );
  6578. const nodeType = this.node.getNodeType( builder );
  6579. builder.setCache( previousCache );
  6580. return nodeType;
  6581. }
  6582. build( builder, ...params ) {
  6583. const previousCache = builder.getCache();
  6584. const cache = builder.getCacheFromNode( this, this.parent );
  6585. builder.setCache( cache );
  6586. const data = this.node.build( builder, ...params );
  6587. builder.setCache( previousCache );
  6588. return data;
  6589. }
  6590. }
  6591. /**
  6592. * TSL function for creating a cache node.
  6593. *
  6594. * @tsl
  6595. * @function
  6596. * @param {Node} node - The node that should be cached.
  6597. * @param {boolean} [parent] - Whether this node refers to a shared parent cache or not.
  6598. * @returns {CacheNode}
  6599. */
  6600. const cache = ( node, parent ) => nodeObject( new CacheNode( nodeObject( node ), parent ) );
  6601. addMethodChaining( 'cache', cache );
  6602. /**
  6603. * The class generates the code of a given node but returns another node in the output.
  6604. * This can be used to call a method or node that does not return a value, i.e.
  6605. * type `void` on an input where returning a value is required. Example:
  6606. *
  6607. * ```js
  6608. * material.colorNode = myColor.bypass( runVoidFn() )
  6609. *```
  6610. *
  6611. * @augments Node
  6612. */
  6613. class BypassNode extends Node {
  6614. static get type() {
  6615. return 'BypassNode';
  6616. }
  6617. /**
  6618. * Constructs a new bypass node.
  6619. *
  6620. * @param {Node} outputNode - The output node.
  6621. * @param {Node} callNode - The call node.
  6622. */
  6623. constructor( outputNode, callNode ) {
  6624. super();
  6625. /**
  6626. * This flag can be used for type testing.
  6627. *
  6628. * @type {boolean}
  6629. * @readonly
  6630. * @default true
  6631. */
  6632. this.isBypassNode = true;
  6633. /**
  6634. * The output node.
  6635. *
  6636. * @type {Node}
  6637. */
  6638. this.outputNode = outputNode;
  6639. /**
  6640. * The call node.
  6641. *
  6642. * @type {Node}
  6643. */
  6644. this.callNode = callNode;
  6645. }
  6646. getNodeType( builder ) {
  6647. return this.outputNode.getNodeType( builder );
  6648. }
  6649. generate( builder ) {
  6650. const snippet = this.callNode.build( builder, 'void' );
  6651. if ( snippet !== '' ) {
  6652. builder.addLineFlowCode( snippet, this );
  6653. }
  6654. return this.outputNode.build( builder );
  6655. }
  6656. }
  6657. /**
  6658. * TSL function for creating a bypass node.
  6659. *
  6660. * @tsl
  6661. * @function
  6662. * @param {Node} outputNode - The output node.
  6663. * @param {Node} callNode - The call node.
  6664. * @returns {BypassNode}
  6665. */
  6666. const bypass = /*@__PURE__*/ nodeProxy( BypassNode ).setParameterLength( 2 );
  6667. addMethodChaining( 'bypass', bypass );
  6668. /**
  6669. * This node allows to remap a node value from one range into another. E.g a value of
  6670. * `0.4` in the range `[ 0.3, 0.5 ]` should be remapped into the normalized range `[ 0, 1 ]`.
  6671. * `RemapNode` takes care of that and converts the original value of `0.4` to `0.5`.
  6672. *
  6673. * @augments Node
  6674. */
  6675. class RemapNode extends Node {
  6676. static get type() {
  6677. return 'RemapNode';
  6678. }
  6679. /**
  6680. * Constructs a new remap node.
  6681. *
  6682. * @param {Node} node - The node that should be remapped.
  6683. * @param {Node} inLowNode - The source or current lower bound of the range.
  6684. * @param {Node} inHighNode - The source or current upper bound of the range.
  6685. * @param {Node} [outLowNode=float(0)] - The target lower bound of the range.
  6686. * @param {Node} [outHighNode=float(1)] - The target upper bound of the range.
  6687. */
  6688. constructor( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) {
  6689. super();
  6690. /**
  6691. * The node that should be remapped.
  6692. *
  6693. * @type {Node}
  6694. */
  6695. this.node = node;
  6696. /**
  6697. * The source or current lower bound of the range.
  6698. *
  6699. * @type {Node}
  6700. */
  6701. this.inLowNode = inLowNode;
  6702. /**
  6703. * The source or current upper bound of the range.
  6704. *
  6705. * @type {Node}
  6706. */
  6707. this.inHighNode = inHighNode;
  6708. /**
  6709. * The target lower bound of the range.
  6710. *
  6711. * @type {Node}
  6712. * @default float(0)
  6713. */
  6714. this.outLowNode = outLowNode;
  6715. /**
  6716. * The target upper bound of the range.
  6717. *
  6718. * @type {Node}
  6719. * @default float(1)
  6720. */
  6721. this.outHighNode = outHighNode;
  6722. /**
  6723. * Whether the node value should be clamped before
  6724. * remapping it to the target range.
  6725. *
  6726. * @type {boolean}
  6727. * @default true
  6728. */
  6729. this.doClamp = true;
  6730. }
  6731. setup() {
  6732. const { node, inLowNode, inHighNode, outLowNode, outHighNode, doClamp } = this;
  6733. let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) );
  6734. if ( doClamp === true ) t = t.clamp();
  6735. return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode );
  6736. }
  6737. }
  6738. /**
  6739. * TSL function for creating a remap node.
  6740. *
  6741. * @tsl
  6742. * @function
  6743. * @param {Node} node - The node that should be remapped.
  6744. * @param {Node} inLowNode - The source or current lower bound of the range.
  6745. * @param {Node} inHighNode - The source or current upper bound of the range.
  6746. * @param {?Node} [outLowNode=float(0)] - The target lower bound of the range.
  6747. * @param {?Node} [outHighNode=float(1)] - The target upper bound of the range.
  6748. * @returns {RemapNode}
  6749. */
  6750. const remap = /*@__PURE__*/ nodeProxy( RemapNode, null, null, { doClamp: false } ).setParameterLength( 3, 5 );
  6751. /**
  6752. * TSL function for creating a remap node, but with enabled clamping.
  6753. *
  6754. * @tsl
  6755. * @function
  6756. * @param {Node} node - The node that should be remapped.
  6757. * @param {Node} inLowNode - The source or current lower bound of the range.
  6758. * @param {Node} inHighNode - The source or current upper bound of the range.
  6759. * @param {?Node} [outLowNode=float(0)] - The target lower bound of the range.
  6760. * @param {?Node} [outHighNode=float(1)] - The target upper bound of the range.
  6761. * @returns {RemapNode}
  6762. */
  6763. const remapClamp = /*@__PURE__*/ nodeProxy( RemapNode ).setParameterLength( 3, 5 );
  6764. addMethodChaining( 'remap', remap );
  6765. addMethodChaining( 'remapClamp', remapClamp );
  6766. /**
  6767. * This class can be used to implement basic expressions in shader code.
  6768. * Basic examples for that are `return`, `continue` or `discard` statements.
  6769. *
  6770. * @augments Node
  6771. */
  6772. class ExpressionNode extends Node {
  6773. static get type() {
  6774. return 'ExpressionNode';
  6775. }
  6776. /**
  6777. * Constructs a new expression node.
  6778. *
  6779. * @param {string} [snippet=''] - The native code snippet.
  6780. * @param {string} [nodeType='void'] - The node type.
  6781. */
  6782. constructor( snippet = '', nodeType = 'void' ) {
  6783. super( nodeType );
  6784. /**
  6785. * The native code snippet.
  6786. *
  6787. * @type {string}
  6788. * @default ''
  6789. */
  6790. this.snippet = snippet;
  6791. }
  6792. generate( builder, output ) {
  6793. const type = this.getNodeType( builder );
  6794. const snippet = this.snippet;
  6795. if ( type === 'void' ) {
  6796. builder.addLineFlowCode( snippet, this );
  6797. } else {
  6798. return builder.format( snippet, type, output );
  6799. }
  6800. }
  6801. }
  6802. /**
  6803. * TSL function for creating an expression node.
  6804. *
  6805. * @tsl
  6806. * @function
  6807. * @param {string} [snippet] - The native code snippet.
  6808. * @param {?string} [nodeType='void'] - The node type.
  6809. * @returns {ExpressionNode}
  6810. */
  6811. const expression = /*@__PURE__*/ nodeProxy( ExpressionNode ).setParameterLength( 1, 2 );
  6812. /**
  6813. * Represents a `discard` shader operation in TSL.
  6814. *
  6815. * @tsl
  6816. * @function
  6817. * @param {?ConditionalNode} conditional - An optional conditional node. It allows to decide whether the discard should be executed or not.
  6818. * @return {Node} The `discard` expression.
  6819. */
  6820. const Discard = ( conditional ) => ( conditional ? select( conditional, expression( 'discard' ) ) : expression( 'discard' ) ).toStack();
  6821. /**
  6822. * Represents a `return` shader operation in TSL.
  6823. *
  6824. * @tsl
  6825. * @function
  6826. * @return {ExpressionNode} The `return` expression.
  6827. */
  6828. const Return = () => expression( 'return' ).toStack();
  6829. addMethodChaining( 'discard', Discard );
  6830. /**
  6831. * Normally, tone mapping and color conversion happens automatically
  6832. * before outputting pixel too the default (screen) framebuffer. In certain
  6833. * post processing setups this happens to late because certain effects
  6834. * require e.g. sRGB input. For such scenarios, `RenderOutputNode` can be used
  6835. * to apply tone mapping and color space conversion at an arbitrary point
  6836. * in the effect chain.
  6837. *
  6838. * When applying tone mapping and color space conversion manually with this node,
  6839. * you have to set {@link PostProcessing#outputColorTransform} to `false`.
  6840. *
  6841. * ```js
  6842. * const postProcessing = new PostProcessing( renderer );
  6843. * postProcessing.outputColorTransform = false;
  6844. *
  6845. * const scenePass = pass( scene, camera );
  6846. * const outputPass = renderOutput( scenePass );
  6847. *
  6848. * postProcessing.outputNode = outputPass;
  6849. * ```
  6850. *
  6851. * @augments TempNode
  6852. */
  6853. class RenderOutputNode extends TempNode {
  6854. static get type() {
  6855. return 'RenderOutputNode';
  6856. }
  6857. /**
  6858. * Constructs a new render output node.
  6859. *
  6860. * @param {Node} colorNode - The color node to process.
  6861. * @param {?number} toneMapping - The tone mapping type.
  6862. * @param {?string} outputColorSpace - The output color space.
  6863. */
  6864. constructor( colorNode, toneMapping, outputColorSpace ) {
  6865. super( 'vec4' );
  6866. /**
  6867. * The color node to process.
  6868. *
  6869. * @type {Node}
  6870. */
  6871. this.colorNode = colorNode;
  6872. /**
  6873. * The tone mapping type.
  6874. *
  6875. * @type {?number}
  6876. */
  6877. this.toneMapping = toneMapping;
  6878. /**
  6879. * The output color space.
  6880. *
  6881. * @type {?string}
  6882. */
  6883. this.outputColorSpace = outputColorSpace;
  6884. /**
  6885. * This flag can be used for type testing.
  6886. *
  6887. * @type {boolean}
  6888. * @readonly
  6889. * @default true
  6890. */
  6891. this.isRenderOutputNode = true;
  6892. }
  6893. setup( { context } ) {
  6894. let outputNode = this.colorNode || context.color;
  6895. // tone mapping
  6896. const toneMapping = ( this.toneMapping !== null ? this.toneMapping : context.toneMapping ) || NoToneMapping;
  6897. const outputColorSpace = ( this.outputColorSpace !== null ? this.outputColorSpace : context.outputColorSpace ) || NoColorSpace;
  6898. if ( toneMapping !== NoToneMapping ) {
  6899. outputNode = outputNode.toneMapping( toneMapping );
  6900. }
  6901. // working to output color space
  6902. if ( outputColorSpace !== NoColorSpace && outputColorSpace !== ColorManagement.workingColorSpace ) {
  6903. outputNode = outputNode.workingToColorSpace( outputColorSpace );
  6904. }
  6905. return outputNode;
  6906. }
  6907. }
  6908. /**
  6909. * TSL function for creating a posterize node.
  6910. *
  6911. * @tsl
  6912. * @function
  6913. * @param {Node} color - The color node to process.
  6914. * @param {?number} [toneMapping=null] - The tone mapping type.
  6915. * @param {?string} [outputColorSpace=null] - The output color space.
  6916. * @returns {RenderOutputNode}
  6917. */
  6918. const renderOutput = ( color, toneMapping = null, outputColorSpace = null ) => nodeObject( new RenderOutputNode( nodeObject( color ), toneMapping, outputColorSpace ) );
  6919. addMethodChaining( 'renderOutput', renderOutput );
  6920. class DebugNode extends TempNode {
  6921. static get type() {
  6922. return 'DebugNode';
  6923. }
  6924. constructor( node, callback = null ) {
  6925. super();
  6926. this.node = node;
  6927. this.callback = callback;
  6928. }
  6929. getNodeType( builder ) {
  6930. return this.node.getNodeType( builder );
  6931. }
  6932. setup( builder ) {
  6933. return this.node.build( builder );
  6934. }
  6935. analyze( builder ) {
  6936. return this.node.build( builder );
  6937. }
  6938. generate( builder ) {
  6939. const callback = this.callback;
  6940. const snippet = this.node.build( builder );
  6941. const title = '--- TSL debug - ' + builder.shaderStage + ' shader ---';
  6942. const border = '-'.repeat( title.length );
  6943. let code = '';
  6944. code += '// #' + title + '#\n';
  6945. code += builder.flow.code.replace( /^\t/mg, '' ) + '\n';
  6946. code += '/* ... */ ' + snippet + ' /* ... */\n';
  6947. code += '// #' + border + '#\n';
  6948. if ( callback !== null ) {
  6949. callback( builder, code );
  6950. } else {
  6951. console.log( code );
  6952. }
  6953. return snippet;
  6954. }
  6955. }
  6956. /**
  6957. * TSL function for creating a debug node.
  6958. *
  6959. * @tsl
  6960. * @function
  6961. * @param {Node} node - The node to debug.
  6962. * @param {?Function} [callback=null] - Optional callback function to handle the debug output.
  6963. * @returns {DebugNode}
  6964. */
  6965. const debug = ( node, callback = null ) => nodeObject( new DebugNode( nodeObject( node ), callback ) );
  6966. addMethodChaining( 'debug', debug );
  6967. // Non-PURE exports list, side-effects are required here.
  6968. // TSL Base Syntax
  6969. function addNodeElement( name/*, nodeElement*/ ) {
  6970. console.warn( 'THREE.TSL: AddNodeElement has been removed in favor of tree-shaking. Trying add', name );
  6971. }
  6972. /**
  6973. * Base class for representing shader attributes as nodes.
  6974. *
  6975. * @augments Node
  6976. */
  6977. class AttributeNode extends Node {
  6978. static get type() {
  6979. return 'AttributeNode';
  6980. }
  6981. /**
  6982. * Constructs a new attribute node.
  6983. *
  6984. * @param {string} attributeName - The name of the attribute.
  6985. * @param {?string} nodeType - The node type.
  6986. */
  6987. constructor( attributeName, nodeType = null ) {
  6988. super( nodeType );
  6989. /**
  6990. * `AttributeNode` sets this property to `true` by default.
  6991. *
  6992. * @type {boolean}
  6993. * @default true
  6994. */
  6995. this.global = true;
  6996. this._attributeName = attributeName;
  6997. }
  6998. getHash( builder ) {
  6999. return this.getAttributeName( builder );
  7000. }
  7001. getNodeType( builder ) {
  7002. let nodeType = this.nodeType;
  7003. if ( nodeType === null ) {
  7004. const attributeName = this.getAttributeName( builder );
  7005. if ( builder.hasGeometryAttribute( attributeName ) ) {
  7006. const attribute = builder.geometry.getAttribute( attributeName );
  7007. nodeType = builder.getTypeFromAttribute( attribute );
  7008. } else {
  7009. nodeType = 'float';
  7010. }
  7011. }
  7012. return nodeType;
  7013. }
  7014. /**
  7015. * Sets the attribute name to the given value. The method can be
  7016. * overwritten in derived classes if the final name must be computed
  7017. * analytically.
  7018. *
  7019. * @param {string} attributeName - The name of the attribute.
  7020. * @return {AttributeNode} A reference to this node.
  7021. */
  7022. setAttributeName( attributeName ) {
  7023. this._attributeName = attributeName;
  7024. return this;
  7025. }
  7026. /**
  7027. * Returns the attribute name of this node. The method can be
  7028. * overwritten in derived classes if the final name must be computed
  7029. * analytically.
  7030. *
  7031. * @param {NodeBuilder} builder - The current node builder.
  7032. * @return {string} The attribute name.
  7033. */
  7034. getAttributeName( /*builder*/ ) {
  7035. return this._attributeName;
  7036. }
  7037. generate( builder ) {
  7038. const attributeName = this.getAttributeName( builder );
  7039. const nodeType = this.getNodeType( builder );
  7040. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  7041. if ( geometryAttribute === true ) {
  7042. const attribute = builder.geometry.getAttribute( attributeName );
  7043. const attributeType = builder.getTypeFromAttribute( attribute );
  7044. const nodeAttribute = builder.getAttribute( attributeName, attributeType );
  7045. if ( builder.shaderStage === 'vertex' ) {
  7046. return builder.format( nodeAttribute.name, attributeType, nodeType );
  7047. } else {
  7048. const nodeVarying = varying( this );
  7049. return nodeVarying.build( builder, nodeType );
  7050. }
  7051. } else {
  7052. console.warn( `AttributeNode: Vertex attribute "${ attributeName }" not found on geometry.` );
  7053. return builder.generateConst( nodeType );
  7054. }
  7055. }
  7056. serialize( data ) {
  7057. super.serialize( data );
  7058. data.global = this.global;
  7059. data._attributeName = this._attributeName;
  7060. }
  7061. deserialize( data ) {
  7062. super.deserialize( data );
  7063. this.global = data.global;
  7064. this._attributeName = data._attributeName;
  7065. }
  7066. }
  7067. /**
  7068. * TSL function for creating an attribute node.
  7069. *
  7070. * @tsl
  7071. * @function
  7072. * @param {string} name - The name of the attribute.
  7073. * @param {?string} [nodeType=null] - The node type.
  7074. * @returns {AttributeNode}
  7075. */
  7076. const attribute = ( name, nodeType = null ) => nodeObject( new AttributeNode( name, nodeType ) );
  7077. /**
  7078. * TSL function for creating an uv attribute node with the given index.
  7079. *
  7080. * @tsl
  7081. * @function
  7082. * @param {number} [index=0] - The uv index.
  7083. * @return {AttributeNode<vec2>} The uv attribute node.
  7084. */
  7085. const uv$1 = ( index = 0 ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' );
  7086. /**
  7087. * A node that represents the dimensions of a texture. The texture size is
  7088. * retrieved in the shader via built-in shader functions like `textureDimensions()`
  7089. * or `textureSize()`.
  7090. *
  7091. * @augments Node
  7092. */
  7093. class TextureSizeNode extends Node {
  7094. static get type() {
  7095. return 'TextureSizeNode';
  7096. }
  7097. /**
  7098. * Constructs a new texture size node.
  7099. *
  7100. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  7101. * @param {?Node<int>} [levelNode=null] - A level node which defines the requested mip.
  7102. */
  7103. constructor( textureNode, levelNode = null ) {
  7104. super( 'uvec2' );
  7105. /**
  7106. * This flag can be used for type testing.
  7107. *
  7108. * @type {boolean}
  7109. * @readonly
  7110. * @default true
  7111. */
  7112. this.isTextureSizeNode = true;
  7113. /**
  7114. * A texture node which size should be retrieved.
  7115. *
  7116. * @type {TextureNode}
  7117. */
  7118. this.textureNode = textureNode;
  7119. /**
  7120. * A level node which defines the requested mip.
  7121. *
  7122. * @type {Node<int>}
  7123. * @default null
  7124. */
  7125. this.levelNode = levelNode;
  7126. }
  7127. generate( builder, output ) {
  7128. const textureProperty = this.textureNode.build( builder, 'property' );
  7129. const level = this.levelNode === null ? '0' : this.levelNode.build( builder, 'int' );
  7130. return builder.format( `${ builder.getMethod( 'textureDimensions' ) }( ${ textureProperty }, ${ level } )`, this.getNodeType( builder ), output );
  7131. }
  7132. }
  7133. /**
  7134. * TSL function for creating a texture size node.
  7135. *
  7136. * @tsl
  7137. * @function
  7138. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  7139. * @param {?Node<int>} [levelNode=null] - A level node which defines the requested mip.
  7140. * @returns {TextureSizeNode}
  7141. */
  7142. const textureSize = /*@__PURE__*/ nodeProxy( TextureSizeNode ).setParameterLength( 1, 2 );
  7143. /**
  7144. * A special type of uniform node that computes the
  7145. * maximum mipmap level for a given texture node.
  7146. *
  7147. * ```js
  7148. * const level = maxMipLevel( textureNode );
  7149. * ```
  7150. *
  7151. * @augments UniformNode
  7152. */
  7153. class MaxMipLevelNode extends UniformNode {
  7154. static get type() {
  7155. return 'MaxMipLevelNode';
  7156. }
  7157. /**
  7158. * Constructs a new max mip level node.
  7159. *
  7160. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  7161. */
  7162. constructor( textureNode ) {
  7163. super( 0 );
  7164. /**
  7165. * The texture node to compute the max mip level for.
  7166. *
  7167. * @private
  7168. * @type {TextureNode}
  7169. */
  7170. this._textureNode = textureNode;
  7171. /**
  7172. * The `updateType` is set to `NodeUpdateType.FRAME` since the node updates
  7173. * the texture once per frame in its {@link MaxMipLevelNode#update} method.
  7174. *
  7175. * @type {string}
  7176. * @default 'frame'
  7177. */
  7178. this.updateType = NodeUpdateType.FRAME;
  7179. }
  7180. /**
  7181. * The texture node to compute the max mip level for.
  7182. *
  7183. * @readonly
  7184. * @type {TextureNode}
  7185. */
  7186. get textureNode() {
  7187. return this._textureNode;
  7188. }
  7189. /**
  7190. * The texture.
  7191. *
  7192. * @readonly
  7193. * @type {Texture}
  7194. */
  7195. get texture() {
  7196. return this._textureNode.value;
  7197. }
  7198. update() {
  7199. const texture = this.texture;
  7200. const images = texture.images;
  7201. const image = ( images && images.length > 0 ) ? ( ( images[ 0 ] && images[ 0 ].image ) || images[ 0 ] ) : texture.image;
  7202. if ( image && image.width !== undefined ) {
  7203. const { width, height } = image;
  7204. this.value = Math.log2( Math.max( width, height ) );
  7205. }
  7206. }
  7207. }
  7208. /**
  7209. * TSL function for creating a max mip level node.
  7210. *
  7211. * @tsl
  7212. * @function
  7213. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  7214. * @returns {MaxMipLevelNode}
  7215. */
  7216. const maxMipLevel = /*@__PURE__*/ nodeProxy( MaxMipLevelNode ).setParameterLength( 1 );
  7217. const EmptyTexture$1 = /*@__PURE__*/ new Texture();
  7218. /**
  7219. * This type of uniform node represents a 2D texture.
  7220. *
  7221. * @augments UniformNode
  7222. */
  7223. class TextureNode extends UniformNode {
  7224. static get type() {
  7225. return 'TextureNode';
  7226. }
  7227. /**
  7228. * Constructs a new texture node.
  7229. *
  7230. * @param {Texture} [value=EmptyTexture] - The texture.
  7231. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  7232. * @param {?Node<int>} [levelNode=null] - The level node.
  7233. * @param {?Node<float>} [biasNode=null] - The bias node.
  7234. */
  7235. constructor( value = EmptyTexture$1, uvNode = null, levelNode = null, biasNode = null ) {
  7236. super( value );
  7237. /**
  7238. * This flag can be used for type testing.
  7239. *
  7240. * @type {boolean}
  7241. * @readonly
  7242. * @default true
  7243. */
  7244. this.isTextureNode = true;
  7245. /**
  7246. * Represents the texture coordinates.
  7247. *
  7248. * @type {?Node<vec2|vec3>}
  7249. * @default null
  7250. */
  7251. this.uvNode = uvNode;
  7252. /**
  7253. * Represents the mip level that should be selected.
  7254. *
  7255. * @type {?Node<int>}
  7256. * @default null
  7257. */
  7258. this.levelNode = levelNode;
  7259. /**
  7260. * Represents the bias to be applied during level-of-detail computation.
  7261. *
  7262. * @type {?Node<float>}
  7263. * @default null
  7264. */
  7265. this.biasNode = biasNode;
  7266. /**
  7267. * Represents a reference value a texture sample is compared to.
  7268. *
  7269. * @type {?Node<float>}
  7270. * @default null
  7271. */
  7272. this.compareNode = null;
  7273. /**
  7274. * When using texture arrays, the depth node defines the layer to select.
  7275. *
  7276. * @type {?Node<int>}
  7277. * @default null
  7278. */
  7279. this.depthNode = null;
  7280. /**
  7281. * When defined, a texture is sampled using explicit gradients.
  7282. *
  7283. * @type {?Array<Node<vec2>>}
  7284. * @default null
  7285. */
  7286. this.gradNode = null;
  7287. /**
  7288. * Whether texture values should be sampled or fetched.
  7289. *
  7290. * @type {boolean}
  7291. * @default true
  7292. */
  7293. this.sampler = true;
  7294. /**
  7295. * Whether the uv transformation matrix should be
  7296. * automatically updated or not. Use `setUpdateMatrix()`
  7297. * if you want to change the value of the property.
  7298. *
  7299. * @type {boolean}
  7300. * @default false
  7301. */
  7302. this.updateMatrix = false;
  7303. /**
  7304. * By default the `update()` method is not executed. `setUpdateMatrix()`
  7305. * sets the value to `frame` when the uv transformation matrix should
  7306. * automatically be updated.
  7307. *
  7308. * @type {string}
  7309. * @default 'none'
  7310. */
  7311. this.updateType = NodeUpdateType.NONE;
  7312. /**
  7313. * The reference node.
  7314. *
  7315. * @type {?Node}
  7316. * @default null
  7317. */
  7318. this.referenceNode = null;
  7319. /**
  7320. * The texture value is stored in a private property.
  7321. *
  7322. * @private
  7323. * @type {Texture}
  7324. */
  7325. this._value = value;
  7326. /**
  7327. * The uniform node that represents the uv transformation matrix.
  7328. *
  7329. * @private
  7330. * @type {?UniformNode<mat3>}
  7331. */
  7332. this._matrixUniform = null;
  7333. this.setUpdateMatrix( uvNode === null );
  7334. }
  7335. set value( value ) {
  7336. if ( this.referenceNode ) {
  7337. this.referenceNode.value = value;
  7338. } else {
  7339. this._value = value;
  7340. }
  7341. }
  7342. /**
  7343. * The texture value.
  7344. *
  7345. * @type {Texture}
  7346. */
  7347. get value() {
  7348. return this.referenceNode ? this.referenceNode.value : this._value;
  7349. }
  7350. /**
  7351. * Overwritten since the uniform hash is defined by the texture's UUID.
  7352. *
  7353. * @param {NodeBuilder} builder - The current node builder.
  7354. * @return {string} The uniform hash.
  7355. */
  7356. getUniformHash( /*builder*/ ) {
  7357. return this.value.uuid;
  7358. }
  7359. /**
  7360. * Overwritten since the node type is inferred from the texture type.
  7361. *
  7362. * @param {NodeBuilder} builder - The current node builder.
  7363. * @return {string} The node type.
  7364. */
  7365. getNodeType( /*builder*/ ) {
  7366. if ( this.value.isDepthTexture === true ) return 'float';
  7367. if ( this.value.type === UnsignedIntType ) {
  7368. return 'uvec4';
  7369. } else if ( this.value.type === IntType ) {
  7370. return 'ivec4';
  7371. }
  7372. return 'vec4';
  7373. }
  7374. /**
  7375. * Overwrites the default implementation to return a fixed value `'texture'`.
  7376. *
  7377. * @param {NodeBuilder} builder - The current node builder.
  7378. * @return {string} The input type.
  7379. */
  7380. getInputType( /*builder*/ ) {
  7381. return 'texture';
  7382. }
  7383. /**
  7384. * Returns a default uvs based on the current texture's channel.
  7385. *
  7386. * @return {AttributeNode<vec2>} The default uvs.
  7387. */
  7388. getDefaultUV() {
  7389. return uv$1( this.value.channel );
  7390. }
  7391. /**
  7392. * Overwritten to always return the texture reference of the node.
  7393. *
  7394. * @param {any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  7395. * @return {Texture} The texture reference.
  7396. */
  7397. updateReference( /*state*/ ) {
  7398. return this.value;
  7399. }
  7400. /**
  7401. * Transforms the given uv node with the texture transformation matrix.
  7402. *
  7403. * @param {Node} uvNode - The uv node to transform.
  7404. * @return {Node} The transformed uv node.
  7405. */
  7406. getTransformedUV( uvNode ) {
  7407. if ( this._matrixUniform === null ) this._matrixUniform = uniform( this.value.matrix );
  7408. return this._matrixUniform.mul( vec3( uvNode, 1 ) ).xy;
  7409. }
  7410. /**
  7411. * Defines whether the uv transformation matrix should automatically be updated or not.
  7412. *
  7413. * @param {boolean} value - The update toggle.
  7414. * @return {TextureNode} A reference to this node.
  7415. */
  7416. setUpdateMatrix( value ) {
  7417. this.updateMatrix = value;
  7418. this.updateType = value ? NodeUpdateType.OBJECT : NodeUpdateType.NONE;
  7419. return this;
  7420. }
  7421. /**
  7422. * Setups the uv node. Depending on the backend as well as texture's image and type, it might be necessary
  7423. * to modify the uv node for correct sampling.
  7424. *
  7425. * @param {NodeBuilder} builder - The current node builder.
  7426. * @param {Node} uvNode - The uv node to setup.
  7427. * @return {Node} The updated uv node.
  7428. */
  7429. setupUV( builder, uvNode ) {
  7430. const texture = this.value;
  7431. if ( builder.isFlipY() && ( ( texture.image instanceof ImageBitmap && texture.flipY === true ) || texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true || texture.isDepthTexture === true ) ) {
  7432. if ( this.sampler ) {
  7433. uvNode = uvNode.flipY();
  7434. } else {
  7435. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  7436. }
  7437. }
  7438. return uvNode;
  7439. }
  7440. /**
  7441. * Setups texture node by preparing the internal nodes for code generation.
  7442. *
  7443. * @param {NodeBuilder} builder - The current node builder.
  7444. */
  7445. setup( builder ) {
  7446. const properties = builder.getNodeProperties( this );
  7447. properties.referenceNode = this.referenceNode;
  7448. //
  7449. const texture = this.value;
  7450. if ( ! texture || texture.isTexture !== true ) {
  7451. throw new Error( 'THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().' );
  7452. }
  7453. //
  7454. let uvNode = this.uvNode;
  7455. if ( ( uvNode === null || builder.context.forceUVContext === true ) && builder.context.getUV ) {
  7456. uvNode = builder.context.getUV( this, builder );
  7457. }
  7458. if ( ! uvNode ) uvNode = this.getDefaultUV();
  7459. if ( this.updateMatrix === true ) {
  7460. uvNode = this.getTransformedUV( uvNode );
  7461. }
  7462. uvNode = this.setupUV( builder, uvNode );
  7463. //
  7464. let levelNode = this.levelNode;
  7465. if ( levelNode === null && builder.context.getTextureLevel ) {
  7466. levelNode = builder.context.getTextureLevel( this );
  7467. }
  7468. //
  7469. properties.uvNode = uvNode;
  7470. properties.levelNode = levelNode;
  7471. properties.biasNode = this.biasNode;
  7472. properties.compareNode = this.compareNode;
  7473. properties.gradNode = this.gradNode;
  7474. properties.depthNode = this.depthNode;
  7475. }
  7476. /**
  7477. * Generates the uv code snippet.
  7478. *
  7479. * @param {NodeBuilder} builder - The current node builder.
  7480. * @param {Node} uvNode - The uv node to generate code for.
  7481. * @return {string} The generated code snippet.
  7482. */
  7483. generateUV( builder, uvNode ) {
  7484. return uvNode.build( builder, this.sampler === true ? 'vec2' : 'ivec2' );
  7485. }
  7486. /**
  7487. * Generates the snippet for the texture sampling.
  7488. *
  7489. * @param {NodeBuilder} builder - The current node builder.
  7490. * @param {string} textureProperty - The texture property.
  7491. * @param {string} uvSnippet - The uv snippet.
  7492. * @param {?string} levelSnippet - The level snippet.
  7493. * @param {?string} biasSnippet - The bias snippet.
  7494. * @param {?string} depthSnippet - The depth snippet.
  7495. * @param {?string} compareSnippet - The compare snippet.
  7496. * @param {?Array<string>} gradSnippet - The grad snippet.
  7497. * @return {string} The generated code snippet.
  7498. */
  7499. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet ) {
  7500. const texture = this.value;
  7501. let snippet;
  7502. if ( levelSnippet ) {
  7503. snippet = builder.generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet );
  7504. } else if ( biasSnippet ) {
  7505. snippet = builder.generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet );
  7506. } else if ( gradSnippet ) {
  7507. snippet = builder.generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet );
  7508. } else if ( compareSnippet ) {
  7509. snippet = builder.generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet );
  7510. } else if ( this.sampler === false ) {
  7511. snippet = builder.generateTextureLoad( texture, textureProperty, uvSnippet, depthSnippet );
  7512. } else {
  7513. snippet = builder.generateTexture( texture, textureProperty, uvSnippet, depthSnippet );
  7514. }
  7515. return snippet;
  7516. }
  7517. /**
  7518. * Generates the code snippet of the texture node.
  7519. *
  7520. * @param {NodeBuilder} builder - The current node builder.
  7521. * @param {string} output - The current output.
  7522. * @return {string} The generated code snippet.
  7523. */
  7524. generate( builder, output ) {
  7525. const texture = this.value;
  7526. const properties = builder.getNodeProperties( this );
  7527. const textureProperty = super.generate( builder, 'property' );
  7528. if ( /^sampler/.test( output ) ) {
  7529. return textureProperty + '_sampler';
  7530. } else if ( builder.isReference( output ) ) {
  7531. return textureProperty;
  7532. } else {
  7533. const nodeData = builder.getDataFromNode( this );
  7534. let propertyName = nodeData.propertyName;
  7535. if ( propertyName === undefined ) {
  7536. const { uvNode, levelNode, biasNode, compareNode, depthNode, gradNode } = properties;
  7537. const uvSnippet = this.generateUV( builder, uvNode );
  7538. const levelSnippet = levelNode ? levelNode.build( builder, 'float' ) : null;
  7539. const biasSnippet = biasNode ? biasNode.build( builder, 'float' ) : null;
  7540. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  7541. const compareSnippet = compareNode ? compareNode.build( builder, 'float' ) : null;
  7542. const gradSnippet = gradNode ? [ gradNode[ 0 ].build( builder, 'vec2' ), gradNode[ 1 ].build( builder, 'vec2' ) ] : null;
  7543. const nodeVar = builder.getVarFromNode( this );
  7544. propertyName = builder.getPropertyName( nodeVar );
  7545. const snippet = this.generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet );
  7546. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  7547. nodeData.snippet = snippet;
  7548. nodeData.propertyName = propertyName;
  7549. }
  7550. let snippet = propertyName;
  7551. const nodeType = this.getNodeType( builder );
  7552. if ( builder.needsToWorkingColorSpace( texture ) ) {
  7553. snippet = colorSpaceToWorking( expression( snippet, nodeType ), texture.colorSpace ).setup( builder ).build( builder, nodeType );
  7554. }
  7555. return builder.format( snippet, nodeType, output );
  7556. }
  7557. }
  7558. /**
  7559. * Sets the sampler value.
  7560. *
  7561. * @param {boolean} value - The sampler value to set.
  7562. * @return {TextureNode} A reference to this texture node.
  7563. */
  7564. setSampler( value ) {
  7565. this.sampler = value;
  7566. return this;
  7567. }
  7568. /**
  7569. * Returns the sampler value.
  7570. *
  7571. * @return {boolean} The sampler value.
  7572. */
  7573. getSampler() {
  7574. return this.sampler;
  7575. }
  7576. // @TODO: Move to TSL
  7577. /**
  7578. * @function
  7579. * @deprecated since r172. Use {@link TextureNode#sample} instead.
  7580. *
  7581. * @param {Node} uvNode - The uv node.
  7582. * @return {TextureNode} A texture node representing the texture sample.
  7583. */
  7584. uv( uvNode ) { // @deprecated, r172
  7585. console.warn( 'THREE.TextureNode: .uv() has been renamed. Use .sample() instead.' );
  7586. return this.sample( uvNode );
  7587. }
  7588. /**
  7589. * Samples the texture with the given uv node.
  7590. *
  7591. * @param {Node} uvNode - The uv node.
  7592. * @return {TextureNode} A texture node representing the texture sample.
  7593. */
  7594. sample( uvNode ) {
  7595. const textureNode = this.clone();
  7596. textureNode.uvNode = nodeObject( uvNode );
  7597. textureNode.referenceNode = this.getSelf();
  7598. return nodeObject( textureNode );
  7599. }
  7600. /**
  7601. * Samples a blurred version of the texture by defining an internal bias.
  7602. *
  7603. * @param {Node<float>} amountNode - How blurred the texture should be.
  7604. * @return {TextureNode} A texture node representing the texture sample.
  7605. */
  7606. blur( amountNode ) {
  7607. const textureNode = this.clone();
  7608. textureNode.biasNode = nodeObject( amountNode ).mul( maxMipLevel( textureNode ) );
  7609. textureNode.referenceNode = this.getSelf();
  7610. const map = textureNode.value;
  7611. if ( textureNode.generateMipmaps === false && ( map && map.generateMipmaps === false || map.minFilter === NearestFilter || map.magFilter === NearestFilter ) ) {
  7612. console.warn( 'THREE.TSL: texture().blur() requires mipmaps and sampling. Use .generateMipmaps=true and .minFilter/.magFilter=THREE.LinearFilter in the Texture.' );
  7613. textureNode.biasNode = null;
  7614. }
  7615. return nodeObject( textureNode );
  7616. }
  7617. /**
  7618. * Samples a specific mip of the texture.
  7619. *
  7620. * @param {Node<int>} levelNode - The mip level to sample.
  7621. * @return {TextureNode} A texture node representing the texture sample.
  7622. */
  7623. level( levelNode ) {
  7624. const textureNode = this.clone();
  7625. textureNode.levelNode = nodeObject( levelNode );
  7626. textureNode.referenceNode = this.getSelf();
  7627. return nodeObject( textureNode );
  7628. }
  7629. /**
  7630. * Returns the texture size of the requested level.
  7631. *
  7632. * @param {Node<int>} levelNode - The level to compute the size for.
  7633. * @return {TextureSizeNode} The texture size.
  7634. */
  7635. size( levelNode ) {
  7636. return textureSize( this, levelNode );
  7637. }
  7638. /**
  7639. * Samples the texture with the given bias.
  7640. *
  7641. * @param {Node<float>} biasNode - The bias node.
  7642. * @return {TextureNode} A texture node representing the texture sample.
  7643. */
  7644. bias( biasNode ) {
  7645. const textureNode = this.clone();
  7646. textureNode.biasNode = nodeObject( biasNode );
  7647. textureNode.referenceNode = this.getSelf();
  7648. return nodeObject( textureNode );
  7649. }
  7650. /**
  7651. * Samples the texture by executing a compare operation.
  7652. *
  7653. * @param {Node<float>} compareNode - The node that defines the compare value.
  7654. * @return {TextureNode} A texture node representing the texture sample.
  7655. */
  7656. compare( compareNode ) {
  7657. const textureNode = this.clone();
  7658. textureNode.compareNode = nodeObject( compareNode );
  7659. textureNode.referenceNode = this.getSelf();
  7660. return nodeObject( textureNode );
  7661. }
  7662. /**
  7663. * Samples the texture using an explicit gradient.
  7664. *
  7665. * @param {Node<vec2>} gradNodeX - The gradX node.
  7666. * @param {Node<vec2>} gradNodeY - The gradY node.
  7667. * @return {TextureNode} A texture node representing the texture sample.
  7668. */
  7669. grad( gradNodeX, gradNodeY ) {
  7670. const textureNode = this.clone();
  7671. textureNode.gradNode = [ nodeObject( gradNodeX ), nodeObject( gradNodeY ) ];
  7672. textureNode.referenceNode = this.getSelf();
  7673. return nodeObject( textureNode );
  7674. }
  7675. /**
  7676. * Samples the texture by defining a depth node.
  7677. *
  7678. * @param {Node<int>} depthNode - The depth node.
  7679. * @return {TextureNode} A texture node representing the texture sample.
  7680. */
  7681. depth( depthNode ) {
  7682. const textureNode = this.clone();
  7683. textureNode.depthNode = nodeObject( depthNode );
  7684. textureNode.referenceNode = this.getSelf();
  7685. return nodeObject( textureNode );
  7686. }
  7687. // --
  7688. serialize( data ) {
  7689. super.serialize( data );
  7690. data.value = this.value.toJSON( data.meta ).uuid;
  7691. data.sampler = this.sampler;
  7692. data.updateMatrix = this.updateMatrix;
  7693. data.updateType = this.updateType;
  7694. }
  7695. deserialize( data ) {
  7696. super.deserialize( data );
  7697. this.value = data.meta.textures[ data.value ];
  7698. this.sampler = data.sampler;
  7699. this.updateMatrix = data.updateMatrix;
  7700. this.updateType = data.updateType;
  7701. }
  7702. /**
  7703. * The update is used to implement the update of the uv transformation matrix.
  7704. */
  7705. update() {
  7706. const texture = this.value;
  7707. const matrixUniform = this._matrixUniform;
  7708. if ( matrixUniform !== null ) matrixUniform.value = texture.matrix;
  7709. if ( texture.matrixAutoUpdate === true ) {
  7710. texture.updateMatrix();
  7711. }
  7712. }
  7713. /**
  7714. * Clones the texture node.
  7715. *
  7716. * @return {TextureNode} The cloned texture node.
  7717. */
  7718. clone() {
  7719. const newNode = new this.constructor( this.value, this.uvNode, this.levelNode, this.biasNode );
  7720. newNode.sampler = this.sampler;
  7721. newNode.depthNode = this.depthNode;
  7722. newNode.compareNode = this.compareNode;
  7723. newNode.gradNode = this.gradNode;
  7724. return newNode;
  7725. }
  7726. }
  7727. /**
  7728. * TSL function for creating a texture node.
  7729. *
  7730. * @tsl
  7731. * @function
  7732. * @param {?Texture} value - The texture.
  7733. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  7734. * @param {?Node<int>} [levelNode=null] - The level node.
  7735. * @param {?Node<float>} [biasNode=null] - The bias node.
  7736. * @returns {TextureNode}
  7737. */
  7738. const textureBase = /*@__PURE__*/ nodeProxy( TextureNode ).setParameterLength( 1, 4 ).setName( 'texture' );
  7739. /**
  7740. * TSL function for creating a texture node or sample a texture node already existing.
  7741. *
  7742. * @tsl
  7743. * @function
  7744. * @param {?Texture|TextureNode} [value=EmptyTexture] - The texture.
  7745. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  7746. * @param {?Node<int>} [levelNode=null] - The level node.
  7747. * @param {?Node<float>} [biasNode=null] - The bias node.
  7748. * @returns {TextureNode}
  7749. */
  7750. const texture = ( value = EmptyTexture$1, uvNode = null, levelNode = null, biasNode = null ) => {
  7751. let textureNode;
  7752. if ( value && value.isTextureNode === true ) {
  7753. textureNode = nodeObject( value.clone() );
  7754. textureNode.referenceNode = value.getSelf(); // Ensure the reference is set to the original node
  7755. if ( uvNode !== null ) textureNode.uvNode = nodeObject( uvNode );
  7756. if ( levelNode !== null ) textureNode.levelNode = nodeObject( levelNode );
  7757. if ( biasNode !== null ) textureNode.biasNode = nodeObject( biasNode );
  7758. } else {
  7759. textureNode = textureBase( value, uvNode, levelNode, biasNode );
  7760. }
  7761. return textureNode;
  7762. };
  7763. /**
  7764. * TSL function for creating a uniform texture node.
  7765. *
  7766. * @tsl
  7767. * @function
  7768. * @param {?Texture} value - The texture.
  7769. * @returns {TextureNode}
  7770. */
  7771. const uniformTexture = ( value = EmptyTexture$1 ) => texture( value );
  7772. /**
  7773. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  7774. *
  7775. * @tsl
  7776. * @function
  7777. * @param {?Texture|TextureNode} [value=EmptyTexture] - The texture.
  7778. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  7779. * @param {?Node<int>} [levelNode=null] - The level node.
  7780. * @param {?Node<float>} [biasNode=null] - The bias node.
  7781. * @returns {TextureNode}
  7782. */
  7783. const textureLoad = ( ...params ) => texture( ...params ).setSampler( false );
  7784. //export const textureLevel = ( value, uv, level ) => texture( value, uv ).level( level );
  7785. /**
  7786. * Converts a texture or texture node to a sampler.
  7787. *
  7788. * @tsl
  7789. * @function
  7790. * @param {TextureNode|Texture} value - The texture or texture node to convert.
  7791. * @returns {Node}
  7792. */
  7793. const sampler = ( value ) => ( value.isNode === true ? value : texture( value ) ).convert( 'sampler' );
  7794. /**
  7795. * Converts a texture or texture node to a sampler comparison.
  7796. *
  7797. * @tsl
  7798. * @function
  7799. * @param {TextureNode|Texture} value - The texture or texture node to convert.
  7800. * @returns {Node}
  7801. */
  7802. const samplerComparison = ( value ) => ( value.isNode === true ? value : texture( value ) ).convert( 'samplerComparison' );
  7803. /**
  7804. * A special type of uniform node which represents array-like data
  7805. * as uniform buffers. The access usually happens via `element()`
  7806. * which returns an instance of {@link ArrayElementNode}. For example:
  7807. *
  7808. * ```js
  7809. * const bufferNode = buffer( array, 'mat4', count );
  7810. * const matrixNode = bufferNode.element( index ); // access a matrix from the buffer
  7811. * ```
  7812. * In general, it is recommended to use the more managed {@link UniformArrayNode}
  7813. * since it handles more input types and automatically cares about buffer paddings.
  7814. *
  7815. * @augments UniformNode
  7816. */
  7817. class BufferNode extends UniformNode {
  7818. static get type() {
  7819. return 'BufferNode';
  7820. }
  7821. /**
  7822. * Constructs a new buffer node.
  7823. *
  7824. * @param {Array<number>} value - Array-like buffer data.
  7825. * @param {string} bufferType - The data type of the buffer.
  7826. * @param {number} [bufferCount=0] - The count of buffer elements.
  7827. */
  7828. constructor( value, bufferType, bufferCount = 0 ) {
  7829. super( value, bufferType );
  7830. /**
  7831. * This flag can be used for type testing.
  7832. *
  7833. * @type {boolean}
  7834. * @readonly
  7835. * @default true
  7836. */
  7837. this.isBufferNode = true;
  7838. /**
  7839. * The data type of the buffer.
  7840. *
  7841. * @type {string}
  7842. */
  7843. this.bufferType = bufferType;
  7844. /**
  7845. * The uniform node that holds the value of the reference node.
  7846. *
  7847. * @type {number}
  7848. * @default 0
  7849. */
  7850. this.bufferCount = bufferCount;
  7851. }
  7852. /**
  7853. * The data type of the buffer elements.
  7854. *
  7855. * @param {NodeBuilder} builder - The current node builder.
  7856. * @return {string} The element type.
  7857. */
  7858. getElementType( builder ) {
  7859. return this.getNodeType( builder );
  7860. }
  7861. /**
  7862. * Overwrites the default implementation to return a fixed value `'buffer'`.
  7863. *
  7864. * @param {NodeBuilder} builder - The current node builder.
  7865. * @return {string} The input type.
  7866. */
  7867. getInputType( /*builder*/ ) {
  7868. return 'buffer';
  7869. }
  7870. }
  7871. /**
  7872. * TSL function for creating a buffer node.
  7873. *
  7874. * @tsl
  7875. * @function
  7876. * @param {Array} value - Array-like buffer data.
  7877. * @param {string} type - The data type of a buffer element.
  7878. * @param {number} count - The count of buffer elements.
  7879. * @returns {BufferNode}
  7880. */
  7881. const buffer = ( value, type, count ) => nodeObject( new BufferNode( value, type, count ) );
  7882. /**
  7883. * Represents the element access on uniform array nodes.
  7884. *
  7885. * @augments ArrayElementNode
  7886. */
  7887. class UniformArrayElementNode extends ArrayElementNode {
  7888. static get type() {
  7889. return 'UniformArrayElementNode';
  7890. }
  7891. /**
  7892. * Constructs a new buffer node.
  7893. *
  7894. * @param {UniformArrayNode} uniformArrayNode - The uniform array node to access.
  7895. * @param {IndexNode} indexNode - The index data that define the position of the accessed element in the array.
  7896. */
  7897. constructor( uniformArrayNode, indexNode ) {
  7898. super( uniformArrayNode, indexNode );
  7899. /**
  7900. * This flag can be used for type testing.
  7901. *
  7902. * @type {boolean}
  7903. * @readonly
  7904. * @default true
  7905. */
  7906. this.isArrayBufferElementNode = true;
  7907. }
  7908. generate( builder ) {
  7909. const snippet = super.generate( builder );
  7910. const type = this.getNodeType();
  7911. const paddedType = this.node.getPaddedType();
  7912. return builder.format( snippet, paddedType, type );
  7913. }
  7914. }
  7915. /**
  7916. * Similar to {@link BufferNode} this module represents array-like data as
  7917. * uniform buffers. Unlike {@link BufferNode}, it can handle more common
  7918. * data types in the array (e.g `three.js` primitives) and automatically
  7919. * manage buffer padding. It should be the first choice when working with
  7920. * uniforms buffers.
  7921. * ```js
  7922. * const tintColors = uniformArray( [
  7923. * new Color( 1, 0, 0 ),
  7924. * new Color( 0, 1, 0 ),
  7925. * new Color( 0, 0, 1 )
  7926. * ], 'color' );
  7927. *
  7928. * const redColor = tintColors.element( 0 );
  7929. *
  7930. * @augments BufferNode
  7931. */
  7932. class UniformArrayNode extends BufferNode {
  7933. static get type() {
  7934. return 'UniformArrayNode';
  7935. }
  7936. /**
  7937. * Constructs a new uniform array node.
  7938. *
  7939. * @param {Array<any>} value - Array holding the buffer data.
  7940. * @param {?string} [elementType=null] - The data type of a buffer element.
  7941. */
  7942. constructor( value, elementType = null ) {
  7943. super( null );
  7944. /**
  7945. * Array holding the buffer data. Unlike {@link BufferNode}, the array can
  7946. * hold number primitives as well as three.js objects like vectors, matrices
  7947. * or colors.
  7948. *
  7949. * @type {Array<any>}
  7950. */
  7951. this.array = value;
  7952. /**
  7953. * The data type of an array element.
  7954. *
  7955. * @type {string}
  7956. */
  7957. this.elementType = elementType === null ? getValueType( value[ 0 ] ) : elementType;
  7958. /**
  7959. * The padded type. Uniform buffers must conform to a certain buffer layout
  7960. * so a separate type is computed to ensure correct buffer size.
  7961. *
  7962. * @type {string}
  7963. */
  7964. this.paddedType = this.getPaddedType();
  7965. /**
  7966. * Overwritten since uniform array nodes are updated per render.
  7967. *
  7968. * @type {string}
  7969. * @default 'render'
  7970. */
  7971. this.updateType = NodeUpdateType.RENDER;
  7972. /**
  7973. * This flag can be used for type testing.
  7974. *
  7975. * @type {boolean}
  7976. * @readonly
  7977. * @default true
  7978. */
  7979. this.isArrayBufferNode = true;
  7980. }
  7981. /**
  7982. * This method is overwritten since the node type is inferred from the
  7983. * {@link UniformArrayNode#paddedType}.
  7984. *
  7985. * @param {NodeBuilder} builder - The current node builder.
  7986. * @return {string} The node type.
  7987. */
  7988. getNodeType( /*builder*/ ) {
  7989. return this.paddedType;
  7990. }
  7991. /**
  7992. * The data type of the array elements.
  7993. *
  7994. * @param {NodeBuilder} builder - The current node builder.
  7995. * @return {string} The element type.
  7996. */
  7997. getElementType() {
  7998. return this.elementType;
  7999. }
  8000. /**
  8001. * Returns the padded type based on the element type.
  8002. *
  8003. * @return {string} The padded type.
  8004. */
  8005. getPaddedType() {
  8006. const elementType = this.elementType;
  8007. let paddedType = 'vec4';
  8008. if ( elementType === 'mat2' ) {
  8009. paddedType = 'mat2';
  8010. } else if ( /mat/.test( elementType ) === true ) {
  8011. paddedType = 'mat4';
  8012. } else if ( elementType.charAt( 0 ) === 'i' ) {
  8013. paddedType = 'ivec4';
  8014. } else if ( elementType.charAt( 0 ) === 'u' ) {
  8015. paddedType = 'uvec4';
  8016. }
  8017. return paddedType;
  8018. }
  8019. /**
  8020. * The update makes sure to correctly transfer the data from the (complex) objects
  8021. * in the array to the internal, correctly padded value buffer.
  8022. *
  8023. * @param {NodeFrame} frame - A reference to the current node frame.
  8024. */
  8025. update( /*frame*/ ) {
  8026. const { array, value } = this;
  8027. const elementType = this.elementType;
  8028. if ( elementType === 'float' || elementType === 'int' || elementType === 'uint' ) {
  8029. for ( let i = 0; i < array.length; i ++ ) {
  8030. const index = i * 4;
  8031. value[ index ] = array[ i ];
  8032. }
  8033. } else if ( elementType === 'color' ) {
  8034. for ( let i = 0; i < array.length; i ++ ) {
  8035. const index = i * 4;
  8036. const vector = array[ i ];
  8037. value[ index ] = vector.r;
  8038. value[ index + 1 ] = vector.g;
  8039. value[ index + 2 ] = vector.b || 0;
  8040. //value[ index + 3 ] = vector.a || 0;
  8041. }
  8042. } else if ( elementType === 'mat2' ) {
  8043. for ( let i = 0; i < array.length; i ++ ) {
  8044. const index = i * 4;
  8045. const matrix = array[ i ];
  8046. value[ index ] = matrix.elements[ 0 ];
  8047. value[ index + 1 ] = matrix.elements[ 1 ];
  8048. value[ index + 2 ] = matrix.elements[ 2 ];
  8049. value[ index + 3 ] = matrix.elements[ 3 ];
  8050. }
  8051. } else if ( elementType === 'mat3' ) {
  8052. for ( let i = 0; i < array.length; i ++ ) {
  8053. const index = i * 16;
  8054. const matrix = array[ i ];
  8055. value[ index ] = matrix.elements[ 0 ];
  8056. value[ index + 1 ] = matrix.elements[ 1 ];
  8057. value[ index + 2 ] = matrix.elements[ 2 ];
  8058. value[ index + 4 ] = matrix.elements[ 3 ];
  8059. value[ index + 5 ] = matrix.elements[ 4 ];
  8060. value[ index + 6 ] = matrix.elements[ 5 ];
  8061. value[ index + 8 ] = matrix.elements[ 6 ];
  8062. value[ index + 9 ] = matrix.elements[ 7 ];
  8063. value[ index + 10 ] = matrix.elements[ 8 ];
  8064. value[ index + 15 ] = 1;
  8065. }
  8066. } else if ( elementType === 'mat4' ) {
  8067. for ( let i = 0; i < array.length; i ++ ) {
  8068. const index = i * 16;
  8069. const matrix = array[ i ];
  8070. for ( let i = 0; i < matrix.elements.length; i ++ ) {
  8071. value[ index + i ] = matrix.elements[ i ];
  8072. }
  8073. }
  8074. } else {
  8075. for ( let i = 0; i < array.length; i ++ ) {
  8076. const index = i * 4;
  8077. const vector = array[ i ];
  8078. value[ index ] = vector.x;
  8079. value[ index + 1 ] = vector.y;
  8080. value[ index + 2 ] = vector.z || 0;
  8081. value[ index + 3 ] = vector.w || 0;
  8082. }
  8083. }
  8084. }
  8085. /**
  8086. * Implement the value buffer creation based on the array data.
  8087. *
  8088. * @param {NodeBuilder} builder - A reference to the current node builder.
  8089. * @return {null}
  8090. */
  8091. setup( builder ) {
  8092. const length = this.array.length;
  8093. const elementType = this.elementType;
  8094. let arrayType = Float32Array;
  8095. const paddedType = this.paddedType;
  8096. const paddedElementLength = builder.getTypeLength( paddedType );
  8097. if ( elementType.charAt( 0 ) === 'i' ) arrayType = Int32Array;
  8098. if ( elementType.charAt( 0 ) === 'u' ) arrayType = Uint32Array;
  8099. this.value = new arrayType( length * paddedElementLength );
  8100. this.bufferCount = length;
  8101. this.bufferType = paddedType;
  8102. return super.setup( builder );
  8103. }
  8104. /**
  8105. * Overwrites the default `element()` method to provide element access
  8106. * based on {@link UniformArrayNode}.
  8107. *
  8108. * @param {IndexNode} indexNode - The index node.
  8109. * @return {UniformArrayElementNode}
  8110. */
  8111. element( indexNode ) {
  8112. return nodeObject( new UniformArrayElementNode( this, nodeObject( indexNode ) ) );
  8113. }
  8114. }
  8115. /**
  8116. * TSL function for creating an uniform array node.
  8117. *
  8118. * @tsl
  8119. * @function
  8120. * @param {Array<any>} values - Array-like data.
  8121. * @param {?string} [nodeType] - The data type of the array elements.
  8122. * @returns {UniformArrayNode}
  8123. */
  8124. const uniformArray = ( values, nodeType ) => nodeObject( new UniformArrayNode( values, nodeType ) );
  8125. /**
  8126. * The node allows to set values for built-in shader variables. That is
  8127. * required for features like hardware-accelerated vertex clipping.
  8128. *
  8129. * @augments Node
  8130. */
  8131. class BuiltinNode extends Node {
  8132. /**
  8133. * Constructs a new builtin node.
  8134. *
  8135. * @param {string} name - The name of the built-in shader variable.
  8136. */
  8137. constructor( name ) {
  8138. super( 'float' );
  8139. /**
  8140. * The name of the built-in shader variable.
  8141. *
  8142. * @type {string}
  8143. */
  8144. this.name = name;
  8145. /**
  8146. * This flag can be used for type testing.
  8147. *
  8148. * @type {boolean}
  8149. * @readonly
  8150. * @default true
  8151. */
  8152. this.isBuiltinNode = true;
  8153. }
  8154. /**
  8155. * Generates the code snippet of the builtin node.
  8156. *
  8157. * @param {NodeBuilder} builder - The current node builder.
  8158. * @return {string} The generated code snippet.
  8159. */
  8160. generate( /* builder */ ) {
  8161. return this.name;
  8162. }
  8163. }
  8164. /**
  8165. * TSL function for creating a builtin node.
  8166. *
  8167. * @tsl
  8168. * @function
  8169. * @param {string} name - The name of the built-in shader variable.
  8170. * @returns {BuiltinNode}
  8171. */
  8172. const builtin = nodeProxy( BuiltinNode ).setParameterLength( 1 );
  8173. /**
  8174. * TSL object that represents the current `index` value of the camera if used ArrayCamera.
  8175. *
  8176. * @tsl
  8177. * @type {UniformNode<uint>}
  8178. */
  8179. const cameraIndex = /*@__PURE__*/ uniform( 0, 'uint' ).label( 'u_cameraIndex' ).setGroup( sharedUniformGroup( 'cameraIndex' ) ).toVarying( 'v_cameraIndex' );
  8180. /**
  8181. * TSL object that represents the `near` value of the camera used for the current render.
  8182. *
  8183. * @tsl
  8184. * @type {UniformNode<float>}
  8185. */
  8186. const cameraNear = /*@__PURE__*/ uniform( 'float' ).label( 'cameraNear' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.near );
  8187. /**
  8188. * TSL object that represents the `far` value of the camera used for the current render.
  8189. *
  8190. * @tsl
  8191. * @type {UniformNode<float>}
  8192. */
  8193. const cameraFar = /*@__PURE__*/ uniform( 'float' ).label( 'cameraFar' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.far );
  8194. /**
  8195. * TSL object that represents the projection matrix of the camera used for the current render.
  8196. *
  8197. * @tsl
  8198. * @type {UniformNode<mat4>}
  8199. */
  8200. const cameraProjectionMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  8201. let cameraProjectionMatrix;
  8202. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  8203. const matrices = [];
  8204. for ( const subCamera of camera.cameras ) {
  8205. matrices.push( subCamera.projectionMatrix );
  8206. }
  8207. const cameraProjectionMatrices = uniformArray( matrices ).setGroup( renderGroup ).label( 'cameraProjectionMatrices' );
  8208. cameraProjectionMatrix = cameraProjectionMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toVar( 'cameraProjectionMatrix' );
  8209. } else {
  8210. cameraProjectionMatrix = uniform( 'mat4' ).label( 'cameraProjectionMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrix );
  8211. }
  8212. return cameraProjectionMatrix;
  8213. } ).once() )();
  8214. /**
  8215. * TSL object that represents the inverse projection matrix of the camera used for the current render.
  8216. *
  8217. * @tsl
  8218. * @type {UniformNode<mat4>}
  8219. */
  8220. const cameraProjectionMatrixInverse = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  8221. let cameraProjectionMatrixInverse;
  8222. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  8223. const matrices = [];
  8224. for ( const subCamera of camera.cameras ) {
  8225. matrices.push( subCamera.projectionMatrixInverse );
  8226. }
  8227. const cameraProjectionMatricesInverse = uniformArray( matrices ).setGroup( renderGroup ).label( 'cameraProjectionMatricesInverse' );
  8228. cameraProjectionMatrixInverse = cameraProjectionMatricesInverse.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toVar( 'cameraProjectionMatrixInverse' );
  8229. } else {
  8230. cameraProjectionMatrixInverse = uniform( 'mat4' ).label( 'cameraProjectionMatrixInverse' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrixInverse );
  8231. }
  8232. return cameraProjectionMatrixInverse;
  8233. } ).once() )();
  8234. /**
  8235. * TSL object that represents the view matrix of the camera used for the current render.
  8236. *
  8237. * @tsl
  8238. * @type {UniformNode<mat4>}
  8239. */
  8240. const cameraViewMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  8241. let cameraViewMatrix;
  8242. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  8243. const matrices = [];
  8244. for ( const subCamera of camera.cameras ) {
  8245. matrices.push( subCamera.matrixWorldInverse );
  8246. }
  8247. const cameraViewMatrices = uniformArray( matrices ).setGroup( renderGroup ).label( 'cameraViewMatrices' );
  8248. cameraViewMatrix = cameraViewMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toVar( 'cameraViewMatrix' );
  8249. } else {
  8250. cameraViewMatrix = uniform( 'mat4' ).label( 'cameraViewMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorldInverse );
  8251. }
  8252. return cameraViewMatrix;
  8253. } ).once() )();
  8254. /**
  8255. * TSL object that represents the world matrix of the camera used for the current render.
  8256. *
  8257. * @tsl
  8258. * @type {UniformNode<mat4>}
  8259. */
  8260. const cameraWorldMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraWorldMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorld );
  8261. /**
  8262. * TSL object that represents the normal matrix of the camera used for the current render.
  8263. *
  8264. * @tsl
  8265. * @type {UniformNode<mat3>}
  8266. */
  8267. const cameraNormalMatrix = /*@__PURE__*/ uniform( 'mat3' ).label( 'cameraNormalMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.normalMatrix );
  8268. /**
  8269. * TSL object that represents the position in world space of the camera used for the current render.
  8270. *
  8271. * @tsl
  8272. * @type {UniformNode<vec3>}
  8273. */
  8274. const cameraPosition = /*@__PURE__*/ uniform( new Vector3() ).label( 'cameraPosition' ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => self.value.setFromMatrixPosition( camera.matrixWorld ) );
  8275. const _sphere = /*@__PURE__*/ new Sphere();
  8276. /**
  8277. * This node can be used to access transformation related metrics of 3D objects.
  8278. * Depending on the selected scope, a different metric is represented as a uniform
  8279. * in the shader. The following scopes are supported:
  8280. *
  8281. * - `POSITION`: The object's position in world space.
  8282. * - `VIEW_POSITION`: The object's position in view/camera space.
  8283. * - `DIRECTION`: The object's direction in world space.
  8284. * - `SCALE`: The object's scale in world space.
  8285. * - `WORLD_MATRIX`: The object's matrix in world space.
  8286. *
  8287. * @augments Node
  8288. */
  8289. class Object3DNode extends Node {
  8290. static get type() {
  8291. return 'Object3DNode';
  8292. }
  8293. /**
  8294. * Constructs a new object 3D node.
  8295. *
  8296. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  8297. * @param {?Object3D} [object3d=null] - The 3D object.
  8298. */
  8299. constructor( scope, object3d = null ) {
  8300. super();
  8301. /**
  8302. * The node reports a different type of transformation depending on the scope.
  8303. *
  8304. * @type {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')}
  8305. */
  8306. this.scope = scope;
  8307. /**
  8308. * The 3D object.
  8309. *
  8310. * @type {?Object3D}
  8311. * @default null
  8312. */
  8313. this.object3d = object3d;
  8314. /**
  8315. * Overwritten since this type of node is updated per object.
  8316. *
  8317. * @type {string}
  8318. * @default 'object'
  8319. */
  8320. this.updateType = NodeUpdateType.OBJECT;
  8321. /**
  8322. * Holds the value of the node as a uniform.
  8323. *
  8324. * @type {UniformNode}
  8325. */
  8326. this.uniformNode = new UniformNode( null );
  8327. }
  8328. /**
  8329. * Overwritten since the node type is inferred from the scope.
  8330. *
  8331. * @return {string} The node type.
  8332. */
  8333. getNodeType() {
  8334. const scope = this.scope;
  8335. if ( scope === Object3DNode.WORLD_MATRIX ) {
  8336. return 'mat4';
  8337. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  8338. return 'vec3';
  8339. } else if ( scope === Object3DNode.RADIUS ) {
  8340. return 'float';
  8341. }
  8342. }
  8343. /**
  8344. * Updates the uniform value depending on the scope.
  8345. *
  8346. * @param {NodeFrame} frame - The current node frame.
  8347. */
  8348. update( frame ) {
  8349. const object = this.object3d;
  8350. const uniformNode = this.uniformNode;
  8351. const scope = this.scope;
  8352. if ( scope === Object3DNode.WORLD_MATRIX ) {
  8353. uniformNode.value = object.matrixWorld;
  8354. } else if ( scope === Object3DNode.POSITION ) {
  8355. uniformNode.value = uniformNode.value || new Vector3();
  8356. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  8357. } else if ( scope === Object3DNode.SCALE ) {
  8358. uniformNode.value = uniformNode.value || new Vector3();
  8359. uniformNode.value.setFromMatrixScale( object.matrixWorld );
  8360. } else if ( scope === Object3DNode.DIRECTION ) {
  8361. uniformNode.value = uniformNode.value || new Vector3();
  8362. object.getWorldDirection( uniformNode.value );
  8363. } else if ( scope === Object3DNode.VIEW_POSITION ) {
  8364. const camera = frame.camera;
  8365. uniformNode.value = uniformNode.value || new Vector3();
  8366. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  8367. uniformNode.value.applyMatrix4( camera.matrixWorldInverse );
  8368. } else if ( scope === Object3DNode.RADIUS ) {
  8369. const geometry = frame.object.geometry;
  8370. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  8371. _sphere.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  8372. uniformNode.value = _sphere.radius;
  8373. }
  8374. }
  8375. /**
  8376. * Generates the code snippet of the uniform node. The node type of the uniform
  8377. * node also depends on the selected scope.
  8378. *
  8379. * @param {NodeBuilder} builder - The current node builder.
  8380. * @return {string} The generated code snippet.
  8381. */
  8382. generate( builder ) {
  8383. const scope = this.scope;
  8384. if ( scope === Object3DNode.WORLD_MATRIX ) {
  8385. this.uniformNode.nodeType = 'mat4';
  8386. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  8387. this.uniformNode.nodeType = 'vec3';
  8388. } else if ( scope === Object3DNode.RADIUS ) {
  8389. this.uniformNode.nodeType = 'float';
  8390. }
  8391. return this.uniformNode.build( builder );
  8392. }
  8393. serialize( data ) {
  8394. super.serialize( data );
  8395. data.scope = this.scope;
  8396. }
  8397. deserialize( data ) {
  8398. super.deserialize( data );
  8399. this.scope = data.scope;
  8400. }
  8401. }
  8402. Object3DNode.WORLD_MATRIX = 'worldMatrix';
  8403. Object3DNode.POSITION = 'position';
  8404. Object3DNode.SCALE = 'scale';
  8405. Object3DNode.VIEW_POSITION = 'viewPosition';
  8406. Object3DNode.DIRECTION = 'direction';
  8407. Object3DNode.RADIUS = 'radius';
  8408. /**
  8409. * TSL function for creating an object 3D node that represents the object's direction in world space.
  8410. *
  8411. * @tsl
  8412. * @function
  8413. * @param {?Object3D} [object3d] - The 3D object.
  8414. * @returns {Object3DNode<vec3>}
  8415. */
  8416. const objectDirection = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.DIRECTION ).setParameterLength( 1 );
  8417. /**
  8418. * TSL function for creating an object 3D node that represents the object's world matrix.
  8419. *
  8420. * @tsl
  8421. * @function
  8422. * @param {?Object3D} [object3d] - The 3D object.
  8423. * @returns {Object3DNode<mat4>}
  8424. */
  8425. const objectWorldMatrix = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX ).setParameterLength( 1 );
  8426. /**
  8427. * TSL function for creating an object 3D node that represents the object's position in world space.
  8428. *
  8429. * @tsl
  8430. * @function
  8431. * @param {?Object3D} [object3d] - The 3D object.
  8432. * @returns {Object3DNode<vec3>}
  8433. */
  8434. const objectPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.POSITION ).setParameterLength( 1 );
  8435. /**
  8436. * TSL function for creating an object 3D node that represents the object's scale in world space.
  8437. *
  8438. * @tsl
  8439. * @function
  8440. * @param {?Object3D} [object3d] - The 3D object.
  8441. * @returns {Object3DNode<vec3>}
  8442. */
  8443. const objectScale = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.SCALE ).setParameterLength( 1 );
  8444. /**
  8445. * TSL function for creating an object 3D node that represents the object's position in view/camera space.
  8446. *
  8447. * @tsl
  8448. * @function
  8449. * @param {?Object3D} [object3d] - The 3D object.
  8450. * @returns {Object3DNode<vec3>}
  8451. */
  8452. const objectViewPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION ).setParameterLength( 1 );
  8453. /**
  8454. * TSL function for creating an object 3D node that represents the object's radius.
  8455. *
  8456. * @tsl
  8457. * @function
  8458. * @param {?Object3D} [object3d] - The 3D object.
  8459. * @returns {Object3DNode<float>}
  8460. */
  8461. const objectRadius = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.RADIUS ).setParameterLength( 1 );
  8462. /**
  8463. * This type of node is a specialized version of `Object3DNode`
  8464. * with larger set of model related metrics. Unlike `Object3DNode`,
  8465. * `ModelNode` extracts the reference to the 3D object from the
  8466. * current node frame state.
  8467. *
  8468. * @augments Object3DNode
  8469. */
  8470. class ModelNode extends Object3DNode {
  8471. static get type() {
  8472. return 'ModelNode';
  8473. }
  8474. /**
  8475. * Constructs a new object model node.
  8476. *
  8477. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  8478. */
  8479. constructor( scope ) {
  8480. super( scope );
  8481. }
  8482. /**
  8483. * Extracts the model reference from the frame state and then
  8484. * updates the uniform value depending on the scope.
  8485. *
  8486. * @param {NodeFrame} frame - The current node frame.
  8487. */
  8488. update( frame ) {
  8489. this.object3d = frame.object;
  8490. super.update( frame );
  8491. }
  8492. }
  8493. /**
  8494. * TSL object that represents the object's direction in world space.
  8495. *
  8496. * @tsl
  8497. * @type {ModelNode<vec3>}
  8498. */
  8499. const modelDirection = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.DIRECTION );
  8500. /**
  8501. * TSL object that represents the object's world matrix.
  8502. *
  8503. * @tsl
  8504. * @type {ModelNode<mat4>}
  8505. */
  8506. const modelWorldMatrix = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX );
  8507. /**
  8508. * TSL object that represents the object's position in world space.
  8509. *
  8510. * @tsl
  8511. * @type {ModelNode<vec3>}
  8512. */
  8513. const modelPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.POSITION );
  8514. /**
  8515. * TSL object that represents the object's scale in world space.
  8516. *
  8517. * @tsl
  8518. * @type {ModelNode<vec3>}
  8519. */
  8520. const modelScale = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.SCALE );
  8521. /**
  8522. * TSL object that represents the object's position in view/camera space.
  8523. *
  8524. * @tsl
  8525. * @type {ModelNode<vec3>}
  8526. */
  8527. const modelViewPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.VIEW_POSITION );
  8528. /**
  8529. * TSL object that represents the object's radius.
  8530. *
  8531. * @tsl
  8532. * @type {ModelNode<float>}
  8533. */
  8534. const modelRadius = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.RADIUS );
  8535. /**
  8536. * TSL object that represents the object's normal matrix.
  8537. *
  8538. * @tsl
  8539. * @type {UniformNode<mat3>}
  8540. */
  8541. const modelNormalMatrix = /*@__PURE__*/ uniform( new Matrix3() ).onObjectUpdate( ( { object }, self ) => self.value.getNormalMatrix( object.matrixWorld ) );
  8542. /**
  8543. * TSL object that represents the object's inverse world matrix.
  8544. *
  8545. * @tsl
  8546. * @type {UniformNode<mat4>}
  8547. */
  8548. const modelWorldMatrixInverse = /*@__PURE__*/ uniform( new Matrix4() ).onObjectUpdate( ( { object }, self ) => self.value.copy( object.matrixWorld ).invert() );
  8549. /**
  8550. * TSL object that represents the object's model view matrix.
  8551. *
  8552. * @tsl
  8553. * @type {Node<mat4>}
  8554. */
  8555. const modelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  8556. return builder.renderer.overrideNodes.modelViewMatrix || mediumpModelViewMatrix;
  8557. } ).once() )().toVar( 'modelViewMatrix' );
  8558. // GPU Precision
  8559. /**
  8560. * TSL object that represents the object's model view in `mediump` precision.
  8561. *
  8562. * @tsl
  8563. * @type {Node<mat4>}
  8564. */
  8565. const mediumpModelViewMatrix = /*@__PURE__*/ cameraViewMatrix.mul( modelWorldMatrix );
  8566. // CPU Precision
  8567. /**
  8568. * TSL object that represents the object's model view in `highp` precision
  8569. * which is achieved by computing the matrix in JS and not in the shader.
  8570. *
  8571. * @tsl
  8572. * @type {Node<mat4>}
  8573. */
  8574. const highpModelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  8575. builder.context.isHighPrecisionModelViewMatrix = true;
  8576. return uniform( 'mat4' ).onObjectUpdate( ( { object, camera } ) => {
  8577. return object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  8578. } );
  8579. } ).once() )().toVar( 'highpModelViewMatrix' );
  8580. /**
  8581. * TSL object that represents the object's model normal view in `highp` precision
  8582. * which is achieved by computing the matrix in JS and not in the shader.
  8583. *
  8584. * @tsl
  8585. * @type {Node<mat3>}
  8586. */
  8587. const highpModelNormalViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  8588. const isHighPrecisionModelViewMatrix = builder.context.isHighPrecisionModelViewMatrix;
  8589. return uniform( 'mat3' ).onObjectUpdate( ( { object, camera } ) => {
  8590. if ( isHighPrecisionModelViewMatrix !== true ) {
  8591. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  8592. }
  8593. return object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  8594. } );
  8595. } ).once() )().toVar( 'highpModelNormalViewMatrix' );
  8596. /**
  8597. * TSL object that represents the position attribute of the current rendered object.
  8598. *
  8599. * @tsl
  8600. * @type {AttributeNode<vec3>}
  8601. */
  8602. const positionGeometry = /*@__PURE__*/ attribute( 'position', 'vec3' );
  8603. /**
  8604. * TSL object that represents the vertex position in local space of the current rendered object.
  8605. *
  8606. * @tsl
  8607. * @type {AttributeNode<vec3>}
  8608. */
  8609. const positionLocal = /*@__PURE__*/ positionGeometry.toVarying( 'positionLocal' );
  8610. /**
  8611. * TSL object that represents the previous vertex position in local space of the current rendered object.
  8612. * Used in context of {@link VelocityNode} for rendering motion vectors.
  8613. *
  8614. * @tsl
  8615. * @type {AttributeNode<vec3>}
  8616. */
  8617. const positionPrevious = /*@__PURE__*/ positionGeometry.toVarying( 'positionPrevious' );
  8618. /**
  8619. * TSL object that represents the vertex position in world space of the current rendered object.
  8620. *
  8621. * @tsl
  8622. * @type {VaryingNode<vec3>}
  8623. */
  8624. const positionWorld = /*@__PURE__*/ ( Fn( ( builder ) => {
  8625. return modelWorldMatrix.mul( positionLocal ).xyz.toVarying( builder.getSubBuildProperty( 'v_positionWorld' ) );
  8626. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  8627. /**
  8628. * TSL object that represents the position world direction of the current rendered object.
  8629. *
  8630. * @tsl
  8631. * @type {Node<vec3>}
  8632. */
  8633. const positionWorldDirection = /*@__PURE__*/ ( Fn( () => {
  8634. const vertexPWD = positionLocal.transformDirection( modelWorldMatrix ).toVarying( 'v_positionWorldDirection' );
  8635. return vertexPWD.normalize().toVar( 'positionWorldDirection' );
  8636. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  8637. /**
  8638. * TSL object that represents the vertex position in view space of the current rendered object.
  8639. *
  8640. * @tsl
  8641. * @type {VaryingNode<vec3>}
  8642. */
  8643. const positionView = /*@__PURE__*/ ( Fn( ( builder ) => {
  8644. return builder.context.setupPositionView().toVarying( 'v_positionView' );
  8645. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  8646. /**
  8647. * TSL object that represents the position view direction of the current rendered object.
  8648. *
  8649. * @tsl
  8650. * @type {VaryingNode<vec3>}
  8651. */
  8652. const positionViewDirection = /*@__PURE__*/ positionView.negate().toVarying( 'v_positionViewDirection' ).normalize().toVar( 'positionViewDirection' );
  8653. /**
  8654. * This node can be used to evaluate whether a primitive is front or back facing.
  8655. *
  8656. * @augments Node
  8657. */
  8658. class FrontFacingNode extends Node {
  8659. static get type() {
  8660. return 'FrontFacingNode';
  8661. }
  8662. /**
  8663. * Constructs a new front facing node.
  8664. */
  8665. constructor() {
  8666. super( 'bool' );
  8667. /**
  8668. * This flag can be used for type testing.
  8669. *
  8670. * @type {boolean}
  8671. * @readonly
  8672. * @default true
  8673. */
  8674. this.isFrontFacingNode = true;
  8675. }
  8676. generate( builder ) {
  8677. if ( builder.shaderStage !== 'fragment' ) return 'true';
  8678. //
  8679. const { renderer, material } = builder;
  8680. if ( renderer.coordinateSystem === WebGLCoordinateSystem ) {
  8681. if ( material.side === BackSide ) {
  8682. return 'false';
  8683. }
  8684. }
  8685. return builder.getFrontFacing();
  8686. }
  8687. }
  8688. /**
  8689. * TSL object that represents whether a primitive is front or back facing
  8690. *
  8691. * @tsl
  8692. * @type {FrontFacingNode<bool>}
  8693. */
  8694. const frontFacing = /*@__PURE__*/ nodeImmutable( FrontFacingNode );
  8695. /**
  8696. * TSL object that represents the front facing status as a number instead of a bool.
  8697. * `1` means front facing, `-1` means back facing.
  8698. *
  8699. * @tsl
  8700. * @type {Node<float>}
  8701. */
  8702. const faceDirection = /*@__PURE__*/ float( frontFacing ).mul( 2.0 ).sub( 1.0 );
  8703. /**
  8704. * Converts a direction vector to a face direction vector based on the material's side.
  8705. *
  8706. * If the material is set to `BackSide`, the direction is inverted.
  8707. * If the material is set to `DoubleSide`, the direction is multiplied by `faceDirection`.
  8708. *
  8709. * @tsl
  8710. * @param {Node<vec3>} direction - The direction vector to convert.
  8711. * @returns {Node<vec3>} The converted direction vector.
  8712. */
  8713. const directionToFaceDirection = /*@__PURE__*/ Fn( ( [ direction ], { material } ) => {
  8714. const side = material.side;
  8715. if ( side === BackSide ) {
  8716. direction = direction.mul( -1 );
  8717. } else if ( side === DoubleSide ) {
  8718. direction = direction.mul( faceDirection );
  8719. }
  8720. return direction;
  8721. } );
  8722. /**
  8723. * TSL object that represents the normal attribute of the current rendered object in local space.
  8724. *
  8725. * @tsl
  8726. * @type {Node<vec3>}
  8727. */
  8728. const normalGeometry = /*@__PURE__*/ attribute( 'normal', 'vec3' );
  8729. /**
  8730. * TSL object that represents the vertex normal of the current rendered object in local space.
  8731. *
  8732. * @tsl
  8733. * @type {Node<vec3>}
  8734. */
  8735. const normalLocal = /*@__PURE__*/ ( Fn( ( builder ) => {
  8736. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  8737. console.warn( 'THREE.TSL: Vertex attribute "normal" not found on geometry.' );
  8738. return vec3( 0, 1, 0 );
  8739. }
  8740. return normalGeometry;
  8741. }, 'vec3' ).once() )().toVar( 'normalLocal' );
  8742. /**
  8743. * TSL object that represents the flat vertex normal of the current rendered object in view space.
  8744. *
  8745. * @tsl
  8746. * @type {Node<vec3>}
  8747. */
  8748. const normalFlat = /*@__PURE__*/ positionView.dFdx().cross( positionView.dFdy() ).normalize().toVar( 'normalFlat' );
  8749. /**
  8750. * TSL object that represents the vertex normal of the current rendered object in view space.
  8751. *
  8752. * @tsl
  8753. * @type {Node<vec3>}
  8754. */
  8755. const normalViewGeometry = /*@__PURE__*/ ( Fn( ( builder ) => {
  8756. let node;
  8757. if ( builder.material.flatShading === true ) {
  8758. node = normalFlat;
  8759. } else {
  8760. node = transformNormalToView( normalLocal ).toVarying( 'v_normalViewGeometry' ).normalize();
  8761. }
  8762. return node;
  8763. }, 'vec3' ).once() )().toVar( 'normalViewGeometry' );
  8764. /**
  8765. * TSL object that represents the vertex normal of the current rendered object in world space.
  8766. *
  8767. * @tsl
  8768. * @type {Node<vec3>}
  8769. */
  8770. const normalWorldGeometry = /*@__PURE__*/ ( Fn( ( builder ) => {
  8771. let normal = normalViewGeometry.transformDirection( cameraViewMatrix );
  8772. if ( builder.material.flatShading !== true ) {
  8773. normal = normal.toVarying( 'v_normalWorldGeometry' );
  8774. }
  8775. return normal.normalize().toVar( 'normalWorldGeometry' );
  8776. }, 'vec3' ).once() )();
  8777. /**
  8778. * TSL object that represents the vertex normal of the current rendered object in view space.
  8779. *
  8780. * @tsl
  8781. * @type {Node<vec3>}
  8782. */
  8783. const normalView = /*@__PURE__*/ ( Fn( ( { subBuildFn, material, context } ) => {
  8784. let node;
  8785. if ( subBuildFn === 'NORMAL' || subBuildFn === 'VERTEX' ) {
  8786. node = normalViewGeometry;
  8787. if ( material.flatShading !== true ) {
  8788. node = directionToFaceDirection( node );
  8789. }
  8790. } else {
  8791. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  8792. node = context.setupNormal().context( { getUV: null } );
  8793. }
  8794. return node;
  8795. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'normalView' );
  8796. /**
  8797. * TSL object that represents the vertex normal of the current rendered object in world space.
  8798. *
  8799. * @tsl
  8800. * @type {Node<vec3>}
  8801. */
  8802. const normalWorld = /*@__PURE__*/ normalView.transformDirection( cameraViewMatrix ).toVar( 'normalWorld' );
  8803. /**
  8804. * TSL object that represents the clearcoat vertex normal of the current rendered object in view space.
  8805. *
  8806. * @tsl
  8807. * @type {Node<vec3>}
  8808. */
  8809. const clearcoatNormalView = /*@__PURE__*/ ( Fn( ( { subBuildFn, context } ) => {
  8810. let node;
  8811. if ( subBuildFn === 'NORMAL' || subBuildFn === 'VERTEX' ) {
  8812. node = normalView;
  8813. } else {
  8814. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  8815. node = context.setupClearcoatNormal().context( { getUV: null } );
  8816. }
  8817. return node;
  8818. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'clearcoatNormalView' );
  8819. /**
  8820. * Transforms the normal with the given matrix.
  8821. *
  8822. * @tsl
  8823. * @function
  8824. * @param {Node<vec3>} normal - The normal.
  8825. * @param {Node<mat3>} [matrix=modelWorldMatrix] - The matrix.
  8826. * @return {Node<vec3>} The transformed normal.
  8827. */
  8828. const transformNormal = /*@__PURE__*/ Fn( ( [ normal, matrix = modelWorldMatrix ] ) => {
  8829. const m = mat3( matrix );
  8830. const transformedNormal = normal.div( vec3( m[ 0 ].dot( m[ 0 ] ), m[ 1 ].dot( m[ 1 ] ), m[ 2 ].dot( m[ 2 ] ) ) );
  8831. return m.mul( transformedNormal ).xyz;
  8832. } );
  8833. /**
  8834. * Transforms the given normal from local to view space.
  8835. *
  8836. * @tsl
  8837. * @function
  8838. * @param {Node<vec3>} normal - The normal.
  8839. * @param {NodeBuilder} builder - The current node builder.
  8840. * @return {Node<vec3>} The transformed normal.
  8841. */
  8842. const transformNormalToView = /*@__PURE__*/ Fn( ( [ normal ], builder ) => {
  8843. const modelNormalViewMatrix = builder.renderer.overrideNodes.modelNormalViewMatrix;
  8844. if ( modelNormalViewMatrix !== null ) {
  8845. return modelNormalViewMatrix.transformDirection( normal );
  8846. }
  8847. //
  8848. const transformedNormal = modelNormalMatrix.mul( normal );
  8849. return cameraViewMatrix.transformDirection( transformedNormal );
  8850. } );
  8851. // Deprecated
  8852. /**
  8853. * TSL object that represents the transformed vertex normal of the current rendered object in view space.
  8854. *
  8855. * @tsl
  8856. * @type {Node<vec3>}
  8857. * @deprecated since r178. Use `normalView` instead.
  8858. */
  8859. const transformedNormalView = ( Fn( () => { // @deprecated, r177
  8860. console.warn( 'THREE.TSL: "transformedNormalView" is deprecated. Use "normalView" instead.' );
  8861. return normalView;
  8862. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  8863. /**
  8864. * TSL object that represents the transformed vertex normal of the current rendered object in world space.
  8865. *
  8866. * @tsl
  8867. * @type {Node<vec3>}
  8868. * @deprecated since r178. Use `normalWorld` instead.
  8869. */
  8870. const transformedNormalWorld = ( Fn( () => { // @deprecated, r177
  8871. console.warn( 'THREE.TSL: "transformedNormalWorld" is deprecated. Use "normalWorld" instead.' );
  8872. return normalWorld;
  8873. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  8874. /**
  8875. * TSL object that represents the transformed clearcoat vertex normal of the current rendered object in view space.
  8876. *
  8877. * @tsl
  8878. * @type {Node<vec3>}
  8879. * @deprecated since r178. Use `clearcoatNormalView` instead.
  8880. */
  8881. const transformedClearcoatNormalView = ( Fn( () => { // @deprecated, r177
  8882. console.warn( 'THREE.TSL: "transformedClearcoatNormalView" is deprecated. Use "clearcoatNormalView" instead.' );
  8883. return clearcoatNormalView;
  8884. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  8885. const _e1$1 = /*@__PURE__*/ new Euler();
  8886. const _m1$1 = /*@__PURE__*/ new Matrix4();
  8887. /**
  8888. * TSL object that represents the refraction ratio of the material used for rendering the current object.
  8889. *
  8890. * @tsl
  8891. * @type {UniformNode<float>}
  8892. */
  8893. const materialRefractionRatio = /*@__PURE__*/ uniform( 0 ).onReference( ( { material } ) => material ).onObjectUpdate( ( { material } ) => material.refractionRatio );
  8894. /**
  8895. * TSL object that represents the intensity of environment maps of PBR materials.
  8896. * When `material.envMap` is set, the value is `material.envMapIntensity` otherwise `scene.environmentIntensity`.
  8897. *
  8898. * @tsl
  8899. * @type {Node<float>}
  8900. */
  8901. const materialEnvIntensity = /*@__PURE__*/ uniform( 1 ).onReference( ( { material } ) => material ).onObjectUpdate( function ( { material, scene } ) {
  8902. return material.envMap ? material.envMapIntensity : scene.environmentIntensity;
  8903. } );
  8904. /**
  8905. * TSL object that represents the rotation of environment maps.
  8906. * When `material.envMap` is set, the value is `material.envMapRotation`. `scene.environmentRotation` controls the
  8907. * rotation of `scene.environment` instead.
  8908. *
  8909. * @tsl
  8910. * @type {Node<mat4>}
  8911. */
  8912. const materialEnvRotation = /*@__PURE__*/ uniform( new Matrix4() ).onReference( function ( frame ) {
  8913. return frame.material;
  8914. } ).onObjectUpdate( function ( { material, scene } ) {
  8915. const rotation = ( scene.environment !== null && material.envMap === null ) ? scene.environmentRotation : material.envMapRotation;
  8916. if ( rotation ) {
  8917. _e1$1.copy( rotation );
  8918. _m1$1.makeRotationFromEuler( _e1$1 );
  8919. } else {
  8920. _m1$1.identity();
  8921. }
  8922. return _m1$1;
  8923. } );
  8924. /**
  8925. * The reflect vector in view space.
  8926. *
  8927. * @tsl
  8928. * @type {Node<vec3>}
  8929. */
  8930. const reflectView = /*@__PURE__*/ positionViewDirection.negate().reflect( normalView );
  8931. /**
  8932. * The refract vector in view space.
  8933. *
  8934. * @tsl
  8935. * @type {Node<vec3>}
  8936. */
  8937. const refractView = /*@__PURE__*/ positionViewDirection.negate().refract( normalView, materialRefractionRatio );
  8938. /**
  8939. * Used for sampling cube maps when using cube reflection mapping.
  8940. *
  8941. * @tsl
  8942. * @type {Node<vec3>}
  8943. */
  8944. const reflectVector = /*@__PURE__*/ reflectView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  8945. /**
  8946. * Used for sampling cube maps when using cube refraction mapping.
  8947. *
  8948. * @tsl
  8949. * @type {Node<vec3>}
  8950. */
  8951. const refractVector = /*@__PURE__*/ refractView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  8952. const EmptyTexture = /*@__PURE__*/ new CubeTexture();
  8953. /**
  8954. * This type of uniform node represents a cube texture.
  8955. *
  8956. * @augments TextureNode
  8957. */
  8958. class CubeTextureNode extends TextureNode {
  8959. static get type() {
  8960. return 'CubeTextureNode';
  8961. }
  8962. /**
  8963. * Constructs a new cube texture node.
  8964. *
  8965. * @param {CubeTexture} value - The cube texture.
  8966. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  8967. * @param {?Node<int>} [levelNode=null] - The level node.
  8968. * @param {?Node<float>} [biasNode=null] - The bias node.
  8969. */
  8970. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  8971. super( value, uvNode, levelNode, biasNode );
  8972. /**
  8973. * This flag can be used for type testing.
  8974. *
  8975. * @type {boolean}
  8976. * @readonly
  8977. * @default true
  8978. */
  8979. this.isCubeTextureNode = true;
  8980. }
  8981. /**
  8982. * Overwrites the default implementation to return a fixed value `'cubeTexture'`.
  8983. *
  8984. * @param {NodeBuilder} builder - The current node builder.
  8985. * @return {string} The input type.
  8986. */
  8987. getInputType( /*builder*/ ) {
  8988. return 'cubeTexture';
  8989. }
  8990. /**
  8991. * Returns a default uvs based on the mapping type of the cube texture.
  8992. *
  8993. * @return {Node<vec3>} The default uv attribute.
  8994. */
  8995. getDefaultUV() {
  8996. const texture = this.value;
  8997. if ( texture.mapping === CubeReflectionMapping ) {
  8998. return reflectVector;
  8999. } else if ( texture.mapping === CubeRefractionMapping ) {
  9000. return refractVector;
  9001. } else {
  9002. console.error( 'THREE.CubeTextureNode: Mapping "%s" not supported.', texture.mapping );
  9003. return vec3( 0, 0, 0 );
  9004. }
  9005. }
  9006. /**
  9007. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  9008. * for cube textures. The uv transformation matrix is not applied to cube textures.
  9009. *
  9010. * @param {boolean} value - The update toggle.
  9011. */
  9012. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for CubeTextureNode
  9013. /**
  9014. * Setups the uv node. Depending on the backend as well as the texture type, it might be necessary
  9015. * to modify the uv node for correct sampling.
  9016. *
  9017. * @param {NodeBuilder} builder - The current node builder.
  9018. * @param {Node} uvNode - The uv node to setup.
  9019. * @return {Node} The updated uv node.
  9020. */
  9021. setupUV( builder, uvNode ) {
  9022. const texture = this.value;
  9023. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem || ! texture.isRenderTargetTexture ) {
  9024. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  9025. }
  9026. return materialEnvRotation.mul( uvNode );
  9027. }
  9028. /**
  9029. * Generates the uv code snippet.
  9030. *
  9031. * @param {NodeBuilder} builder - The current node builder.
  9032. * @param {Node} cubeUV - The uv node to generate code for.
  9033. * @return {string} The generated code snippet.
  9034. */
  9035. generateUV( builder, cubeUV ) {
  9036. return cubeUV.build( builder, 'vec3' );
  9037. }
  9038. }
  9039. /**
  9040. * TSL function for creating a cube texture node.
  9041. *
  9042. * @tsl
  9043. * @function
  9044. * @param {CubeTexture} value - The cube texture.
  9045. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  9046. * @param {?Node<int>} [levelNode=null] - The level node.
  9047. * @param {?Node<float>} [biasNode=null] - The bias node.
  9048. * @returns {CubeTextureNode}
  9049. */
  9050. const cubeTextureBase = /*@__PURE__*/ nodeProxy( CubeTextureNode ).setParameterLength( 1, 4 ).setName( 'cubeTexture' );
  9051. /**
  9052. * TSL function for creating a cube texture uniform node.
  9053. *
  9054. * @tsl
  9055. * @function
  9056. * @param {?CubeTexture|CubeTextureNode} [value=EmptyTexture] - The cube texture.
  9057. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  9058. * @param {?Node<int>} [levelNode=null] - The level node.
  9059. * @param {?Node<float>} [biasNode=null] - The bias node.
  9060. * @returns {CubeTextureNode}
  9061. */
  9062. const cubeTexture = ( value = EmptyTexture, uvNode = null, levelNode = null, biasNode = null ) => {
  9063. let textureNode;
  9064. if ( value && value.isCubeTextureNode === true ) {
  9065. textureNode = nodeObject( value.clone() );
  9066. textureNode.referenceNode = value.getSelf(); // Ensure the reference is set to the original node
  9067. if ( uvNode !== null ) textureNode.uvNode = nodeObject( uvNode );
  9068. if ( levelNode !== null ) textureNode.levelNode = nodeObject( levelNode );
  9069. if ( biasNode !== null ) textureNode.biasNode = nodeObject( biasNode );
  9070. } else {
  9071. textureNode = cubeTextureBase( value, uvNode, levelNode, biasNode );
  9072. }
  9073. return textureNode;
  9074. };
  9075. /**
  9076. * TSL function for creating a uniform cube texture node.
  9077. *
  9078. * @tsl
  9079. * @function
  9080. * @param {?CubeTexture} [value=EmptyTexture] - The cube texture.
  9081. * @returns {CubeTextureNode}
  9082. */
  9083. const uniformCubeTexture = ( value = EmptyTexture ) => cubeTextureBase( value );
  9084. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  9085. /**
  9086. * This class is only relevant if the referenced property is array-like.
  9087. * In this case, `ReferenceElementNode` allows to refer to a specific
  9088. * element inside the data structure via an index.
  9089. *
  9090. * @augments ArrayElementNode
  9091. */
  9092. class ReferenceElementNode extends ArrayElementNode {
  9093. static get type() {
  9094. return 'ReferenceElementNode';
  9095. }
  9096. /**
  9097. * Constructs a new reference element node.
  9098. *
  9099. * @param {?ReferenceNode} referenceNode - The reference node.
  9100. * @param {Node} indexNode - The index node that defines the element access.
  9101. */
  9102. constructor( referenceNode, indexNode ) {
  9103. super( referenceNode, indexNode );
  9104. /**
  9105. * Similar to {@link ReferenceNode#reference}, an additional
  9106. * property references to the current node.
  9107. *
  9108. * @type {?ReferenceNode}
  9109. * @default null
  9110. */
  9111. this.referenceNode = referenceNode;
  9112. /**
  9113. * This flag can be used for type testing.
  9114. *
  9115. * @type {boolean}
  9116. * @readonly
  9117. * @default true
  9118. */
  9119. this.isReferenceElementNode = true;
  9120. }
  9121. /**
  9122. * This method is overwritten since the node type is inferred from
  9123. * the uniform type of the reference node.
  9124. *
  9125. * @return {string} The node type.
  9126. */
  9127. getNodeType() {
  9128. return this.referenceNode.uniformType;
  9129. }
  9130. generate( builder ) {
  9131. const snippet = super.generate( builder );
  9132. const arrayType = this.referenceNode.getNodeType();
  9133. const elementType = this.getNodeType();
  9134. return builder.format( snippet, arrayType, elementType );
  9135. }
  9136. }
  9137. /**
  9138. * This type of node establishes a reference to a property of another object.
  9139. * In this way, the value of the node is automatically linked to the value of
  9140. * referenced object. Reference nodes internally represent the linked value
  9141. * as a uniform.
  9142. *
  9143. * @augments Node
  9144. */
  9145. class ReferenceNode extends Node {
  9146. static get type() {
  9147. return 'ReferenceNode';
  9148. }
  9149. /**
  9150. * Constructs a new reference node.
  9151. *
  9152. * @param {string} property - The name of the property the node refers to.
  9153. * @param {string} uniformType - The uniform type that should be used to represent the property value.
  9154. * @param {?Object} [object=null] - The object the property belongs to.
  9155. * @param {?number} [count=null] - When the linked property is an array-like, this parameter defines its length.
  9156. */
  9157. constructor( property, uniformType, object = null, count = null ) {
  9158. super();
  9159. /**
  9160. * The name of the property the node refers to.
  9161. *
  9162. * @type {string}
  9163. */
  9164. this.property = property;
  9165. /**
  9166. * The uniform type that should be used to represent the property value.
  9167. *
  9168. * @type {string}
  9169. */
  9170. this.uniformType = uniformType;
  9171. /**
  9172. * The object the property belongs to.
  9173. *
  9174. * @type {?Object}
  9175. * @default null
  9176. */
  9177. this.object = object;
  9178. /**
  9179. * When the linked property is an array, this parameter defines its length.
  9180. *
  9181. * @type {?number}
  9182. * @default null
  9183. */
  9184. this.count = count;
  9185. /**
  9186. * The property name might have dots so nested properties can be referred.
  9187. * The hierarchy of the names is stored inside this array.
  9188. *
  9189. * @type {Array<string>}
  9190. */
  9191. this.properties = property.split( '.' );
  9192. /**
  9193. * Points to the current referred object. This property exists next to {@link ReferenceNode#object}
  9194. * since the final reference might be updated from calling code.
  9195. *
  9196. * @type {?Object}
  9197. * @default null
  9198. */
  9199. this.reference = object;
  9200. /**
  9201. * The uniform node that holds the value of the reference node.
  9202. *
  9203. * @type {UniformNode}
  9204. * @default null
  9205. */
  9206. this.node = null;
  9207. /**
  9208. * The uniform group of the internal uniform.
  9209. *
  9210. * @type {UniformGroupNode}
  9211. * @default null
  9212. */
  9213. this.group = null;
  9214. /**
  9215. * An optional label of the internal uniform node.
  9216. *
  9217. * @type {?string}
  9218. * @default null
  9219. */
  9220. this.name = null;
  9221. /**
  9222. * Overwritten since reference nodes are updated per object.
  9223. *
  9224. * @type {string}
  9225. * @default 'object'
  9226. */
  9227. this.updateType = NodeUpdateType.OBJECT;
  9228. }
  9229. /**
  9230. * When the referred property is array-like, this method can be used
  9231. * to access elements via an index node.
  9232. *
  9233. * @param {IndexNode} indexNode - indexNode.
  9234. * @return {ReferenceElementNode} A reference to an element.
  9235. */
  9236. element( indexNode ) {
  9237. return nodeObject( new ReferenceElementNode( this, nodeObject( indexNode ) ) );
  9238. }
  9239. /**
  9240. * Sets the uniform group for this reference node.
  9241. *
  9242. * @param {UniformGroupNode} group - The uniform group to set.
  9243. * @return {ReferenceNode} A reference to this node.
  9244. */
  9245. setGroup( group ) {
  9246. this.group = group;
  9247. return this;
  9248. }
  9249. /**
  9250. * Sets the label for the internal uniform.
  9251. *
  9252. * @param {string} name - The label to set.
  9253. * @return {ReferenceNode} A reference to this node.
  9254. */
  9255. label( name ) {
  9256. this.name = name;
  9257. return this;
  9258. }
  9259. /**
  9260. * Sets the node type which automatically defines the internal
  9261. * uniform type.
  9262. *
  9263. * @param {string} uniformType - The type to set.
  9264. */
  9265. setNodeType( uniformType ) {
  9266. let node = null;
  9267. if ( this.count !== null ) {
  9268. node = buffer( null, uniformType, this.count );
  9269. } else if ( Array.isArray( this.getValueFromReference() ) ) {
  9270. node = uniformArray( null, uniformType );
  9271. } else if ( uniformType === 'texture' ) {
  9272. node = texture( null );
  9273. } else if ( uniformType === 'cubeTexture' ) {
  9274. node = cubeTexture( null );
  9275. } else {
  9276. node = uniform( null, uniformType );
  9277. }
  9278. if ( this.group !== null ) {
  9279. node.setGroup( this.group );
  9280. }
  9281. if ( this.name !== null ) node.label( this.name );
  9282. this.node = node.getSelf();
  9283. }
  9284. /**
  9285. * This method is overwritten since the node type is inferred from
  9286. * the type of the reference node.
  9287. *
  9288. * @param {NodeBuilder} builder - The current node builder.
  9289. * @return {string} The node type.
  9290. */
  9291. getNodeType( builder ) {
  9292. if ( this.node === null ) {
  9293. this.updateReference( builder );
  9294. this.updateValue();
  9295. }
  9296. return this.node.getNodeType( builder );
  9297. }
  9298. /**
  9299. * Returns the property value from the given referred object.
  9300. *
  9301. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  9302. * @return {any} The value.
  9303. */
  9304. getValueFromReference( object = this.reference ) {
  9305. const { properties } = this;
  9306. let value = object[ properties[ 0 ] ];
  9307. for ( let i = 1; i < properties.length; i ++ ) {
  9308. value = value[ properties[ i ] ];
  9309. }
  9310. return value;
  9311. }
  9312. /**
  9313. * Allows to update the reference based on the given state. The state is only
  9314. * evaluated {@link ReferenceNode#object} is not set.
  9315. *
  9316. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  9317. * @return {Object} The updated reference.
  9318. */
  9319. updateReference( state ) {
  9320. this.reference = this.object !== null ? this.object : state.object;
  9321. return this.reference;
  9322. }
  9323. /**
  9324. * The output of the reference node is the internal uniform node.
  9325. *
  9326. * @param {NodeBuilder} builder - The current node builder.
  9327. * @return {UniformNode} The output node.
  9328. */
  9329. setup( /* builder */ ) {
  9330. this.updateValue();
  9331. return this.node;
  9332. }
  9333. /**
  9334. * Overwritten to update the internal uniform value.
  9335. *
  9336. * @param {NodeFrame} frame - A reference to the current node frame.
  9337. */
  9338. update( /*frame*/ ) {
  9339. this.updateValue();
  9340. }
  9341. /**
  9342. * Retrieves the value from the referred object property and uses it
  9343. * to updated the internal uniform.
  9344. */
  9345. updateValue() {
  9346. if ( this.node === null ) this.setNodeType( this.uniformType );
  9347. const value = this.getValueFromReference();
  9348. if ( Array.isArray( value ) ) {
  9349. this.node.array = value;
  9350. } else {
  9351. this.node.value = value;
  9352. }
  9353. }
  9354. }
  9355. /**
  9356. * TSL function for creating a reference node.
  9357. *
  9358. * @tsl
  9359. * @function
  9360. * @param {string} name - The name of the property the node refers to.
  9361. * @param {string} type - The uniform type that should be used to represent the property value.
  9362. * @param {?Object} [object] - The object the property belongs to.
  9363. * @returns {ReferenceNode}
  9364. */
  9365. const reference = ( name, type, object ) => nodeObject( new ReferenceNode( name, type, object ) );
  9366. /**
  9367. * TSL function for creating a reference node. Use this function if you want need a reference
  9368. * to an array-like property that should be represented as a uniform buffer.
  9369. *
  9370. * @tsl
  9371. * @function
  9372. * @param {string} name - The name of the property the node refers to.
  9373. * @param {string} type - The uniform type that should be used to represent the property value.
  9374. * @param {number} count - The number of value inside the array-like object.
  9375. * @param {Object} object - An array-like object the property belongs to.
  9376. * @returns {ReferenceNode}
  9377. */
  9378. const referenceBuffer = ( name, type, count, object ) => nodeObject( new ReferenceNode( name, type, object, count ) );
  9379. /**
  9380. * This node is a special type of reference node which is intended
  9381. * for linking material properties with node values.
  9382. * ```js
  9383. * const opacityNode = materialReference( 'opacity', 'float', material );
  9384. * ```
  9385. * When changing `material.opacity`, the node value of `opacityNode` will
  9386. * automatically be updated.
  9387. *
  9388. * @augments ReferenceNode
  9389. */
  9390. class MaterialReferenceNode extends ReferenceNode {
  9391. static get type() {
  9392. return 'MaterialReferenceNode';
  9393. }
  9394. /**
  9395. * Constructs a new material reference node.
  9396. *
  9397. * @param {string} property - The name of the property the node refers to.
  9398. * @param {string} inputType - The uniform type that should be used to represent the property value.
  9399. * @param {?Material} [material=null] - The material the property belongs to. When no material is set,
  9400. * the node refers to the material of the current rendered object.
  9401. */
  9402. constructor( property, inputType, material = null ) {
  9403. super( property, inputType, material );
  9404. /**
  9405. * The material the property belongs to. When no material is set,
  9406. * the node refers to the material of the current rendered object.
  9407. *
  9408. * @type {?Material}
  9409. * @default null
  9410. */
  9411. this.material = material;
  9412. /**
  9413. * This flag can be used for type testing.
  9414. *
  9415. * @type {boolean}
  9416. * @readonly
  9417. * @default true
  9418. */
  9419. this.isMaterialReferenceNode = true;
  9420. }
  9421. /**
  9422. * Updates the reference based on the given state. The state is only evaluated
  9423. * {@link MaterialReferenceNode#material} is not set.
  9424. *
  9425. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  9426. * @return {Object} The updated reference.
  9427. */
  9428. updateReference( state ) {
  9429. this.reference = this.material !== null ? this.material : state.material;
  9430. return this.reference;
  9431. }
  9432. }
  9433. /**
  9434. * TSL function for creating a material reference node.
  9435. *
  9436. * @tsl
  9437. * @function
  9438. * @param {string} name - The name of the property the node refers to.
  9439. * @param {string} type - The uniform type that should be used to represent the property value.
  9440. * @param {?Material} [material=null] - The material the property belongs to.
  9441. * When no material is set, the node refers to the material of the current rendered object.
  9442. * @returns {MaterialReferenceNode}
  9443. */
  9444. const materialReference = ( name, type, material = null ) => nodeObject( new MaterialReferenceNode( name, type, material ) );
  9445. // Normal Mapping Without Precomputed Tangents
  9446. // http://www.thetenthplanet.de/archives/1180
  9447. const uv = uv$1();
  9448. const q0 = positionView.dFdx();
  9449. const q1 = positionView.dFdy();
  9450. const st0 = uv.dFdx();
  9451. const st1 = uv.dFdy();
  9452. const N = normalView;
  9453. const q1perp = q1.cross( N );
  9454. const q0perp = N.cross( q0 );
  9455. const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) );
  9456. const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) );
  9457. const det = T.dot( T ).max( B.dot( B ) );
  9458. const scale = det.equal( 0.0 ).select( 0.0, det.inverseSqrt() );
  9459. /**
  9460. * Tangent vector in view space, computed dynamically from geometry and UV derivatives.
  9461. * Useful for normal mapping without precomputed tangents.
  9462. *
  9463. * Reference: http://www.thetenthplanet.de/archives/1180
  9464. *
  9465. * @tsl
  9466. * @type {Node<vec3>}
  9467. */
  9468. const tangentViewFrame = /*@__PURE__*/ T.mul( scale ).toVar( 'tangentViewFrame' );
  9469. /**
  9470. * Bitangent vector in view space, computed dynamically from geometry and UV derivatives.
  9471. * Complements the tangentViewFrame for constructing the tangent space basis.
  9472. *
  9473. * Reference: http://www.thetenthplanet.de/archives/1180
  9474. *
  9475. * @tsl
  9476. * @type {Node<vec3>}
  9477. */
  9478. const bitangentViewFrame = /*@__PURE__*/ B.mul( scale ).toVar( 'bitangentViewFrame' );
  9479. /**
  9480. * TSL object that represents the tangent attribute of the current rendered object.
  9481. *
  9482. * @tsl
  9483. * @type {Node<vec4>}
  9484. */
  9485. const tangentGeometry = /*@__PURE__*/ Fn( ( builder ) => {
  9486. if ( builder.geometry.hasAttribute( 'tangent' ) === false ) {
  9487. builder.geometry.computeTangents();
  9488. }
  9489. return attribute( 'tangent', 'vec4' );
  9490. } )();
  9491. /**
  9492. * TSL object that represents the vertex tangent in local space of the current rendered object.
  9493. *
  9494. * @tsl
  9495. * @type {Node<vec3>}
  9496. */
  9497. const tangentLocal = /*@__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' );
  9498. /**
  9499. * TSL object that represents the vertex tangent in view space of the current rendered object.
  9500. *
  9501. * @tsl
  9502. * @type {Node<vec3>}
  9503. */
  9504. const tangentView = /*@__PURE__*/ ( Fn( ( { subBuildFn, geometry, material } ) => {
  9505. let node;
  9506. if ( subBuildFn === 'VERTEX' || geometry.hasAttribute( 'tangent' ) ) {
  9507. node = modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz.toVarying( 'v_tangentView' ).normalize();
  9508. } else {
  9509. node = tangentViewFrame;
  9510. }
  9511. if ( material.flatShading !== true ) {
  9512. node = directionToFaceDirection( node );
  9513. }
  9514. return node;
  9515. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'tangentView' );
  9516. /**
  9517. * TSL object that represents the vertex tangent in world space of the current rendered object.
  9518. *
  9519. * @tsl
  9520. * @type {Node<vec3>}
  9521. */
  9522. const tangentWorld = /*@__PURE__*/ tangentView.transformDirection( cameraViewMatrix ).toVarying( 'v_tangentWorld' ).normalize().toVar( 'tangentWorld' );
  9523. /**
  9524. * Returns the bitangent node and assigns it to a varying if the material is not flat shaded.
  9525. *
  9526. * @tsl
  9527. * @private
  9528. * @param {Node<vec3>} crossNormalTangent - The cross product of the normal and tangent vectors.
  9529. * @param {string} varyingName - The name of the varying to assign the bitangent to.
  9530. * @returns {Node<vec3>} The bitangent node.
  9531. */
  9532. const getBitangent = /*@__PURE__*/ Fn( ( [ crossNormalTangent, varyingName ], { subBuildFn, material } ) => {
  9533. let bitangent = crossNormalTangent.mul( tangentGeometry.w ).xyz;
  9534. if ( subBuildFn === 'NORMAL' && material.flatShading !== true ) {
  9535. bitangent = bitangent.toVarying( varyingName );
  9536. }
  9537. return bitangent;
  9538. } ).once( [ 'NORMAL' ] );
  9539. /**
  9540. * TSL object that represents the bitangent attribute of the current rendered object.
  9541. *
  9542. * @tsl
  9543. * @type {Node<vec3>}
  9544. */
  9545. const bitangentGeometry = /*@__PURE__*/ getBitangent( normalGeometry.cross( tangentGeometry ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' );
  9546. /**
  9547. * TSL object that represents the vertex bitangent in local space of the current rendered object.
  9548. *
  9549. * @tsl
  9550. * @type {Node<vec3>}
  9551. */
  9552. const bitangentLocal = /*@__PURE__*/ getBitangent( normalLocal.cross( tangentLocal ), 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' );
  9553. /**
  9554. * TSL object that represents the vertex bitangent in view space of the current rendered object.
  9555. *
  9556. * @tsl
  9557. * @type {Node<vec3>}
  9558. */
  9559. const bitangentView = /*@__PURE__*/ ( Fn( ( { subBuildFn, geometry, material } ) => {
  9560. let node;
  9561. if ( subBuildFn === 'VERTEX' || geometry.hasAttribute( 'tangent' ) ) {
  9562. node = getBitangent( normalView.cross( tangentView ), 'v_bitangentView' ).normalize();
  9563. } else {
  9564. node = bitangentViewFrame;
  9565. }
  9566. if ( material.flatShading !== true ) {
  9567. node = directionToFaceDirection( node );
  9568. }
  9569. return node;
  9570. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'bitangentView' );
  9571. /**
  9572. * TSL object that represents the vertex bitangent in world space of the current rendered object.
  9573. *
  9574. * @tsl
  9575. * @type {Node<vec3>}
  9576. */
  9577. const bitangentWorld = /*@__PURE__*/ getBitangent( normalWorld.cross( tangentWorld ), 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' );
  9578. /**
  9579. * TSL object that represents the TBN matrix in view space.
  9580. *
  9581. * @tsl
  9582. * @type {Node<mat3>}
  9583. */
  9584. const TBNViewMatrix = /*@__PURE__*/ mat3( tangentView, bitangentView, normalView ).toVar( 'TBNViewMatrix' );
  9585. /**
  9586. * TSL object that represents the parallax direction.
  9587. *
  9588. * @tsl
  9589. * @type {Node<mat3>}
  9590. */
  9591. const parallaxDirection = /*@__PURE__*/ positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/;
  9592. /**
  9593. * TSL function for computing parallax uv coordinates.
  9594. *
  9595. * @tsl
  9596. * @function
  9597. * @param {Node<vec2>} uv - A uv node.
  9598. * @param {Node<vec2>} scale - A scale node.
  9599. * @returns {Node<vec2>} Parallax uv coordinates.
  9600. */
  9601. const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) );
  9602. /**
  9603. * TSL function for computing bent normals.
  9604. *
  9605. * @tsl
  9606. * @function
  9607. * @returns {Node<vec3>} Bent normals.
  9608. */
  9609. const bentNormalView = /*@__PURE__*/ ( Fn( () => {
  9610. // https://google.github.io/filament/Filament.md.html#lighting/imagebasedlights/anisotropy
  9611. let bentNormal = anisotropyB.cross( positionViewDirection );
  9612. bentNormal = bentNormal.cross( anisotropyB ).normalize();
  9613. bentNormal = mix( bentNormal, normalView, anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2() ).normalize();
  9614. return bentNormal;
  9615. } ).once() )();
  9616. /**
  9617. * This class can be used for applying normals maps to materials.
  9618. *
  9619. * ```js
  9620. * material.normalNode = normalMap( texture( normalTex ) );
  9621. * ```
  9622. *
  9623. * @augments TempNode
  9624. */
  9625. class NormalMapNode extends TempNode {
  9626. static get type() {
  9627. return 'NormalMapNode';
  9628. }
  9629. /**
  9630. * Constructs a new normal map node.
  9631. *
  9632. * @param {Node<vec3>} node - Represents the normal map data.
  9633. * @param {?Node<vec2>} [scaleNode=null] - Controls the intensity of the effect.
  9634. */
  9635. constructor( node, scaleNode = null ) {
  9636. super( 'vec3' );
  9637. /**
  9638. * Represents the normal map data.
  9639. *
  9640. * @type {Node<vec3>}
  9641. */
  9642. this.node = node;
  9643. /**
  9644. * Controls the intensity of the effect.
  9645. *
  9646. * @type {?Node<vec2>}
  9647. * @default null
  9648. */
  9649. this.scaleNode = scaleNode;
  9650. /**
  9651. * The normal map type.
  9652. *
  9653. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  9654. * @default TangentSpaceNormalMap
  9655. */
  9656. this.normalMapType = TangentSpaceNormalMap;
  9657. }
  9658. setup( { material } ) {
  9659. const { normalMapType, scaleNode } = this;
  9660. let normalMap = this.node.mul( 2.0 ).sub( 1.0 );
  9661. if ( scaleNode !== null ) {
  9662. let scale = scaleNode;
  9663. if ( material.flatShading === true ) {
  9664. scale = directionToFaceDirection( scale );
  9665. }
  9666. normalMap = vec3( normalMap.xy.mul( scale ), normalMap.z );
  9667. }
  9668. let output = null;
  9669. if ( normalMapType === ObjectSpaceNormalMap ) {
  9670. output = transformNormalToView( normalMap );
  9671. } else if ( normalMapType === TangentSpaceNormalMap ) {
  9672. output = TBNViewMatrix.mul( normalMap ).normalize();
  9673. } else {
  9674. console.error( `THREE.NodeMaterial: Unsupported normal map type: ${ normalMapType }` );
  9675. output = normalView; // Fallback to default normal view
  9676. }
  9677. return output;
  9678. }
  9679. }
  9680. /**
  9681. * TSL function for creating a normal map node.
  9682. *
  9683. * @tsl
  9684. * @function
  9685. * @param {Node<vec3>} node - Represents the normal map data.
  9686. * @param {?Node<vec2>} [scaleNode=null] - Controls the intensity of the effect.
  9687. * @returns {NormalMapNode}
  9688. */
  9689. const normalMap = /*@__PURE__*/ nodeProxy( NormalMapNode ).setParameterLength( 1, 2 );
  9690. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  9691. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  9692. const dHdxy_fwd = Fn( ( { textureNode, bumpScale } ) => {
  9693. // It's used to preserve the same TextureNode instance
  9694. const sampleTexture = ( callback ) => textureNode.cache().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv$1() ), forceUVContext: true } );
  9695. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  9696. return vec2(
  9697. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  9698. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  9699. ).mul( bumpScale );
  9700. } );
  9701. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  9702. const perturbNormalArb = Fn( ( inputs ) => {
  9703. const { surf_pos, surf_norm, dHdxy } = inputs;
  9704. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  9705. const vSigmaX = surf_pos.dFdx().normalize();
  9706. const vSigmaY = surf_pos.dFdy().normalize();
  9707. const vN = surf_norm; // normalized
  9708. const R1 = vSigmaY.cross( vN );
  9709. const R2 = vN.cross( vSigmaX );
  9710. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  9711. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  9712. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  9713. } );
  9714. /**
  9715. * This class can be used for applying bump maps to materials.
  9716. *
  9717. * ```js
  9718. * material.normalNode = bumpMap( texture( bumpTex ) );
  9719. * ```
  9720. *
  9721. * @augments TempNode
  9722. */
  9723. class BumpMapNode extends TempNode {
  9724. static get type() {
  9725. return 'BumpMapNode';
  9726. }
  9727. /**
  9728. * Constructs a new bump map node.
  9729. *
  9730. * @param {Node<float>} textureNode - Represents the bump map data.
  9731. * @param {?Node<float>} [scaleNode=null] - Controls the intensity of the bump effect.
  9732. */
  9733. constructor( textureNode, scaleNode = null ) {
  9734. super( 'vec3' );
  9735. /**
  9736. * Represents the bump map data.
  9737. *
  9738. * @type {Node<float>}
  9739. */
  9740. this.textureNode = textureNode;
  9741. /**
  9742. * Controls the intensity of the bump effect.
  9743. *
  9744. * @type {?Node<float>}
  9745. * @default null
  9746. */
  9747. this.scaleNode = scaleNode;
  9748. }
  9749. setup() {
  9750. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  9751. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  9752. return perturbNormalArb( {
  9753. surf_pos: positionView,
  9754. surf_norm: normalView,
  9755. dHdxy
  9756. } );
  9757. }
  9758. }
  9759. /**
  9760. * TSL function for creating a bump map node.
  9761. *
  9762. * @tsl
  9763. * @function
  9764. * @param {Node<float>} textureNode - Represents the bump map data.
  9765. * @param {?Node<float>} [scaleNode=null] - Controls the intensity of the bump effect.
  9766. * @returns {BumpMapNode}
  9767. */
  9768. const bumpMap = /*@__PURE__*/ nodeProxy( BumpMapNode ).setParameterLength( 1, 2 );
  9769. const _propertyCache = new Map();
  9770. /**
  9771. * This class should simplify the node access to material properties.
  9772. * It internal uses reference nodes to make sure changes to material
  9773. * properties are automatically reflected to predefined TSL objects
  9774. * like e.g. `materialColor`.
  9775. *
  9776. * @augments Node
  9777. */
  9778. class MaterialNode extends Node {
  9779. static get type() {
  9780. return 'MaterialNode';
  9781. }
  9782. /**
  9783. * Constructs a new material node.
  9784. *
  9785. * @param {string} scope - The scope defines what kind of material property is referred by the node.
  9786. */
  9787. constructor( scope ) {
  9788. super();
  9789. /**
  9790. * The scope defines what material property is referred by the node.
  9791. *
  9792. * @type {string}
  9793. */
  9794. this.scope = scope;
  9795. }
  9796. /**
  9797. * Returns a cached reference node for the given property and type.
  9798. *
  9799. * @param {string} property - The name of the material property.
  9800. * @param {string} type - The uniform type of the property.
  9801. * @return {MaterialReferenceNode} A material reference node representing the property access.
  9802. */
  9803. getCache( property, type ) {
  9804. let node = _propertyCache.get( property );
  9805. if ( node === undefined ) {
  9806. node = materialReference( property, type );
  9807. _propertyCache.set( property, node );
  9808. }
  9809. return node;
  9810. }
  9811. /**
  9812. * Returns a float-typed material reference node for the given property name.
  9813. *
  9814. * @param {string} property - The name of the material property.
  9815. * @return {MaterialReferenceNode<float>} A material reference node representing the property access.
  9816. */
  9817. getFloat( property ) {
  9818. return this.getCache( property, 'float' );
  9819. }
  9820. /**
  9821. * Returns a color-typed material reference node for the given property name.
  9822. *
  9823. * @param {string} property - The name of the material property.
  9824. * @return {MaterialReferenceNode<color>} A material reference node representing the property access.
  9825. */
  9826. getColor( property ) {
  9827. return this.getCache( property, 'color' );
  9828. }
  9829. /**
  9830. * Returns a texture-typed material reference node for the given property name.
  9831. *
  9832. * @param {string} property - The name of the material property.
  9833. * @return {MaterialReferenceNode} A material reference node representing the property access.
  9834. */
  9835. getTexture( property ) {
  9836. return this.getCache( property === 'map' ? 'map' : property + 'Map', 'texture' );
  9837. }
  9838. /**
  9839. * The node setup is done depending on the selected scope. Multiple material properties
  9840. * might be grouped into a single node composition if they logically belong together.
  9841. *
  9842. * @param {NodeBuilder} builder - The current node builder.
  9843. * @return {Node} The node representing the selected scope.
  9844. */
  9845. setup( builder ) {
  9846. const material = builder.context.material;
  9847. const scope = this.scope;
  9848. let node = null;
  9849. if ( scope === MaterialNode.COLOR ) {
  9850. const colorNode = material.color !== undefined ? this.getColor( scope ) : vec3();
  9851. if ( material.map && material.map.isTexture === true ) {
  9852. node = colorNode.mul( this.getTexture( 'map' ) );
  9853. } else {
  9854. node = colorNode;
  9855. }
  9856. } else if ( scope === MaterialNode.OPACITY ) {
  9857. const opacityNode = this.getFloat( scope );
  9858. if ( material.alphaMap && material.alphaMap.isTexture === true ) {
  9859. node = opacityNode.mul( this.getTexture( 'alpha' ) );
  9860. } else {
  9861. node = opacityNode;
  9862. }
  9863. } else if ( scope === MaterialNode.SPECULAR_STRENGTH ) {
  9864. if ( material.specularMap && material.specularMap.isTexture === true ) {
  9865. node = this.getTexture( 'specular' ).r;
  9866. } else {
  9867. node = float( 1 );
  9868. }
  9869. } else if ( scope === MaterialNode.SPECULAR_INTENSITY ) {
  9870. const specularIntensityNode = this.getFloat( scope );
  9871. if ( material.specularIntensityMap && material.specularIntensityMap.isTexture === true ) {
  9872. node = specularIntensityNode.mul( this.getTexture( scope ).a );
  9873. } else {
  9874. node = specularIntensityNode;
  9875. }
  9876. } else if ( scope === MaterialNode.SPECULAR_COLOR ) {
  9877. const specularColorNode = this.getColor( scope );
  9878. if ( material.specularColorMap && material.specularColorMap.isTexture === true ) {
  9879. node = specularColorNode.mul( this.getTexture( scope ).rgb );
  9880. } else {
  9881. node = specularColorNode;
  9882. }
  9883. } else if ( scope === MaterialNode.ROUGHNESS ) { // TODO: cleanup similar branches
  9884. const roughnessNode = this.getFloat( scope );
  9885. if ( material.roughnessMap && material.roughnessMap.isTexture === true ) {
  9886. node = roughnessNode.mul( this.getTexture( scope ).g );
  9887. } else {
  9888. node = roughnessNode;
  9889. }
  9890. } else if ( scope === MaterialNode.METALNESS ) {
  9891. const metalnessNode = this.getFloat( scope );
  9892. if ( material.metalnessMap && material.metalnessMap.isTexture === true ) {
  9893. node = metalnessNode.mul( this.getTexture( scope ).b );
  9894. } else {
  9895. node = metalnessNode;
  9896. }
  9897. } else if ( scope === MaterialNode.EMISSIVE ) {
  9898. const emissiveIntensityNode = this.getFloat( 'emissiveIntensity' );
  9899. const emissiveNode = this.getColor( scope ).mul( emissiveIntensityNode );
  9900. if ( material.emissiveMap && material.emissiveMap.isTexture === true ) {
  9901. node = emissiveNode.mul( this.getTexture( scope ) );
  9902. } else {
  9903. node = emissiveNode;
  9904. }
  9905. } else if ( scope === MaterialNode.NORMAL ) {
  9906. if ( material.normalMap ) {
  9907. node = normalMap( this.getTexture( 'normal' ), this.getCache( 'normalScale', 'vec2' ) );
  9908. node.normalMapType = material.normalMapType;
  9909. } else if ( material.bumpMap ) {
  9910. node = bumpMap( this.getTexture( 'bump' ).r, this.getFloat( 'bumpScale' ) );
  9911. } else {
  9912. node = normalView;
  9913. }
  9914. } else if ( scope === MaterialNode.CLEARCOAT ) {
  9915. const clearcoatNode = this.getFloat( scope );
  9916. if ( material.clearcoatMap && material.clearcoatMap.isTexture === true ) {
  9917. node = clearcoatNode.mul( this.getTexture( scope ).r );
  9918. } else {
  9919. node = clearcoatNode;
  9920. }
  9921. } else if ( scope === MaterialNode.CLEARCOAT_ROUGHNESS ) {
  9922. const clearcoatRoughnessNode = this.getFloat( scope );
  9923. if ( material.clearcoatRoughnessMap && material.clearcoatRoughnessMap.isTexture === true ) {
  9924. node = clearcoatRoughnessNode.mul( this.getTexture( scope ).r );
  9925. } else {
  9926. node = clearcoatRoughnessNode;
  9927. }
  9928. } else if ( scope === MaterialNode.CLEARCOAT_NORMAL ) {
  9929. if ( material.clearcoatNormalMap ) {
  9930. node = normalMap( this.getTexture( scope ), this.getCache( scope + 'Scale', 'vec2' ) );
  9931. } else {
  9932. node = normalView;
  9933. }
  9934. } else if ( scope === MaterialNode.SHEEN ) {
  9935. const sheenNode = this.getColor( 'sheenColor' ).mul( this.getFloat( 'sheen' ) ); // Move this mul() to CPU
  9936. if ( material.sheenColorMap && material.sheenColorMap.isTexture === true ) {
  9937. node = sheenNode.mul( this.getTexture( 'sheenColor' ).rgb );
  9938. } else {
  9939. node = sheenNode;
  9940. }
  9941. } else if ( scope === MaterialNode.SHEEN_ROUGHNESS ) {
  9942. const sheenRoughnessNode = this.getFloat( scope );
  9943. if ( material.sheenRoughnessMap && material.sheenRoughnessMap.isTexture === true ) {
  9944. node = sheenRoughnessNode.mul( this.getTexture( scope ).a );
  9945. } else {
  9946. node = sheenRoughnessNode;
  9947. }
  9948. node = node.clamp( 0.07, 1.0 );
  9949. } else if ( scope === MaterialNode.ANISOTROPY ) {
  9950. if ( material.anisotropyMap && material.anisotropyMap.isTexture === true ) {
  9951. const anisotropyPolar = this.getTexture( scope );
  9952. const anisotropyMat = mat2( materialAnisotropyVector.x, materialAnisotropyVector.y, materialAnisotropyVector.y.negate(), materialAnisotropyVector.x );
  9953. node = anisotropyMat.mul( anisotropyPolar.rg.mul( 2.0 ).sub( vec2( 1.0 ) ).normalize().mul( anisotropyPolar.b ) );
  9954. } else {
  9955. node = materialAnisotropyVector;
  9956. }
  9957. } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) {
  9958. const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange );
  9959. if ( material.iridescenceThicknessMap ) {
  9960. const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange );
  9961. node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum );
  9962. } else {
  9963. node = iridescenceThicknessMaximum;
  9964. }
  9965. } else if ( scope === MaterialNode.TRANSMISSION ) {
  9966. const transmissionNode = this.getFloat( scope );
  9967. if ( material.transmissionMap ) {
  9968. node = transmissionNode.mul( this.getTexture( scope ).r );
  9969. } else {
  9970. node = transmissionNode;
  9971. }
  9972. } else if ( scope === MaterialNode.THICKNESS ) {
  9973. const thicknessNode = this.getFloat( scope );
  9974. if ( material.thicknessMap ) {
  9975. node = thicknessNode.mul( this.getTexture( scope ).g );
  9976. } else {
  9977. node = thicknessNode;
  9978. }
  9979. } else if ( scope === MaterialNode.IOR ) {
  9980. node = this.getFloat( scope );
  9981. } else if ( scope === MaterialNode.LIGHT_MAP ) {
  9982. node = this.getTexture( scope ).rgb.mul( this.getFloat( 'lightMapIntensity' ) );
  9983. } else if ( scope === MaterialNode.AO ) {
  9984. node = this.getTexture( scope ).r.sub( 1.0 ).mul( this.getFloat( 'aoMapIntensity' ) ).add( 1.0 );
  9985. } else if ( scope === MaterialNode.LINE_DASH_OFFSET ) {
  9986. node = ( material.dashOffset ) ? this.getFloat( scope ) : float( 0 );
  9987. } else {
  9988. const outputType = this.getNodeType( builder );
  9989. node = this.getCache( scope, outputType );
  9990. }
  9991. return node;
  9992. }
  9993. }
  9994. MaterialNode.ALPHA_TEST = 'alphaTest';
  9995. MaterialNode.COLOR = 'color';
  9996. MaterialNode.OPACITY = 'opacity';
  9997. MaterialNode.SHININESS = 'shininess';
  9998. MaterialNode.SPECULAR = 'specular';
  9999. MaterialNode.SPECULAR_STRENGTH = 'specularStrength';
  10000. MaterialNode.SPECULAR_INTENSITY = 'specularIntensity';
  10001. MaterialNode.SPECULAR_COLOR = 'specularColor';
  10002. MaterialNode.REFLECTIVITY = 'reflectivity';
  10003. MaterialNode.ROUGHNESS = 'roughness';
  10004. MaterialNode.METALNESS = 'metalness';
  10005. MaterialNode.NORMAL = 'normal';
  10006. MaterialNode.CLEARCOAT = 'clearcoat';
  10007. MaterialNode.CLEARCOAT_ROUGHNESS = 'clearcoatRoughness';
  10008. MaterialNode.CLEARCOAT_NORMAL = 'clearcoatNormal';
  10009. MaterialNode.EMISSIVE = 'emissive';
  10010. MaterialNode.ROTATION = 'rotation';
  10011. MaterialNode.SHEEN = 'sheen';
  10012. MaterialNode.SHEEN_ROUGHNESS = 'sheenRoughness';
  10013. MaterialNode.ANISOTROPY = 'anisotropy';
  10014. MaterialNode.IRIDESCENCE = 'iridescence';
  10015. MaterialNode.IRIDESCENCE_IOR = 'iridescenceIOR';
  10016. MaterialNode.IRIDESCENCE_THICKNESS = 'iridescenceThickness';
  10017. MaterialNode.IOR = 'ior';
  10018. MaterialNode.TRANSMISSION = 'transmission';
  10019. MaterialNode.THICKNESS = 'thickness';
  10020. MaterialNode.ATTENUATION_DISTANCE = 'attenuationDistance';
  10021. MaterialNode.ATTENUATION_COLOR = 'attenuationColor';
  10022. MaterialNode.LINE_SCALE = 'scale';
  10023. MaterialNode.LINE_DASH_SIZE = 'dashSize';
  10024. MaterialNode.LINE_GAP_SIZE = 'gapSize';
  10025. MaterialNode.LINE_WIDTH = 'linewidth';
  10026. MaterialNode.LINE_DASH_OFFSET = 'dashOffset';
  10027. MaterialNode.POINT_SIZE = 'size';
  10028. MaterialNode.DISPERSION = 'dispersion';
  10029. MaterialNode.LIGHT_MAP = 'light';
  10030. MaterialNode.AO = 'ao';
  10031. /**
  10032. * TSL object that represents alpha test of the current material.
  10033. *
  10034. * @tsl
  10035. * @type {Node<float>}
  10036. */
  10037. const materialAlphaTest = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ALPHA_TEST );
  10038. /**
  10039. * TSL object that represents the diffuse color of the current material.
  10040. * The value is composed via `color` * `map`.
  10041. *
  10042. * @tsl
  10043. * @type {Node<vec3>}
  10044. */
  10045. const materialColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.COLOR );
  10046. /**
  10047. * TSL object that represents the shininess of the current material.
  10048. *
  10049. * @tsl
  10050. * @type {Node<float>}
  10051. */
  10052. const materialShininess = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHININESS );
  10053. /**
  10054. * TSL object that represents the emissive color of the current material.
  10055. * The value is composed via `emissive` * `emissiveIntensity` * `emissiveMap`.
  10056. *
  10057. * @tsl
  10058. * @type {Node<vec3>}
  10059. */
  10060. const materialEmissive = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.EMISSIVE );
  10061. /**
  10062. * TSL object that represents the opacity of the current material.
  10063. * The value is composed via `opacity` * `alphaMap`.
  10064. *
  10065. * @tsl
  10066. * @type {Node<float>}
  10067. */
  10068. const materialOpacity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.OPACITY );
  10069. /**
  10070. * TSL object that represents the specular of the current material.
  10071. *
  10072. * @tsl
  10073. * @type {Node<vec3>}
  10074. */
  10075. const materialSpecular = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR );
  10076. /**
  10077. * TSL object that represents the specular intensity of the current material.
  10078. * The value is composed via `specularIntensity` * `specularMap.a`.
  10079. *
  10080. * @tsl
  10081. * @type {Node<float>}
  10082. */
  10083. const materialSpecularIntensity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_INTENSITY );
  10084. /**
  10085. * TSL object that represents the specular color of the current material.
  10086. * The value is composed via `specularColor` * `specularMap.rgb`.
  10087. *
  10088. * @tsl
  10089. * @type {Node<vec3>}
  10090. */
  10091. const materialSpecularColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_COLOR );
  10092. /**
  10093. * TSL object that represents the specular strength of the current material.
  10094. * The value is composed via `specularMap.r`.
  10095. *
  10096. * @tsl
  10097. * @type {Node<float>}
  10098. */
  10099. const materialSpecularStrength = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_STRENGTH );
  10100. /**
  10101. * TSL object that represents the reflectivity of the current material.
  10102. *
  10103. * @tsl
  10104. * @type {Node<float>}
  10105. */
  10106. const materialReflectivity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.REFLECTIVITY );
  10107. /**
  10108. * TSL object that represents the roughness of the current material.
  10109. * The value is composed via `roughness` * `roughnessMap.g`.
  10110. *
  10111. * @tsl
  10112. * @type {Node<float>}
  10113. */
  10114. const materialRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROUGHNESS );
  10115. /**
  10116. * TSL object that represents the metalness of the current material.
  10117. * The value is composed via `metalness` * `metalnessMap.b`.
  10118. *
  10119. * @tsl
  10120. * @type {Node<float>}
  10121. */
  10122. const materialMetalness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.METALNESS );
  10123. /**
  10124. * TSL object that represents the normal of the current material.
  10125. * The value will be either `normalMap` * `normalScale`, `bumpMap` * `bumpScale` or `normalView`.
  10126. *
  10127. * @tsl
  10128. * @type {Node<vec3>}
  10129. */
  10130. const materialNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.NORMAL );
  10131. /**
  10132. * TSL object that represents the clearcoat of the current material.
  10133. * The value is composed via `clearcoat` * `clearcoatMap.r`
  10134. *
  10135. * @tsl
  10136. * @type {Node<float>}
  10137. */
  10138. const materialClearcoat = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT );
  10139. /**
  10140. * TSL object that represents the clearcoat roughness of the current material.
  10141. * The value is composed via `clearcoatRoughness` * `clearcoatRoughnessMap.r`.
  10142. *
  10143. * @tsl
  10144. * @type {Node<float>}
  10145. */
  10146. const materialClearcoatRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_ROUGHNESS );
  10147. /**
  10148. * TSL object that represents the clearcoat normal of the current material.
  10149. * The value will be either `clearcoatNormalMap` or `normalView`.
  10150. *
  10151. * @tsl
  10152. * @type {Node<vec3>}
  10153. */
  10154. const materialClearcoatNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_NORMAL );
  10155. /**
  10156. * TSL object that represents the rotation of the current sprite material.
  10157. *
  10158. * @tsl
  10159. * @type {Node<float>}
  10160. */
  10161. const materialRotation = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROTATION );
  10162. /**
  10163. * TSL object that represents the sheen color of the current material.
  10164. * The value is composed via `sheen` * `sheenColor` * `sheenColorMap`.
  10165. *
  10166. * @tsl
  10167. * @type {Node<vec3>}
  10168. */
  10169. const materialSheen = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN );
  10170. /**
  10171. * TSL object that represents the sheen roughness of the current material.
  10172. * The value is composed via `sheenRoughness` * `sheenRoughnessMap.a`.
  10173. *
  10174. * @tsl
  10175. * @type {Node<float>}
  10176. */
  10177. const materialSheenRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN_ROUGHNESS );
  10178. /**
  10179. * TSL object that represents the anisotropy of the current material.
  10180. *
  10181. * @tsl
  10182. * @type {Node<vec2>}
  10183. */
  10184. const materialAnisotropy = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ANISOTROPY );
  10185. /**
  10186. * TSL object that represents the iridescence of the current material.
  10187. *
  10188. * @tsl
  10189. * @type {Node<float>}
  10190. */
  10191. const materialIridescence = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE );
  10192. /**
  10193. * TSL object that represents the iridescence IOR of the current material.
  10194. *
  10195. * @tsl
  10196. * @type {Node<float>}
  10197. */
  10198. const materialIridescenceIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_IOR );
  10199. /**
  10200. * TSL object that represents the iridescence thickness of the current material.
  10201. *
  10202. * @tsl
  10203. * @type {Node<float>}
  10204. */
  10205. const materialIridescenceThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_THICKNESS );
  10206. /**
  10207. * TSL object that represents the transmission of the current material.
  10208. * The value is composed via `transmission` * `transmissionMap.r`.
  10209. *
  10210. * @tsl
  10211. * @type {Node<float>}
  10212. */
  10213. const materialTransmission = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.TRANSMISSION );
  10214. /**
  10215. * TSL object that represents the thickness of the current material.
  10216. * The value is composed via `thickness` * `thicknessMap.g`.
  10217. *
  10218. * @tsl
  10219. * @type {Node<float>}
  10220. */
  10221. const materialThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.THICKNESS );
  10222. /**
  10223. * TSL object that represents the IOR of the current material.
  10224. *
  10225. * @tsl
  10226. * @type {Node<float>}
  10227. */
  10228. const materialIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IOR );
  10229. /**
  10230. * TSL object that represents the attenuation distance of the current material.
  10231. *
  10232. * @tsl
  10233. * @type {Node<float>}
  10234. */
  10235. const materialAttenuationDistance = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_DISTANCE );
  10236. /**
  10237. * TSL object that represents the attenuation color of the current material.
  10238. *
  10239. * @tsl
  10240. * @type {Node<vec3>}
  10241. */
  10242. const materialAttenuationColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_COLOR );
  10243. /**
  10244. * TSL object that represents the scale of the current dashed line material.
  10245. *
  10246. * @tsl
  10247. * @type {Node<float>}
  10248. */
  10249. const materialLineScale = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_SCALE );
  10250. /**
  10251. * TSL object that represents the dash size of the current dashed line material.
  10252. *
  10253. * @tsl
  10254. * @type {Node<float>}
  10255. */
  10256. const materialLineDashSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_SIZE );
  10257. /**
  10258. * TSL object that represents the gap size of the current dashed line material.
  10259. *
  10260. * @tsl
  10261. * @type {Node<float>}
  10262. */
  10263. const materialLineGapSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_GAP_SIZE );
  10264. /**
  10265. * TSL object that represents the line width of the current line material.
  10266. *
  10267. * @tsl
  10268. * @type {Node<float>}
  10269. */
  10270. const materialLineWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_WIDTH );
  10271. /**
  10272. * TSL object that represents the dash offset of the current line material.
  10273. *
  10274. * @tsl
  10275. * @type {Node<float>}
  10276. */
  10277. const materialLineDashOffset = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_OFFSET );
  10278. /**
  10279. * TSL object that represents the point size of the current points material.
  10280. *
  10281. * @tsl
  10282. * @type {Node<float>}
  10283. */
  10284. const materialPointSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.POINT_SIZE );
  10285. /**
  10286. * TSL object that represents the dispersion of the current material.
  10287. *
  10288. * @tsl
  10289. * @type {Node<float>}
  10290. */
  10291. const materialDispersion = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.DISPERSION );
  10292. /**
  10293. * TSL object that represents the light map of the current material.
  10294. * The value is composed via `lightMapIntensity` * `lightMap.rgb`.
  10295. *
  10296. * @tsl
  10297. * @type {Node<vec3>}
  10298. */
  10299. const materialLightMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LIGHT_MAP );
  10300. /**
  10301. * TSL object that represents the ambient occlusion map of the current material.
  10302. * The value is composed via `aoMap.r` - 1 * `aoMapIntensity` + 1.
  10303. *
  10304. * @tsl
  10305. * @type {Node<float>}
  10306. */
  10307. const materialAO = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.AO );
  10308. /**
  10309. * TSL object that represents the anisotropy vector of the current material.
  10310. *
  10311. * @tsl
  10312. * @type {Node<vec2>}
  10313. */
  10314. const materialAnisotropyVector = /*@__PURE__*/ uniform( new Vector2() ).onReference( function ( frame ) {
  10315. return frame.material;
  10316. } ).onRenderUpdate( function ( { material } ) {
  10317. this.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  10318. } );
  10319. /**
  10320. * TSL object that represents the position in clip space after the model-view-projection transform of the current rendered object.
  10321. *
  10322. * @tsl
  10323. * @type {VaryingNode<vec4>}
  10324. */
  10325. const modelViewProjection = /*@__PURE__*/ ( Fn( ( builder ) => {
  10326. return builder.context.setupModelViewProjection();
  10327. }, 'vec4' ).once() )().toVarying( 'v_modelViewProjection' );
  10328. /**
  10329. * This class represents shader indices of different types. The following predefined node
  10330. * objects cover frequent use cases:
  10331. *
  10332. * - `vertexIndex`: The index of a vertex within a mesh.
  10333. * - `instanceIndex`: The index of either a mesh instance or an invocation of a compute shader.
  10334. * - `drawIndex`: The index of a draw call.
  10335. * - `invocationLocalIndex`: The index of a compute invocation within the scope of a workgroup load.
  10336. * - `invocationSubgroupIndex`: The index of a compute invocation within the scope of a subgroup.
  10337. * - `subgroupIndex`: The index of the subgroup the current compute invocation belongs to.
  10338. *
  10339. * @augments Node
  10340. */
  10341. class IndexNode extends Node {
  10342. static get type() {
  10343. return 'IndexNode';
  10344. }
  10345. /**
  10346. * Constructs a new index node.
  10347. *
  10348. * @param {('vertex'|'instance'|'subgroup'|'invocationLocal'|'invocationSubgroup'|'draw')} scope - The scope of the index node.
  10349. */
  10350. constructor( scope ) {
  10351. super( 'uint' );
  10352. /**
  10353. * The scope of the index node.
  10354. *
  10355. * @type {string}
  10356. */
  10357. this.scope = scope;
  10358. /**
  10359. * This flag can be used for type testing.
  10360. *
  10361. * @type {boolean}
  10362. * @readonly
  10363. * @default true
  10364. */
  10365. this.isIndexNode = true;
  10366. }
  10367. generate( builder ) {
  10368. const nodeType = this.getNodeType( builder );
  10369. const scope = this.scope;
  10370. let propertyName;
  10371. if ( scope === IndexNode.VERTEX ) {
  10372. propertyName = builder.getVertexIndex();
  10373. } else if ( scope === IndexNode.INSTANCE ) {
  10374. propertyName = builder.getInstanceIndex();
  10375. } else if ( scope === IndexNode.DRAW ) {
  10376. propertyName = builder.getDrawIndex();
  10377. } else if ( scope === IndexNode.INVOCATION_LOCAL ) {
  10378. propertyName = builder.getInvocationLocalIndex();
  10379. } else if ( scope === IndexNode.INVOCATION_SUBGROUP ) {
  10380. propertyName = builder.getInvocationSubgroupIndex();
  10381. } else if ( scope === IndexNode.SUBGROUP ) {
  10382. propertyName = builder.getSubgroupIndex();
  10383. } else {
  10384. throw new Error( 'THREE.IndexNode: Unknown scope: ' + scope );
  10385. }
  10386. let output;
  10387. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  10388. output = propertyName;
  10389. } else {
  10390. const nodeVarying = varying( this );
  10391. output = nodeVarying.build( builder, nodeType );
  10392. }
  10393. return output;
  10394. }
  10395. }
  10396. IndexNode.VERTEX = 'vertex';
  10397. IndexNode.INSTANCE = 'instance';
  10398. IndexNode.SUBGROUP = 'subgroup';
  10399. IndexNode.INVOCATION_LOCAL = 'invocationLocal';
  10400. IndexNode.INVOCATION_SUBGROUP = 'invocationSubgroup';
  10401. IndexNode.DRAW = 'draw';
  10402. /**
  10403. * TSL object that represents the index of a vertex within a mesh.
  10404. *
  10405. * @tsl
  10406. * @type {IndexNode}
  10407. */
  10408. const vertexIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.VERTEX );
  10409. /**
  10410. * TSL object that represents the index of either a mesh instance or an invocation of a compute shader.
  10411. *
  10412. * @tsl
  10413. * @type {IndexNode}
  10414. */
  10415. const instanceIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INSTANCE );
  10416. /**
  10417. * TSL object that represents the index of the subgroup the current compute invocation belongs to.
  10418. *
  10419. * @tsl
  10420. * @type {IndexNode}
  10421. */
  10422. const subgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.SUBGROUP );
  10423. /**
  10424. * TSL object that represents the index of a compute invocation within the scope of a subgroup.
  10425. *
  10426. * @tsl
  10427. * @type {IndexNode}
  10428. */
  10429. const invocationSubgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_SUBGROUP );
  10430. /**
  10431. * TSL object that represents the index of a compute invocation within the scope of a workgroup load.
  10432. *
  10433. * @tsl
  10434. * @type {IndexNode}
  10435. */
  10436. const invocationLocalIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_LOCAL );
  10437. /**
  10438. * TSL object that represents the index of a draw call.
  10439. *
  10440. * @tsl
  10441. * @type {IndexNode}
  10442. */
  10443. const drawIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.DRAW );
  10444. /**
  10445. * This node implements the vertex shader logic which is required
  10446. * when rendering 3D objects via instancing. The code makes sure
  10447. * vertex positions, normals and colors can be modified via instanced
  10448. * data.
  10449. *
  10450. * @augments Node
  10451. */
  10452. class InstanceNode extends Node {
  10453. static get type() {
  10454. return 'InstanceNode';
  10455. }
  10456. /**
  10457. * Constructs a new instance node.
  10458. *
  10459. * @param {number} count - The number of instances.
  10460. * @param {InstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  10461. * @param {?InstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  10462. */
  10463. constructor( count, instanceMatrix, instanceColor = null ) {
  10464. super( 'void' );
  10465. /**
  10466. * The number of instances.
  10467. *
  10468. * @type {number}
  10469. */
  10470. this.count = count;
  10471. /**
  10472. * Instanced buffer attribute representing the transformation of instances.
  10473. *
  10474. * @type {InstancedBufferAttribute}
  10475. */
  10476. this.instanceMatrix = instanceMatrix;
  10477. /**
  10478. * Instanced buffer attribute representing the color of instances.
  10479. *
  10480. * @type {InstancedBufferAttribute}
  10481. */
  10482. this.instanceColor = instanceColor;
  10483. /**
  10484. * The node that represents the instance matrix data.
  10485. *
  10486. * @type {?Node}
  10487. */
  10488. this.instanceMatrixNode = null;
  10489. /**
  10490. * The node that represents the instance color data.
  10491. *
  10492. * @type {?Node}
  10493. * @default null
  10494. */
  10495. this.instanceColorNode = null;
  10496. /**
  10497. * The update type is set to `frame` since an update
  10498. * of instanced buffer data must be checked per frame.
  10499. *
  10500. * @type {string}
  10501. * @default 'frame'
  10502. */
  10503. this.updateType = NodeUpdateType.FRAME;
  10504. /**
  10505. * A reference to a buffer that is used by `instanceMatrixNode`.
  10506. *
  10507. * @type {?InstancedInterleavedBuffer}
  10508. */
  10509. this.buffer = null;
  10510. /**
  10511. * A reference to a buffer that is used by `instanceColorNode`.
  10512. *
  10513. * @type {?InstancedBufferAttribute}
  10514. */
  10515. this.bufferColor = null;
  10516. }
  10517. /**
  10518. * Setups the internal buffers and nodes and assigns the transformed vertex data
  10519. * to predefined node variables for accumulation. That follows the same patterns
  10520. * like with morph and skinning nodes.
  10521. *
  10522. * @param {NodeBuilder} builder - The current node builder.
  10523. */
  10524. setup( builder ) {
  10525. const { count, instanceMatrix, instanceColor } = this;
  10526. let { instanceMatrixNode, instanceColorNode } = this;
  10527. if ( instanceMatrixNode === null ) {
  10528. // 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.
  10529. if ( count <= 1000 ) {
  10530. instanceMatrixNode = buffer( instanceMatrix.array, 'mat4', Math.max( count, 1 ) ).element( instanceIndex );
  10531. } else {
  10532. const buffer = new InstancedInterleavedBuffer( instanceMatrix.array, 16, 1 );
  10533. this.buffer = buffer;
  10534. const bufferFn = instanceMatrix.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  10535. const instanceBuffers = [
  10536. // F.Signature -> bufferAttribute( array, type, stride, offset )
  10537. bufferFn( buffer, 'vec4', 16, 0 ),
  10538. bufferFn( buffer, 'vec4', 16, 4 ),
  10539. bufferFn( buffer, 'vec4', 16, 8 ),
  10540. bufferFn( buffer, 'vec4', 16, 12 )
  10541. ];
  10542. instanceMatrixNode = mat4( ...instanceBuffers );
  10543. }
  10544. this.instanceMatrixNode = instanceMatrixNode;
  10545. }
  10546. if ( instanceColor && instanceColorNode === null ) {
  10547. const buffer = new InstancedBufferAttribute( instanceColor.array, 3 );
  10548. const bufferFn = instanceColor.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  10549. this.bufferColor = buffer;
  10550. instanceColorNode = vec3( bufferFn( buffer, 'vec3', 3, 0 ) );
  10551. this.instanceColorNode = instanceColorNode;
  10552. }
  10553. // POSITION
  10554. const instancePosition = instanceMatrixNode.mul( positionLocal ).xyz;
  10555. positionLocal.assign( instancePosition );
  10556. // NORMAL
  10557. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  10558. const instanceNormal = transformNormal( normalLocal, instanceMatrixNode );
  10559. // ASSIGNS
  10560. normalLocal.assign( instanceNormal );
  10561. }
  10562. // COLOR
  10563. if ( this.instanceColorNode !== null ) {
  10564. varyingProperty( 'vec3', 'vInstanceColor' ).assign( this.instanceColorNode );
  10565. }
  10566. }
  10567. /**
  10568. * Checks if the internal buffers required an update.
  10569. *
  10570. * @param {NodeFrame} frame - The current node frame.
  10571. */
  10572. update( /*frame*/ ) {
  10573. if ( this.instanceMatrix.usage !== DynamicDrawUsage && this.buffer !== null && this.instanceMatrix.version !== this.buffer.version ) {
  10574. this.buffer.version = this.instanceMatrix.version;
  10575. }
  10576. if ( this.instanceColor && this.instanceColor.usage !== DynamicDrawUsage && this.bufferColor !== null && this.instanceColor.version !== this.bufferColor.version ) {
  10577. this.bufferColor.version = this.instanceColor.version;
  10578. }
  10579. }
  10580. }
  10581. /**
  10582. * TSL function for creating an instance node.
  10583. *
  10584. * @tsl
  10585. * @function
  10586. * @param {number} count - The number of instances.
  10587. * @param {InstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  10588. * @param {?InstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  10589. * @returns {InstanceNode}
  10590. */
  10591. const instance = /*@__PURE__*/ nodeProxy( InstanceNode ).setParameterLength( 2, 3 );
  10592. /**
  10593. * This is a special version of `InstanceNode` which requires the usage of {@link InstancedMesh}.
  10594. * It allows an easier setup of the instance node.
  10595. *
  10596. * @augments InstanceNode
  10597. */
  10598. class InstancedMeshNode extends InstanceNode {
  10599. static get type() {
  10600. return 'InstancedMeshNode';
  10601. }
  10602. /**
  10603. * Constructs a new instanced mesh node.
  10604. *
  10605. * @param {InstancedMesh} instancedMesh - The instanced mesh.
  10606. */
  10607. constructor( instancedMesh ) {
  10608. const { count, instanceMatrix, instanceColor } = instancedMesh;
  10609. super( count, instanceMatrix, instanceColor );
  10610. /**
  10611. * A reference to the instanced mesh.
  10612. *
  10613. * @type {InstancedMesh}
  10614. */
  10615. this.instancedMesh = instancedMesh;
  10616. }
  10617. }
  10618. /**
  10619. * TSL function for creating an instanced mesh node.
  10620. *
  10621. * @tsl
  10622. * @function
  10623. * @param {InstancedMesh} instancedMesh - The instancedMesh.
  10624. * @returns {InstancedMeshNode}
  10625. */
  10626. const instancedMesh = /*@__PURE__*/ nodeProxy( InstancedMeshNode ).setParameterLength( 1 );
  10627. /**
  10628. * This node implements the vertex shader logic which is required
  10629. * when rendering 3D objects via batching. `BatchNode` must be used
  10630. * with instances of {@link BatchedMesh}.
  10631. *
  10632. * @augments Node
  10633. */
  10634. class BatchNode extends Node {
  10635. static get type() {
  10636. return 'BatchNode';
  10637. }
  10638. /**
  10639. * Constructs a new batch node.
  10640. *
  10641. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  10642. */
  10643. constructor( batchMesh ) {
  10644. super( 'void' );
  10645. /**
  10646. * A reference to batched mesh.
  10647. *
  10648. * @type {BatchedMesh}
  10649. */
  10650. this.batchMesh = batchMesh;
  10651. /**
  10652. * The batching index node.
  10653. *
  10654. * @type {?IndexNode}
  10655. * @default null
  10656. */
  10657. this.batchingIdNode = null;
  10658. }
  10659. /**
  10660. * Setups the internal buffers and nodes and assigns the transformed vertex data
  10661. * to predefined node variables for accumulation. That follows the same patterns
  10662. * like with morph and skinning nodes.
  10663. *
  10664. * @param {NodeBuilder} builder - The current node builder.
  10665. */
  10666. setup( builder ) {
  10667. if ( this.batchingIdNode === null ) {
  10668. if ( builder.getDrawIndex() === null ) {
  10669. this.batchingIdNode = instanceIndex;
  10670. } else {
  10671. this.batchingIdNode = drawIndex;
  10672. }
  10673. }
  10674. const getIndirectIndex = Fn( ( [ id ] ) => {
  10675. const size = int( textureSize( textureLoad( this.batchMesh._indirectTexture ), 0 ).x );
  10676. const x = int( id ).mod( size );
  10677. const y = int( id ).div( size );
  10678. return textureLoad( this.batchMesh._indirectTexture, ivec2( x, y ) ).x;
  10679. } ).setLayout( {
  10680. name: 'getIndirectIndex',
  10681. type: 'uint',
  10682. inputs: [
  10683. { name: 'id', type: 'int' }
  10684. ]
  10685. } );
  10686. const indirectId = getIndirectIndex( int( this.batchingIdNode ) );
  10687. const matricesTexture = this.batchMesh._matricesTexture;
  10688. const size = int( textureSize( textureLoad( matricesTexture ), 0 ).x );
  10689. const j = float( indirectId ).mul( 4 ).toInt().toVar();
  10690. const x = j.mod( size );
  10691. const y = j.div( size );
  10692. const batchingMatrix = mat4(
  10693. textureLoad( matricesTexture, ivec2( x, y ) ),
  10694. textureLoad( matricesTexture, ivec2( x.add( 1 ), y ) ),
  10695. textureLoad( matricesTexture, ivec2( x.add( 2 ), y ) ),
  10696. textureLoad( matricesTexture, ivec2( x.add( 3 ), y ) )
  10697. );
  10698. const colorsTexture = this.batchMesh._colorsTexture;
  10699. if ( colorsTexture !== null ) {
  10700. const getBatchingColor = Fn( ( [ id ] ) => {
  10701. const size = int( textureSize( textureLoad( colorsTexture ), 0 ).x );
  10702. const j = id;
  10703. const x = j.mod( size );
  10704. const y = j.div( size );
  10705. return textureLoad( colorsTexture, ivec2( x, y ) ).rgb;
  10706. } ).setLayout( {
  10707. name: 'getBatchingColor',
  10708. type: 'vec3',
  10709. inputs: [
  10710. { name: 'id', type: 'int' }
  10711. ]
  10712. } );
  10713. const color = getBatchingColor( indirectId );
  10714. varyingProperty( 'vec3', 'vBatchColor' ).assign( color );
  10715. }
  10716. const bm = mat3( batchingMatrix );
  10717. positionLocal.assign( batchingMatrix.mul( positionLocal ) );
  10718. const transformedNormal = normalLocal.div( vec3( bm[ 0 ].dot( bm[ 0 ] ), bm[ 1 ].dot( bm[ 1 ] ), bm[ 2 ].dot( bm[ 2 ] ) ) );
  10719. const batchingNormal = bm.mul( transformedNormal ).xyz;
  10720. normalLocal.assign( batchingNormal );
  10721. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  10722. tangentLocal.mulAssign( bm );
  10723. }
  10724. }
  10725. }
  10726. /**
  10727. * TSL function for creating a batch node.
  10728. *
  10729. * @tsl
  10730. * @function
  10731. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  10732. * @returns {BatchNode}
  10733. */
  10734. const batch = /*@__PURE__*/ nodeProxy( BatchNode ).setParameterLength( 1 );
  10735. /**
  10736. * This class enables element access on instances of {@link StorageBufferNode}.
  10737. * In most cases, it is indirectly used when accessing elements with the
  10738. * {@link StorageBufferNode#element} method.
  10739. *
  10740. * ```js
  10741. * const position = positionStorage.element( instanceIndex );
  10742. * ```
  10743. *
  10744. * @augments ArrayElementNode
  10745. */
  10746. class StorageArrayElementNode extends ArrayElementNode {
  10747. static get type() {
  10748. return 'StorageArrayElementNode';
  10749. }
  10750. /**
  10751. * Constructs storage buffer element node.
  10752. *
  10753. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  10754. * @param {Node} indexNode - The index node that defines the element access.
  10755. */
  10756. constructor( storageBufferNode, indexNode ) {
  10757. super( storageBufferNode, indexNode );
  10758. /**
  10759. * This flag can be used for type testing.
  10760. *
  10761. * @type {boolean}
  10762. * @readonly
  10763. * @default true
  10764. */
  10765. this.isStorageArrayElementNode = true;
  10766. }
  10767. /**
  10768. * The storage buffer node.
  10769. *
  10770. * @param {Node} value
  10771. * @type {StorageBufferNode}
  10772. */
  10773. set storageBufferNode( value ) {
  10774. this.node = value;
  10775. }
  10776. get storageBufferNode() {
  10777. return this.node;
  10778. }
  10779. getMemberType( builder, name ) {
  10780. const structTypeNode = this.storageBufferNode.structTypeNode;
  10781. if ( structTypeNode ) {
  10782. return structTypeNode.getMemberType( builder, name );
  10783. }
  10784. return 'void';
  10785. }
  10786. setup( builder ) {
  10787. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  10788. if ( this.node.isPBO === true ) {
  10789. builder.setupPBO( this.node );
  10790. }
  10791. }
  10792. return super.setup( builder );
  10793. }
  10794. generate( builder, output ) {
  10795. let snippet;
  10796. const isAssignContext = builder.context.assign;
  10797. //
  10798. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  10799. if ( this.node.isPBO === true && isAssignContext !== true && ( this.node.value.isInstancedBufferAttribute || builder.shaderStage !== 'compute' ) ) {
  10800. snippet = builder.generatePBO( this );
  10801. } else {
  10802. snippet = this.node.build( builder );
  10803. }
  10804. } else {
  10805. snippet = super.generate( builder );
  10806. }
  10807. if ( isAssignContext !== true ) {
  10808. const type = this.getNodeType( builder );
  10809. snippet = builder.format( snippet, type, output );
  10810. }
  10811. return snippet;
  10812. }
  10813. }
  10814. /**
  10815. * TSL function for creating a storage element node.
  10816. *
  10817. * @tsl
  10818. * @function
  10819. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  10820. * @param {Node} indexNode - The index node that defines the element access.
  10821. * @returns {StorageArrayElementNode}
  10822. */
  10823. const storageElement = /*@__PURE__*/ nodeProxy( StorageArrayElementNode ).setParameterLength( 2 );
  10824. /**
  10825. * This node is used in context of compute shaders and allows to define a
  10826. * storage buffer for data. A typical workflow is to create instances of
  10827. * this node with the convenience functions `attributeArray()` or `instancedArray()`,
  10828. * setup up a compute shader that writes into the buffers and then convert
  10829. * the storage buffers to attribute nodes for rendering.
  10830. *
  10831. * ```js
  10832. * const positionBuffer = instancedArray( particleCount, 'vec3' ); // the storage buffer node
  10833. *
  10834. * const computeInit = Fn( () => { // the compute shader
  10835. *
  10836. * const position = positionBuffer.element( instanceIndex );
  10837. *
  10838. * // compute position data
  10839. *
  10840. * position.x = 1;
  10841. * position.y = 1;
  10842. * position.z = 1;
  10843. *
  10844. * } )().compute( particleCount );
  10845. *
  10846. * const particleMaterial = new THREE.SpriteNodeMaterial();
  10847. * particleMaterial.positionNode = positionBuffer.toAttribute();
  10848. *
  10849. * renderer.computeAsync( computeInit );
  10850. *
  10851. * ```
  10852. *
  10853. * @augments BufferNode
  10854. */
  10855. class StorageBufferNode extends BufferNode {
  10856. static get type() {
  10857. return 'StorageBufferNode';
  10858. }
  10859. /**
  10860. * Constructs a new storage buffer node.
  10861. *
  10862. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  10863. * @param {?(string|Struct)} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  10864. * @param {number} [bufferCount=0] - The buffer count.
  10865. */
  10866. constructor( value, bufferType = null, bufferCount = 0 ) {
  10867. let nodeType, structTypeNode = null;
  10868. if ( bufferType && bufferType.isStruct ) {
  10869. nodeType = 'struct';
  10870. structTypeNode = bufferType.layout;
  10871. if ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) {
  10872. bufferCount = value.count;
  10873. }
  10874. } else if ( bufferType === null && ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) ) {
  10875. nodeType = getTypeFromLength( value.itemSize );
  10876. bufferCount = value.count;
  10877. } else {
  10878. nodeType = bufferType;
  10879. }
  10880. super( value, nodeType, bufferCount );
  10881. /**
  10882. * This flag can be used for type testing.
  10883. *
  10884. * @type {boolean}
  10885. * @readonly
  10886. * @default true
  10887. */
  10888. this.isStorageBufferNode = true;
  10889. /**
  10890. * The buffer struct type.
  10891. *
  10892. * @type {?StructTypeNode}
  10893. * @default null
  10894. */
  10895. this.structTypeNode = structTypeNode;
  10896. /**
  10897. * The access type of the texture node.
  10898. *
  10899. * @type {string}
  10900. * @default 'readWrite'
  10901. */
  10902. this.access = NodeAccess.READ_WRITE;
  10903. /**
  10904. * Whether the node is atomic or not.
  10905. *
  10906. * @type {boolean}
  10907. * @default false
  10908. */
  10909. this.isAtomic = false;
  10910. /**
  10911. * Whether the node represents a PBO or not.
  10912. * Only relevant for WebGL.
  10913. *
  10914. * @type {boolean}
  10915. * @default false
  10916. */
  10917. this.isPBO = false;
  10918. /**
  10919. * A reference to the internal buffer attribute node.
  10920. *
  10921. * @type {?BufferAttributeNode}
  10922. * @default null
  10923. */
  10924. this._attribute = null;
  10925. /**
  10926. * A reference to the internal varying node.
  10927. *
  10928. * @type {?VaryingNode}
  10929. * @default null
  10930. */
  10931. this._varying = null;
  10932. /**
  10933. * `StorageBufferNode` sets this property to `true` by default.
  10934. *
  10935. * @type {boolean}
  10936. * @default true
  10937. */
  10938. this.global = true;
  10939. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  10940. // TODO: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  10941. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  10942. else value.isStorageBufferAttribute = true;
  10943. }
  10944. }
  10945. /**
  10946. * This method is overwritten since the buffer data might be shared
  10947. * and thus the hash should be shared as well.
  10948. *
  10949. * @param {NodeBuilder} builder - The current node builder.
  10950. * @return {string} The hash.
  10951. */
  10952. getHash( builder ) {
  10953. if ( this.bufferCount === 0 ) {
  10954. let bufferData = builder.globalCache.getData( this.value );
  10955. if ( bufferData === undefined ) {
  10956. bufferData = {
  10957. node: this
  10958. };
  10959. builder.globalCache.setData( this.value, bufferData );
  10960. }
  10961. return bufferData.node.uuid;
  10962. }
  10963. return this.uuid;
  10964. }
  10965. /**
  10966. * Overwrites the default implementation to return a fixed value `'indirectStorageBuffer'` or `'storageBuffer'`.
  10967. *
  10968. * @param {NodeBuilder} builder - The current node builder.
  10969. * @return {string} The input type.
  10970. */
  10971. getInputType( /*builder*/ ) {
  10972. return this.value.isIndirectStorageBufferAttribute ? 'indirectStorageBuffer' : 'storageBuffer';
  10973. }
  10974. /**
  10975. * Enables element access with the given index node.
  10976. *
  10977. * @param {IndexNode} indexNode - The index node.
  10978. * @return {StorageArrayElementNode} A node representing the element access.
  10979. */
  10980. element( indexNode ) {
  10981. return storageElement( this, indexNode );
  10982. }
  10983. /**
  10984. * Defines whether this node is a PBO or not. Only relevant for WebGL.
  10985. *
  10986. * @param {boolean} value - The value so set.
  10987. * @return {StorageBufferNode} A reference to this node.
  10988. */
  10989. setPBO( value ) {
  10990. this.isPBO = value;
  10991. return this;
  10992. }
  10993. /**
  10994. * Returns the `isPBO` value.
  10995. *
  10996. * @return {boolean} Whether the node represents a PBO or not.
  10997. */
  10998. getPBO() {
  10999. return this.isPBO;
  11000. }
  11001. /**
  11002. * Defines the node access.
  11003. *
  11004. * @param {string} value - The node access.
  11005. * @return {StorageBufferNode} A reference to this node.
  11006. */
  11007. setAccess( value ) {
  11008. this.access = value;
  11009. return this;
  11010. }
  11011. /**
  11012. * Convenience method for configuring a read-only node access.
  11013. *
  11014. * @return {StorageBufferNode} A reference to this node.
  11015. */
  11016. toReadOnly() {
  11017. return this.setAccess( NodeAccess.READ_ONLY );
  11018. }
  11019. /**
  11020. * Defines whether the node is atomic or not.
  11021. *
  11022. * @param {boolean} value - The atomic flag.
  11023. * @return {StorageBufferNode} A reference to this node.
  11024. */
  11025. setAtomic( value ) {
  11026. this.isAtomic = value;
  11027. return this;
  11028. }
  11029. /**
  11030. * Convenience method for making this node atomic.
  11031. *
  11032. * @return {StorageBufferNode} A reference to this node.
  11033. */
  11034. toAtomic() {
  11035. return this.setAtomic( true );
  11036. }
  11037. /**
  11038. * Returns attribute data for this storage buffer node.
  11039. *
  11040. * @return {{attribute: BufferAttributeNode, varying: VaryingNode}} The attribute data.
  11041. */
  11042. getAttributeData() {
  11043. if ( this._attribute === null ) {
  11044. this._attribute = bufferAttribute( this.value );
  11045. this._varying = varying( this._attribute );
  11046. }
  11047. return {
  11048. attribute: this._attribute,
  11049. varying: this._varying
  11050. };
  11051. }
  11052. /**
  11053. * This method is overwritten since the node type from the availability of storage buffers
  11054. * and the attribute data.
  11055. *
  11056. * @param {NodeBuilder} builder - The current node builder.
  11057. * @return {string} The node type.
  11058. */
  11059. getNodeType( builder ) {
  11060. if ( this.structTypeNode !== null ) {
  11061. return this.structTypeNode.getNodeType( builder );
  11062. }
  11063. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  11064. return super.getNodeType( builder );
  11065. }
  11066. const { attribute } = this.getAttributeData();
  11067. return attribute.getNodeType( builder );
  11068. }
  11069. /**
  11070. * Returns the type of a member of the struct.
  11071. *
  11072. * @param {NodeBuilder} builder - The current node builder.
  11073. * @param {string} name - The name of the member.
  11074. * @return {string} The type of the member.
  11075. */
  11076. getMemberType( builder, name ) {
  11077. if ( this.structTypeNode !== null ) {
  11078. return this.structTypeNode.getMemberType( builder, name );
  11079. }
  11080. return 'void';
  11081. }
  11082. /**
  11083. * Generates the code snippet of the storage buffer node.
  11084. *
  11085. * @param {NodeBuilder} builder - The current node builder.
  11086. * @return {string} The generated code snippet.
  11087. */
  11088. generate( builder ) {
  11089. if ( this.structTypeNode !== null ) this.structTypeNode.build( builder );
  11090. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  11091. return super.generate( builder );
  11092. }
  11093. const { attribute, varying } = this.getAttributeData();
  11094. const output = varying.build( builder );
  11095. builder.registerTransform( output, attribute );
  11096. return output;
  11097. }
  11098. }
  11099. /**
  11100. * TSL function for creating a storage buffer node.
  11101. *
  11102. * @tsl
  11103. * @function
  11104. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  11105. * @param {?(string|Struct)} [type=null] - The buffer type (e.g. `'vec3'`).
  11106. * @param {number} [count=0] - The buffer count.
  11107. * @returns {StorageBufferNode}
  11108. */
  11109. const storage = ( value, type = null, count = 0 ) => nodeObject( new StorageBufferNode( value, type, count ) );
  11110. /**
  11111. * @tsl
  11112. * @function
  11113. * @deprecated since r171. Use `storage().setPBO( true )` instead.
  11114. *
  11115. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  11116. * @param {?string} type - The buffer type (e.g. `'vec3'`).
  11117. * @param {number} count - The buffer count.
  11118. * @returns {StorageBufferNode}
  11119. */
  11120. const storageObject = ( value, type, count ) => { // @deprecated, r171
  11121. console.warn( 'THREE.TSL: "storageObject()" is deprecated. Use "storage().setPBO( true )" instead.' );
  11122. return storage( value, type, count ).setPBO( true );
  11123. };
  11124. const _frameId = new WeakMap();
  11125. /**
  11126. * This node implements the vertex transformation shader logic which is required
  11127. * for skinning/skeletal animation.
  11128. *
  11129. * @augments Node
  11130. */
  11131. class SkinningNode extends Node {
  11132. static get type() {
  11133. return 'SkinningNode';
  11134. }
  11135. /**
  11136. * Constructs a new skinning node.
  11137. *
  11138. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  11139. */
  11140. constructor( skinnedMesh ) {
  11141. super( 'void' );
  11142. /**
  11143. * The skinned mesh.
  11144. *
  11145. * @type {SkinnedMesh}
  11146. */
  11147. this.skinnedMesh = skinnedMesh;
  11148. /**
  11149. * The update type overwritten since skinning nodes are updated per object.
  11150. *
  11151. * @type {string}
  11152. */
  11153. this.updateType = NodeUpdateType.OBJECT;
  11154. //
  11155. /**
  11156. * The skin index attribute.
  11157. *
  11158. * @type {AttributeNode}
  11159. */
  11160. this.skinIndexNode = attribute( 'skinIndex', 'uvec4' );
  11161. /**
  11162. * The skin weight attribute.
  11163. *
  11164. * @type {AttributeNode}
  11165. */
  11166. this.skinWeightNode = attribute( 'skinWeight', 'vec4' );
  11167. /**
  11168. * The bind matrix node.
  11169. *
  11170. * @type {Node<mat4>}
  11171. */
  11172. this.bindMatrixNode = reference( 'bindMatrix', 'mat4' );
  11173. /**
  11174. * The bind matrix inverse node.
  11175. *
  11176. * @type {Node<mat4>}
  11177. */
  11178. this.bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' );
  11179. /**
  11180. * The bind matrices as a uniform buffer node.
  11181. *
  11182. * @type {Node}
  11183. */
  11184. this.boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  11185. /**
  11186. * The current vertex position in local space.
  11187. *
  11188. * @type {Node<vec3>}
  11189. */
  11190. this.positionNode = positionLocal;
  11191. /**
  11192. * The result of vertex position in local space.
  11193. *
  11194. * @type {Node<vec3>}
  11195. */
  11196. this.toPositionNode = positionLocal;
  11197. /**
  11198. * The previous bind matrices as a uniform buffer node.
  11199. * Required for computing motion vectors.
  11200. *
  11201. * @type {?Node}
  11202. * @default null
  11203. */
  11204. this.previousBoneMatricesNode = null;
  11205. }
  11206. /**
  11207. * Transforms the given vertex position via skinning.
  11208. *
  11209. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  11210. * @param {Node<vec3>} [position=this.positionNode] - The vertex position in local space.
  11211. * @return {Node<vec3>} The transformed vertex position.
  11212. */
  11213. getSkinnedPosition( boneMatrices = this.boneMatricesNode, position = this.positionNode ) {
  11214. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  11215. const boneMatX = boneMatrices.element( skinIndexNode.x );
  11216. const boneMatY = boneMatrices.element( skinIndexNode.y );
  11217. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  11218. const boneMatW = boneMatrices.element( skinIndexNode.w );
  11219. // POSITION
  11220. const skinVertex = bindMatrixNode.mul( position );
  11221. const skinned = add(
  11222. boneMatX.mul( skinWeightNode.x ).mul( skinVertex ),
  11223. boneMatY.mul( skinWeightNode.y ).mul( skinVertex ),
  11224. boneMatZ.mul( skinWeightNode.z ).mul( skinVertex ),
  11225. boneMatW.mul( skinWeightNode.w ).mul( skinVertex )
  11226. );
  11227. return bindMatrixInverseNode.mul( skinned ).xyz;
  11228. }
  11229. /**
  11230. * Transforms the given vertex normal via skinning.
  11231. *
  11232. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  11233. * @param {Node<vec3>} [normal=normalLocal] - The vertex normal in local space.
  11234. * @return {Node<vec3>} The transformed vertex normal.
  11235. */
  11236. getSkinnedNormal( boneMatrices = this.boneMatricesNode, normal = normalLocal ) {
  11237. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  11238. const boneMatX = boneMatrices.element( skinIndexNode.x );
  11239. const boneMatY = boneMatrices.element( skinIndexNode.y );
  11240. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  11241. const boneMatW = boneMatrices.element( skinIndexNode.w );
  11242. // NORMAL
  11243. let skinMatrix = add(
  11244. skinWeightNode.x.mul( boneMatX ),
  11245. skinWeightNode.y.mul( boneMatY ),
  11246. skinWeightNode.z.mul( boneMatZ ),
  11247. skinWeightNode.w.mul( boneMatW )
  11248. );
  11249. skinMatrix = bindMatrixInverseNode.mul( skinMatrix ).mul( bindMatrixNode );
  11250. return skinMatrix.transformDirection( normal ).xyz;
  11251. }
  11252. /**
  11253. * Computes the transformed/skinned vertex position of the previous frame.
  11254. *
  11255. * @param {NodeBuilder} builder - The current node builder.
  11256. * @return {Node<vec3>} The skinned position from the previous frame.
  11257. */
  11258. getPreviousSkinnedPosition( builder ) {
  11259. const skinnedMesh = builder.object;
  11260. if ( this.previousBoneMatricesNode === null ) {
  11261. skinnedMesh.skeleton.previousBoneMatrices = new Float32Array( skinnedMesh.skeleton.boneMatrices );
  11262. this.previousBoneMatricesNode = referenceBuffer( 'skeleton.previousBoneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  11263. }
  11264. return this.getSkinnedPosition( this.previousBoneMatricesNode, positionPrevious );
  11265. }
  11266. /**
  11267. * Returns `true` if bone matrices from the previous frame are required. Relevant
  11268. * when computing motion vectors with {@link VelocityNode}.
  11269. *
  11270. * @param {NodeBuilder} builder - The current node builder.
  11271. * @return {boolean} Whether bone matrices from the previous frame are required or not.
  11272. */
  11273. needsPreviousBoneMatrices( builder ) {
  11274. const mrt = builder.renderer.getMRT();
  11275. return ( mrt && mrt.has( 'velocity' ) ) || getDataFromObject( builder.object ).useVelocity === true;
  11276. }
  11277. /**
  11278. * Setups the skinning node by assigning the transformed vertex data to predefined node variables.
  11279. *
  11280. * @param {NodeBuilder} builder - The current node builder.
  11281. * @return {Node<vec3>} The transformed vertex position.
  11282. */
  11283. setup( builder ) {
  11284. if ( this.needsPreviousBoneMatrices( builder ) ) {
  11285. positionPrevious.assign( this.getPreviousSkinnedPosition( builder ) );
  11286. }
  11287. const skinPosition = this.getSkinnedPosition();
  11288. if ( this.toPositionNode ) this.toPositionNode.assign( skinPosition );
  11289. //
  11290. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  11291. const skinNormal = this.getSkinnedNormal();
  11292. normalLocal.assign( skinNormal );
  11293. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  11294. tangentLocal.assign( skinNormal );
  11295. }
  11296. }
  11297. return skinPosition;
  11298. }
  11299. /**
  11300. * Generates the code snippet of the skinning node.
  11301. *
  11302. * @param {NodeBuilder} builder - The current node builder.
  11303. * @param {string} output - The current output.
  11304. * @return {string} The generated code snippet.
  11305. */
  11306. generate( builder, output ) {
  11307. if ( output !== 'void' ) {
  11308. return super.generate( builder, output );
  11309. }
  11310. }
  11311. /**
  11312. * Updates the state of the skinned mesh by updating the skeleton once per frame.
  11313. *
  11314. * @param {NodeFrame} frame - The current node frame.
  11315. */
  11316. update( frame ) {
  11317. const skeleton = frame.object && frame.object.skeleton ? frame.object.skeleton : this.skinnedMesh.skeleton;
  11318. if ( _frameId.get( skeleton ) === frame.frameId ) return;
  11319. _frameId.set( skeleton, frame.frameId );
  11320. if ( this.previousBoneMatricesNode !== null ) skeleton.previousBoneMatrices.set( skeleton.boneMatrices );
  11321. skeleton.update();
  11322. }
  11323. }
  11324. /**
  11325. * TSL function for creating a skinning node.
  11326. *
  11327. * @tsl
  11328. * @function
  11329. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  11330. * @returns {SkinningNode}
  11331. */
  11332. const skinning = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh ) );
  11333. /**
  11334. * TSL function for computing skinning.
  11335. *
  11336. * @tsl
  11337. * @function
  11338. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  11339. * @param {Node<vec3>} [toPosition=null] - The target position.
  11340. * @returns {SkinningNode}
  11341. */
  11342. const computeSkinning = ( skinnedMesh, toPosition = null ) => {
  11343. const node = new SkinningNode( skinnedMesh );
  11344. node.positionNode = storage( new InstancedBufferAttribute( skinnedMesh.geometry.getAttribute( 'position' ).array, 3 ), 'vec3' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  11345. node.skinIndexNode = storage( new InstancedBufferAttribute( new Uint32Array( skinnedMesh.geometry.getAttribute( 'skinIndex' ).array ), 4 ), 'uvec4' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  11346. node.skinWeightNode = storage( new InstancedBufferAttribute( skinnedMesh.geometry.getAttribute( 'skinWeight' ).array, 4 ), 'vec4' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  11347. node.bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' );
  11348. node.bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' );
  11349. node.boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length );
  11350. node.toPositionNode = toPosition;
  11351. return nodeObject( node );
  11352. };
  11353. /**
  11354. * This module offers a variety of ways to implement loops in TSL. In it's basic form it's:
  11355. * ```js
  11356. * Loop( count, ( { i } ) => {
  11357. *
  11358. * } );
  11359. * ```
  11360. * However, it is also possible to define a start and end ranges, data types and loop conditions:
  11361. * ```js
  11362. * Loop( { start: int( 0 ), end: int( 10 ), type: 'int', condition: '<' }, ( { i } ) => {
  11363. *
  11364. * } );
  11365. *```
  11366. * Nested loops can be defined in a compacted form:
  11367. * ```js
  11368. * Loop( 10, 5, ( { i, j } ) => {
  11369. *
  11370. * } );
  11371. * ```
  11372. * Loops that should run backwards can be defined like so:
  11373. * ```js
  11374. * Loop( { start: 10 }, () => {} );
  11375. * ```
  11376. * It is possible to execute with boolean values, similar to the `while` syntax.
  11377. * ```js
  11378. * const value = float( 0 ).toVar();
  11379. *
  11380. * Loop( value.lessThan( 10 ), () => {
  11381. *
  11382. * value.addAssign( 1 );
  11383. *
  11384. * } );
  11385. * ```
  11386. * The module also provides `Break()` and `Continue()` TSL expression for loop control.
  11387. * @augments Node
  11388. */
  11389. class LoopNode extends Node {
  11390. static get type() {
  11391. return 'LoopNode';
  11392. }
  11393. /**
  11394. * Constructs a new loop node.
  11395. *
  11396. * @param {Array<any>} params - Depending on the loop type, array holds different parameterization values for the loop.
  11397. */
  11398. constructor( params = [] ) {
  11399. super();
  11400. this.params = params;
  11401. }
  11402. /**
  11403. * Returns a loop variable name based on an index. The pattern is
  11404. * `0` = `i`, `1`= `j`, `2`= `k` and so on.
  11405. *
  11406. * @param {number} index - The index.
  11407. * @return {string} The loop variable name.
  11408. */
  11409. getVarName( index ) {
  11410. return String.fromCharCode( 'i'.charCodeAt( 0 ) + index );
  11411. }
  11412. /**
  11413. * Returns properties about this node.
  11414. *
  11415. * @param {NodeBuilder} builder - The current node builder.
  11416. * @return {Object} The node properties.
  11417. */
  11418. getProperties( builder ) {
  11419. const properties = builder.getNodeProperties( this );
  11420. if ( properties.stackNode !== undefined ) return properties;
  11421. //
  11422. const inputs = {};
  11423. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  11424. const param = this.params[ i ];
  11425. const name = ( param.isNode !== true && param.name ) || this.getVarName( i );
  11426. const type = ( param.isNode !== true && param.type ) || 'int';
  11427. inputs[ name ] = expression( name, type );
  11428. }
  11429. const stack = builder.addStack(); // TODO: cache() it
  11430. properties.returnsNode = this.params[ this.params.length - 1 ]( inputs, builder );
  11431. properties.stackNode = stack;
  11432. const baseParam = this.params[ 0 ];
  11433. if ( baseParam.isNode !== true && typeof baseParam.update === 'function' ) {
  11434. properties.updateNode = Fn( this.params[ 0 ].update )( inputs );
  11435. }
  11436. builder.removeStack();
  11437. return properties;
  11438. }
  11439. /**
  11440. * This method is overwritten since the node type is inferred based on the loop configuration.
  11441. *
  11442. * @param {NodeBuilder} builder - The current node builder.
  11443. * @return {string} The node type.
  11444. */
  11445. getNodeType( builder ) {
  11446. const { returnsNode } = this.getProperties( builder );
  11447. return returnsNode ? returnsNode.getNodeType( builder ) : 'void';
  11448. }
  11449. setup( builder ) {
  11450. // setup properties
  11451. this.getProperties( builder );
  11452. }
  11453. generate( builder ) {
  11454. const properties = this.getProperties( builder );
  11455. const params = this.params;
  11456. const stackNode = properties.stackNode;
  11457. for ( let i = 0, l = params.length - 1; i < l; i ++ ) {
  11458. const param = params[ i ];
  11459. let isWhile = false, start = null, end = null, name = null, type = null, condition = null, update = null;
  11460. if ( param.isNode ) {
  11461. if ( param.getNodeType( builder ) === 'bool' ) {
  11462. isWhile = true;
  11463. type = 'bool';
  11464. end = param.build( builder, type );
  11465. } else {
  11466. type = 'int';
  11467. name = this.getVarName( i );
  11468. start = '0';
  11469. end = param.build( builder, type );
  11470. condition = '<';
  11471. }
  11472. } else {
  11473. type = param.type || 'int';
  11474. name = param.name || this.getVarName( i );
  11475. start = param.start;
  11476. end = param.end;
  11477. condition = param.condition;
  11478. update = param.update;
  11479. if ( typeof start === 'number' ) start = builder.generateConst( type, start );
  11480. else if ( start && start.isNode ) start = start.build( builder, type );
  11481. if ( typeof end === 'number' ) end = builder.generateConst( type, end );
  11482. else if ( end && end.isNode ) end = end.build( builder, type );
  11483. if ( start !== undefined && end === undefined ) {
  11484. start = start + ' - 1';
  11485. end = '0';
  11486. condition = '>=';
  11487. } else if ( end !== undefined && start === undefined ) {
  11488. start = '0';
  11489. condition = '<';
  11490. }
  11491. if ( condition === undefined ) {
  11492. if ( Number( start ) > Number( end ) ) {
  11493. condition = '>=';
  11494. } else {
  11495. condition = '<';
  11496. }
  11497. }
  11498. }
  11499. let loopSnippet;
  11500. if ( isWhile ) {
  11501. loopSnippet = `while ( ${ end } )`;
  11502. } else {
  11503. const internalParam = { start, end};
  11504. //
  11505. const startSnippet = internalParam.start;
  11506. const endSnippet = internalParam.end;
  11507. let updateSnippet;
  11508. const deltaOperator = () => condition.includes( '<' ) ? '+=' : '-=';
  11509. if ( update !== undefined && update !== null ) {
  11510. switch ( typeof update ) {
  11511. case 'function':
  11512. const flow = builder.flowStagesNode( properties.updateNode, 'void' );
  11513. const snippet = flow.code.replace( /\t|;/g, '' );
  11514. updateSnippet = snippet;
  11515. break;
  11516. case 'number':
  11517. updateSnippet = name + ' ' + deltaOperator() + ' ' + builder.generateConst( type, update );
  11518. break;
  11519. case 'string':
  11520. updateSnippet = name + ' ' + update;
  11521. break;
  11522. default:
  11523. if ( update.isNode ) {
  11524. updateSnippet = name + ' ' + deltaOperator() + ' ' + update.build( builder );
  11525. } else {
  11526. console.error( 'THREE.TSL: \'Loop( { update: ... } )\' is not a function, string or number.' );
  11527. updateSnippet = 'break /* invalid update */';
  11528. }
  11529. }
  11530. } else {
  11531. if ( type === 'int' || type === 'uint' ) {
  11532. update = condition.includes( '<' ) ? '++' : '--';
  11533. } else {
  11534. update = deltaOperator() + ' 1.';
  11535. }
  11536. updateSnippet = name + ' ' + update;
  11537. }
  11538. const declarationSnippet = builder.getVar( type, name ) + ' = ' + startSnippet;
  11539. const conditionalSnippet = name + ' ' + condition + ' ' + endSnippet;
  11540. loopSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`;
  11541. }
  11542. builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + loopSnippet + ' {\n\n' ).addFlowTab();
  11543. }
  11544. const stackSnippet = stackNode.build( builder, 'void' );
  11545. const returnsSnippet = properties.returnsNode ? properties.returnsNode.build( builder ) : '';
  11546. builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet );
  11547. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  11548. builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab();
  11549. }
  11550. builder.addFlowTab();
  11551. return returnsSnippet;
  11552. }
  11553. }
  11554. /**
  11555. * TSL function for creating a loop node.
  11556. *
  11557. * @tsl
  11558. * @function
  11559. * @param {...any} params - A list of parameters.
  11560. * @returns {LoopNode}
  11561. */
  11562. const Loop = ( ...params ) => nodeObject( new LoopNode( nodeArray( params, 'int' ) ) ).toStack();
  11563. /**
  11564. * TSL function for creating a `Continue()` expression.
  11565. *
  11566. * @tsl
  11567. * @function
  11568. * @returns {ExpressionNode}
  11569. */
  11570. const Continue = () => expression( 'continue' ).toStack();
  11571. /**
  11572. * TSL function for creating a `Break()` expression.
  11573. *
  11574. * @tsl
  11575. * @function
  11576. * @returns {ExpressionNode}
  11577. */
  11578. const Break = () => expression( 'break' ).toStack();
  11579. const _morphTextures = /*@__PURE__*/ new WeakMap();
  11580. const _morphVec4 = /*@__PURE__*/ new Vector4();
  11581. const getMorph = /*@__PURE__*/ Fn( ( { bufferMap, influence, stride, width, depth, offset } ) => {
  11582. const texelIndex = int( vertexIndex ).mul( stride ).add( offset );
  11583. const y = texelIndex.div( width );
  11584. const x = texelIndex.sub( y.mul( width ) );
  11585. const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth ).xyz;
  11586. return bufferAttrib.mul( influence );
  11587. } );
  11588. function getEntry( geometry ) {
  11589. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  11590. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  11591. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  11592. // instead of using attributes, the WebGL 2 code path encodes morph targets
  11593. // into an array of data textures. Each layer represents a single morph target.
  11594. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  11595. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  11596. let entry = _morphTextures.get( geometry );
  11597. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  11598. if ( entry !== undefined ) entry.texture.dispose();
  11599. const morphTargets = geometry.morphAttributes.position || [];
  11600. const morphNormals = geometry.morphAttributes.normal || [];
  11601. const morphColors = geometry.morphAttributes.color || [];
  11602. let vertexDataCount = 0;
  11603. if ( hasMorphPosition === true ) vertexDataCount = 1;
  11604. if ( hasMorphNormals === true ) vertexDataCount = 2;
  11605. if ( hasMorphColors === true ) vertexDataCount = 3;
  11606. let width = geometry.attributes.position.count * vertexDataCount;
  11607. let height = 1;
  11608. const maxTextureSize = 4096; // @TODO: Use 'capabilities.maxTextureSize'
  11609. if ( width > maxTextureSize ) {
  11610. height = Math.ceil( width / maxTextureSize );
  11611. width = maxTextureSize;
  11612. }
  11613. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  11614. const bufferTexture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  11615. bufferTexture.type = FloatType;
  11616. bufferTexture.needsUpdate = true;
  11617. // fill buffer
  11618. const vertexDataStride = vertexDataCount * 4;
  11619. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  11620. const morphTarget = morphTargets[ i ];
  11621. const morphNormal = morphNormals[ i ];
  11622. const morphColor = morphColors[ i ];
  11623. const offset = width * height * 4 * i;
  11624. for ( let j = 0; j < morphTarget.count; j ++ ) {
  11625. const stride = j * vertexDataStride;
  11626. if ( hasMorphPosition === true ) {
  11627. _morphVec4.fromBufferAttribute( morphTarget, j );
  11628. buffer[ offset + stride + 0 ] = _morphVec4.x;
  11629. buffer[ offset + stride + 1 ] = _morphVec4.y;
  11630. buffer[ offset + stride + 2 ] = _morphVec4.z;
  11631. buffer[ offset + stride + 3 ] = 0;
  11632. }
  11633. if ( hasMorphNormals === true ) {
  11634. _morphVec4.fromBufferAttribute( morphNormal, j );
  11635. buffer[ offset + stride + 4 ] = _morphVec4.x;
  11636. buffer[ offset + stride + 5 ] = _morphVec4.y;
  11637. buffer[ offset + stride + 6 ] = _morphVec4.z;
  11638. buffer[ offset + stride + 7 ] = 0;
  11639. }
  11640. if ( hasMorphColors === true ) {
  11641. _morphVec4.fromBufferAttribute( morphColor, j );
  11642. buffer[ offset + stride + 8 ] = _morphVec4.x;
  11643. buffer[ offset + stride + 9 ] = _morphVec4.y;
  11644. buffer[ offset + stride + 10 ] = _morphVec4.z;
  11645. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? _morphVec4.w : 1;
  11646. }
  11647. }
  11648. }
  11649. entry = {
  11650. count: morphTargetsCount,
  11651. texture: bufferTexture,
  11652. stride: vertexDataCount,
  11653. size: new Vector2( width, height )
  11654. };
  11655. _morphTextures.set( geometry, entry );
  11656. function disposeTexture() {
  11657. bufferTexture.dispose();
  11658. _morphTextures.delete( geometry );
  11659. geometry.removeEventListener( 'dispose', disposeTexture );
  11660. }
  11661. geometry.addEventListener( 'dispose', disposeTexture );
  11662. }
  11663. return entry;
  11664. }
  11665. /**
  11666. * This node implements the vertex transformation shader logic which is required
  11667. * for morph target animation.
  11668. *
  11669. * @augments Node
  11670. */
  11671. class MorphNode extends Node {
  11672. static get type() {
  11673. return 'MorphNode';
  11674. }
  11675. /**
  11676. * Constructs a new morph node.
  11677. *
  11678. * @param {Mesh} mesh - The mesh holding the morph targets.
  11679. */
  11680. constructor( mesh ) {
  11681. super( 'void' );
  11682. /**
  11683. * The mesh holding the morph targets.
  11684. *
  11685. * @type {Mesh}
  11686. */
  11687. this.mesh = mesh;
  11688. /**
  11689. * A uniform node which represents the morph base influence value.
  11690. *
  11691. * @type {UniformNode<float>}
  11692. */
  11693. this.morphBaseInfluence = uniform( 1 );
  11694. /**
  11695. * The update type overwritten since morph nodes are updated per object.
  11696. *
  11697. * @type {string}
  11698. */
  11699. this.updateType = NodeUpdateType.OBJECT;
  11700. }
  11701. /**
  11702. * Setups the morph node by assigning the transformed vertex data to predefined node variables.
  11703. *
  11704. * @param {NodeBuilder} builder - The current node builder.
  11705. */
  11706. setup( builder ) {
  11707. const { geometry } = builder;
  11708. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  11709. const hasMorphNormals = geometry.hasAttribute( 'normal' ) && geometry.morphAttributes.normal !== undefined;
  11710. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  11711. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  11712. // nodes
  11713. const { texture: bufferMap, stride, size } = getEntry( geometry );
  11714. if ( hasMorphPosition === true ) positionLocal.mulAssign( this.morphBaseInfluence );
  11715. if ( hasMorphNormals === true ) normalLocal.mulAssign( this.morphBaseInfluence );
  11716. const width = int( size.width );
  11717. Loop( morphTargetsCount, ( { i } ) => {
  11718. const influence = float( 0 ).toVar();
  11719. if ( this.mesh.count > 1 && ( this.mesh.morphTexture !== null && this.mesh.morphTexture !== undefined ) ) {
  11720. influence.assign( textureLoad( this.mesh.morphTexture, ivec2( int( i ).add( 1 ), int( instanceIndex ) ) ).r );
  11721. } else {
  11722. influence.assign( reference( 'morphTargetInfluences', 'float' ).element( i ).toVar() );
  11723. }
  11724. If( influence.notEqual( 0 ), () => {
  11725. if ( hasMorphPosition === true ) {
  11726. positionLocal.addAssign( getMorph( {
  11727. bufferMap,
  11728. influence,
  11729. stride,
  11730. width,
  11731. depth: i,
  11732. offset: int( 0 )
  11733. } ) );
  11734. }
  11735. if ( hasMorphNormals === true ) {
  11736. normalLocal.addAssign( getMorph( {
  11737. bufferMap,
  11738. influence,
  11739. stride,
  11740. width,
  11741. depth: i,
  11742. offset: int( 1 )
  11743. } ) );
  11744. }
  11745. } );
  11746. } );
  11747. }
  11748. /**
  11749. * Updates the state of the morphed mesh by updating the base influence.
  11750. *
  11751. * @param {NodeFrame} frame - The current node frame.
  11752. */
  11753. update( /*frame*/ ) {
  11754. const morphBaseInfluence = this.morphBaseInfluence;
  11755. if ( this.mesh.geometry.morphTargetsRelative ) {
  11756. morphBaseInfluence.value = 1;
  11757. } else {
  11758. morphBaseInfluence.value = 1 - this.mesh.morphTargetInfluences.reduce( ( a, b ) => a + b, 0 );
  11759. }
  11760. }
  11761. }
  11762. /**
  11763. * TSL function for creating a morph node.
  11764. *
  11765. * @tsl
  11766. * @function
  11767. * @param {Mesh} mesh - The mesh holding the morph targets.
  11768. * @returns {MorphNode}
  11769. */
  11770. const morphReference = /*@__PURE__*/ nodeProxy( MorphNode ).setParameterLength( 1 );
  11771. /**
  11772. * Base class for lighting nodes.
  11773. *
  11774. * @augments Node
  11775. */
  11776. class LightingNode extends Node {
  11777. static get type() {
  11778. return 'LightingNode';
  11779. }
  11780. /**
  11781. * Constructs a new lighting node.
  11782. */
  11783. constructor() {
  11784. super( 'vec3' );
  11785. /**
  11786. * This flag can be used for type testing.
  11787. *
  11788. * @type {boolean}
  11789. * @readonly
  11790. * @default true
  11791. */
  11792. this.isLightingNode = true;
  11793. }
  11794. }
  11795. /**
  11796. * A generic class that can be used by nodes which contribute
  11797. * ambient occlusion to the scene. E.g. an ambient occlusion map
  11798. * node can be used as input for this module. Used in {@link NodeMaterial}.
  11799. *
  11800. * @augments LightingNode
  11801. */
  11802. class AONode extends LightingNode {
  11803. static get type() {
  11804. return 'AONode';
  11805. }
  11806. /**
  11807. * Constructs a new AO node.
  11808. *
  11809. * @param {?Node<float>} [aoNode=null] - The ambient occlusion node.
  11810. */
  11811. constructor( aoNode = null ) {
  11812. super();
  11813. /**
  11814. * The ambient occlusion node.
  11815. *
  11816. * @type {?Node<float>}
  11817. * @default null
  11818. */
  11819. this.aoNode = aoNode;
  11820. }
  11821. setup( builder ) {
  11822. builder.context.ambientOcclusion.mulAssign( this.aoNode );
  11823. }
  11824. }
  11825. /**
  11826. * `LightingContextNode` represents an extension of the {@link ContextNode} module
  11827. * by adding lighting specific context data. It represents the runtime context of
  11828. * {@link LightsNode}.
  11829. *
  11830. * @augments ContextNode
  11831. */
  11832. class LightingContextNode extends ContextNode {
  11833. static get type() {
  11834. return 'LightingContextNode';
  11835. }
  11836. /**
  11837. * Constructs a new lighting context node.
  11838. *
  11839. * @param {LightsNode} lightsNode - The lights node.
  11840. * @param {?LightingModel} [lightingModel=null] - The current lighting model.
  11841. * @param {?Node<vec3>} [backdropNode=null] - A backdrop node.
  11842. * @param {?Node<float>} [backdropAlphaNode=null] - A backdrop alpha node.
  11843. */
  11844. constructor( lightsNode, lightingModel = null, backdropNode = null, backdropAlphaNode = null ) {
  11845. super( lightsNode );
  11846. /**
  11847. * The current lighting model.
  11848. *
  11849. * @type {?LightingModel}
  11850. * @default null
  11851. */
  11852. this.lightingModel = lightingModel;
  11853. /**
  11854. * A backdrop node.
  11855. *
  11856. * @type {?Node<vec3>}
  11857. * @default null
  11858. */
  11859. this.backdropNode = backdropNode;
  11860. /**
  11861. * A backdrop alpha node.
  11862. *
  11863. * @type {?Node<float>}
  11864. * @default null
  11865. */
  11866. this.backdropAlphaNode = backdropAlphaNode;
  11867. this._value = null;
  11868. }
  11869. /**
  11870. * Returns a lighting context object.
  11871. *
  11872. * @return {{
  11873. * radiance: Node<vec3>,
  11874. * irradiance: Node<vec3>,
  11875. * iblIrradiance: Node<vec3>,
  11876. * ambientOcclusion: Node<float>,
  11877. * reflectedLight: {directDiffuse: Node<vec3>, directSpecular: Node<vec3>, indirectDiffuse: Node<vec3>, indirectSpecular: Node<vec3>},
  11878. * backdrop: Node<vec3>,
  11879. * backdropAlpha: Node<float>
  11880. * }} The lighting context object.
  11881. */
  11882. getContext() {
  11883. const { backdropNode, backdropAlphaNode } = this;
  11884. const directDiffuse = vec3().toVar( 'directDiffuse' ),
  11885. directSpecular = vec3().toVar( 'directSpecular' ),
  11886. indirectDiffuse = vec3().toVar( 'indirectDiffuse' ),
  11887. indirectSpecular = vec3().toVar( 'indirectSpecular' );
  11888. const reflectedLight = {
  11889. directDiffuse,
  11890. directSpecular,
  11891. indirectDiffuse,
  11892. indirectSpecular
  11893. };
  11894. const context = {
  11895. radiance: vec3().toVar( 'radiance' ),
  11896. irradiance: vec3().toVar( 'irradiance' ),
  11897. iblIrradiance: vec3().toVar( 'iblIrradiance' ),
  11898. ambientOcclusion: float( 1 ).toVar( 'ambientOcclusion' ),
  11899. reflectedLight,
  11900. backdrop: backdropNode,
  11901. backdropAlpha: backdropAlphaNode
  11902. };
  11903. return context;
  11904. }
  11905. setup( builder ) {
  11906. this.value = this._value || ( this._value = this.getContext() );
  11907. this.value.lightingModel = this.lightingModel || builder.context.lightingModel;
  11908. return super.setup( builder );
  11909. }
  11910. }
  11911. const lightingContext = /*@__PURE__*/ nodeProxy( LightingContextNode );
  11912. /**
  11913. * A generic class that can be used by nodes which contribute
  11914. * irradiance to the scene. E.g. a light map node can be used
  11915. * as input for this module. Used in {@link NodeMaterial}.
  11916. *
  11917. * @augments LightingNode
  11918. */
  11919. class IrradianceNode extends LightingNode {
  11920. static get type() {
  11921. return 'IrradianceNode';
  11922. }
  11923. /**
  11924. * Constructs a new irradiance node.
  11925. *
  11926. * @param {Node<vec3>} node - A node contributing irradiance.
  11927. */
  11928. constructor( node ) {
  11929. super();
  11930. /**
  11931. * A node contributing irradiance.
  11932. *
  11933. * @type {Node<vec3>}
  11934. */
  11935. this.node = node;
  11936. }
  11937. setup( builder ) {
  11938. builder.context.irradiance.addAssign( this.node );
  11939. }
  11940. }
  11941. let screenSizeVec, viewportVec;
  11942. /**
  11943. * This node provides a collection of screen related metrics.
  11944. * Depending on {@link ScreenNode#scope}, the nodes can represent
  11945. * resolution or viewport data as well as fragment or uv coordinates.
  11946. *
  11947. * @augments Node
  11948. */
  11949. class ScreenNode extends Node {
  11950. static get type() {
  11951. return 'ScreenNode';
  11952. }
  11953. /**
  11954. * Constructs a new screen node.
  11955. *
  11956. * @param {('coordinate'|'viewport'|'size'|'uv')} scope - The node's scope.
  11957. */
  11958. constructor( scope ) {
  11959. super();
  11960. /**
  11961. * The node represents different metric depending on which scope is selected.
  11962. *
  11963. * - `ScreenNode.COORDINATE`: Window-relative coordinates of the current fragment according to WebGPU standards.
  11964. * - `ScreenNode.VIEWPORT`: The current viewport defined as a four-dimensional vector.
  11965. * - `ScreenNode.SIZE`: The dimensions of the current bound framebuffer.
  11966. * - `ScreenNode.UV`: Normalized coordinates.
  11967. *
  11968. * @type {('coordinate'|'viewport'|'size'|'uv')}
  11969. */
  11970. this.scope = scope;
  11971. /**
  11972. * This flag can be used for type testing.
  11973. *
  11974. * @type {boolean}
  11975. * @readonly
  11976. * @default true
  11977. */
  11978. this.isViewportNode = true;
  11979. }
  11980. /**
  11981. * This method is overwritten since the node type depends on the selected scope.
  11982. *
  11983. * @return {('vec2'|'vec4')} The node type.
  11984. */
  11985. getNodeType() {
  11986. if ( this.scope === ScreenNode.VIEWPORT ) return 'vec4';
  11987. else return 'vec2';
  11988. }
  11989. /**
  11990. * This method is overwritten since the node's update type depends on the selected scope.
  11991. *
  11992. * @return {NodeUpdateType} The update type.
  11993. */
  11994. getUpdateType() {
  11995. let updateType = NodeUpdateType.NONE;
  11996. if ( this.scope === ScreenNode.SIZE || this.scope === ScreenNode.VIEWPORT ) {
  11997. updateType = NodeUpdateType.RENDER;
  11998. }
  11999. this.updateType = updateType;
  12000. return updateType;
  12001. }
  12002. /**
  12003. * `ScreenNode` implements {@link Node#update} to retrieve viewport and size information
  12004. * from the current renderer.
  12005. *
  12006. * @param {NodeFrame} frame - A reference to the current node frame.
  12007. */
  12008. update( { renderer } ) {
  12009. const renderTarget = renderer.getRenderTarget();
  12010. if ( this.scope === ScreenNode.VIEWPORT ) {
  12011. if ( renderTarget !== null ) {
  12012. viewportVec.copy( renderTarget.viewport );
  12013. } else {
  12014. renderer.getViewport( viewportVec );
  12015. viewportVec.multiplyScalar( renderer.getPixelRatio() );
  12016. }
  12017. } else {
  12018. if ( renderTarget !== null ) {
  12019. screenSizeVec.width = renderTarget.width;
  12020. screenSizeVec.height = renderTarget.height;
  12021. } else {
  12022. renderer.getDrawingBufferSize( screenSizeVec );
  12023. }
  12024. }
  12025. }
  12026. setup( /*builder*/ ) {
  12027. const scope = this.scope;
  12028. let output = null;
  12029. if ( scope === ScreenNode.SIZE ) {
  12030. output = uniform( screenSizeVec || ( screenSizeVec = new Vector2() ) );
  12031. } else if ( scope === ScreenNode.VIEWPORT ) {
  12032. output = uniform( viewportVec || ( viewportVec = new Vector4() ) );
  12033. } else {
  12034. output = vec2( screenCoordinate.div( screenSize ) );
  12035. }
  12036. return output;
  12037. }
  12038. generate( builder ) {
  12039. if ( this.scope === ScreenNode.COORDINATE ) {
  12040. let coord = builder.getFragCoord();
  12041. if ( builder.isFlipY() ) {
  12042. // follow webgpu standards
  12043. const size = builder.getNodeProperties( screenSize ).outputNode.build( builder );
  12044. coord = `${ builder.getType( 'vec2' ) }( ${ coord }.x, ${ size }.y - ${ coord }.y )`;
  12045. }
  12046. return coord;
  12047. }
  12048. return super.generate( builder );
  12049. }
  12050. }
  12051. ScreenNode.COORDINATE = 'coordinate';
  12052. ScreenNode.VIEWPORT = 'viewport';
  12053. ScreenNode.SIZE = 'size';
  12054. ScreenNode.UV = 'uv';
  12055. // Screen
  12056. /**
  12057. * TSL object that represents normalized screen coordinates, unitless in `[0, 1]`.
  12058. *
  12059. * @tsl
  12060. * @type {ScreenNode<vec2>}
  12061. */
  12062. const screenUV = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.UV );
  12063. /**
  12064. * TSL object that represents the screen resolution in physical pixel units.
  12065. *
  12066. * @tsl
  12067. * @type {ScreenNode<vec2>}
  12068. */
  12069. const screenSize = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.SIZE );
  12070. /**
  12071. * TSL object that represents the current `x`/`y` pixel position on the screen in physical pixel units.
  12072. *
  12073. * @tsl
  12074. * @type {ScreenNode<vec2>}
  12075. */
  12076. const screenCoordinate = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.COORDINATE );
  12077. // Viewport
  12078. /**
  12079. * TSL object that represents the viewport rectangle as `x`, `y`, `width` and `height` in physical pixel units.
  12080. *
  12081. * @tsl
  12082. * @type {ScreenNode<vec4>}
  12083. */
  12084. const viewport = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.VIEWPORT );
  12085. /**
  12086. * TSL object that represents the viewport resolution in physical pixel units.
  12087. *
  12088. * @tsl
  12089. * @type {ScreenNode<vec2>}
  12090. */
  12091. const viewportSize = viewport.zw;
  12092. /**
  12093. * TSL object that represents the current `x`/`y` pixel position on the viewport in physical pixel units.
  12094. *
  12095. * @tsl
  12096. * @type {ScreenNode<vec2>}
  12097. */
  12098. const viewportCoordinate = /*@__PURE__*/ screenCoordinate.sub( viewport.xy );
  12099. /**
  12100. * TSL object that represents normalized viewport coordinates, unitless in `[0, 1]`.
  12101. *
  12102. * @tsl
  12103. * @type {ScreenNode<vec2>}
  12104. */
  12105. const viewportUV = /*@__PURE__*/ viewportCoordinate.div( viewportSize );
  12106. // Deprecated
  12107. /**
  12108. * @deprecated since r169. Use {@link screenSize} instead.
  12109. */
  12110. const viewportResolution = /*@__PURE__*/ ( Fn( () => { // @deprecated, r169
  12111. console.warn( 'THREE.TSL: "viewportResolution" is deprecated. Use "screenSize" instead.' );
  12112. return screenSize;
  12113. }, 'vec2' ).once() )();
  12114. const _size$4 = /*@__PURE__*/ new Vector2();
  12115. /**
  12116. * A special type of texture node which represents the data of the current viewport
  12117. * as a texture. The module extracts data from the current bound framebuffer with
  12118. * a copy operation so no extra render pass is required to produce the texture data
  12119. * (which is good for performance). `ViewportTextureNode` can be used as an input for a
  12120. * variety of effects like refractive or transmissive materials.
  12121. *
  12122. * @augments TextureNode
  12123. */
  12124. class ViewportTextureNode extends TextureNode {
  12125. static get type() {
  12126. return 'ViewportTextureNode';
  12127. }
  12128. /**
  12129. * Constructs a new viewport texture node.
  12130. *
  12131. * @param {Node} [uvNode=screenUV] - The uv node.
  12132. * @param {?Node} [levelNode=null] - The level node.
  12133. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  12134. */
  12135. constructor( uvNode = screenUV, levelNode = null, framebufferTexture = null ) {
  12136. let defaultFramebuffer = null;
  12137. if ( framebufferTexture === null ) {
  12138. defaultFramebuffer = new FramebufferTexture();
  12139. defaultFramebuffer.minFilter = LinearMipmapLinearFilter;
  12140. framebufferTexture = defaultFramebuffer;
  12141. } else {
  12142. defaultFramebuffer = framebufferTexture;
  12143. }
  12144. super( framebufferTexture, uvNode, levelNode );
  12145. /**
  12146. * Whether to generate mipmaps or not.
  12147. *
  12148. * @type {boolean}
  12149. * @default false
  12150. */
  12151. this.generateMipmaps = false;
  12152. /**
  12153. * The reference framebuffer texture. This is used to store the framebuffer texture
  12154. * for the current render target. If the render target changes, a new framebuffer texture
  12155. * is created automatically.
  12156. *
  12157. * @type {FramebufferTexture}
  12158. * @default null
  12159. */
  12160. this.defaultFramebuffer = defaultFramebuffer;
  12161. /**
  12162. * This flag can be used for type testing.
  12163. *
  12164. * @type {boolean}
  12165. * @readonly
  12166. * @default true
  12167. */
  12168. this.isOutputTextureNode = true;
  12169. /**
  12170. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node renders the
  12171. * scene once per render in its {@link ViewportTextureNode#updateBefore} method.
  12172. *
  12173. * @type {string}
  12174. * @default 'frame'
  12175. */
  12176. this.updateBeforeType = NodeUpdateType.RENDER;
  12177. /**
  12178. * The framebuffer texture for the current renderer context.
  12179. *
  12180. * @type {WeakMap<RenderTarget, FramebufferTexture>}
  12181. * @private
  12182. */
  12183. this._textures = new WeakMap();
  12184. }
  12185. getFrameBufferTexture( reference = null ) {
  12186. const defaultFramebuffer = this.referenceNode ? this.referenceNode.defaultFramebuffer : this.defaultFramebuffer;
  12187. if ( reference === null ) {
  12188. return defaultFramebuffer;
  12189. }
  12190. if ( this._textures.has( reference ) === false ) {
  12191. const framebufferTexture = defaultFramebuffer.clone();
  12192. this._textures.set( reference, framebufferTexture );
  12193. }
  12194. return this._textures.get( reference );
  12195. }
  12196. updateBefore( frame ) {
  12197. const renderer = frame.renderer;
  12198. const renderTarget = renderer.getRenderTarget();
  12199. if ( renderTarget === null ) {
  12200. renderer.getDrawingBufferSize( _size$4 );
  12201. } else {
  12202. _size$4.set( renderTarget.width, renderTarget.height );
  12203. }
  12204. //
  12205. const framebufferTexture = this.getFrameBufferTexture( renderTarget );
  12206. if ( framebufferTexture.image.width !== _size$4.width || framebufferTexture.image.height !== _size$4.height ) {
  12207. framebufferTexture.image.width = _size$4.width;
  12208. framebufferTexture.image.height = _size$4.height;
  12209. framebufferTexture.needsUpdate = true;
  12210. }
  12211. //
  12212. const currentGenerateMipmaps = framebufferTexture.generateMipmaps;
  12213. framebufferTexture.generateMipmaps = this.generateMipmaps;
  12214. renderer.copyFramebufferToTexture( framebufferTexture );
  12215. framebufferTexture.generateMipmaps = currentGenerateMipmaps;
  12216. this.value = framebufferTexture;
  12217. }
  12218. clone() {
  12219. const viewportTextureNode = new this.constructor( this.uvNode, this.levelNode, this.value );
  12220. viewportTextureNode.generateMipmaps = this.generateMipmaps;
  12221. return viewportTextureNode;
  12222. }
  12223. }
  12224. /**
  12225. * TSL function for creating a viewport texture node.
  12226. *
  12227. * @tsl
  12228. * @function
  12229. * @param {?Node} [uvNode=screenUV] - The uv node.
  12230. * @param {?Node} [levelNode=null] - The level node.
  12231. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  12232. * @returns {ViewportTextureNode}
  12233. */
  12234. const viewportTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode ).setParameterLength( 0, 3 );
  12235. /**
  12236. * TSL function for creating a viewport texture node with enabled mipmap generation.
  12237. *
  12238. * @tsl
  12239. * @function
  12240. * @param {?Node} [uvNode=screenUV] - The uv node.
  12241. * @param {?Node} [levelNode=null] - The level node.
  12242. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  12243. * @returns {ViewportTextureNode}
  12244. */
  12245. const viewportMipTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode, null, null, { generateMipmaps: true } ).setParameterLength( 0, 3 );
  12246. let sharedDepthbuffer = null;
  12247. /**
  12248. * Represents the depth of the current viewport as a texture. This module
  12249. * can be used in combination with viewport texture to achieve effects
  12250. * that require depth evaluation.
  12251. *
  12252. * @augments ViewportTextureNode
  12253. */
  12254. class ViewportDepthTextureNode extends ViewportTextureNode {
  12255. static get type() {
  12256. return 'ViewportDepthTextureNode';
  12257. }
  12258. /**
  12259. * Constructs a new viewport depth texture node.
  12260. *
  12261. * @param {Node} [uvNode=screenUV] - The uv node.
  12262. * @param {?Node} [levelNode=null] - The level node.
  12263. */
  12264. constructor( uvNode = screenUV, levelNode = null ) {
  12265. if ( sharedDepthbuffer === null ) {
  12266. sharedDepthbuffer = new DepthTexture();
  12267. }
  12268. super( uvNode, levelNode, sharedDepthbuffer );
  12269. }
  12270. }
  12271. /**
  12272. * TSL function for a viewport depth texture node.
  12273. *
  12274. * @tsl
  12275. * @function
  12276. * @param {?Node} [uvNode=screenUV] - The uv node.
  12277. * @param {?Node} [levelNode=null] - The level node.
  12278. * @returns {ViewportDepthTextureNode}
  12279. */
  12280. const viewportDepthTexture = /*@__PURE__*/ nodeProxy( ViewportDepthTextureNode ).setParameterLength( 0, 2 );
  12281. /**
  12282. * This node offers a collection of features in context of the depth logic in the fragment shader.
  12283. * Depending on {@link ViewportDepthNode#scope}, it can be used to define a depth value for the current
  12284. * fragment or for depth evaluation purposes.
  12285. *
  12286. * @augments Node
  12287. */
  12288. class ViewportDepthNode extends Node {
  12289. static get type() {
  12290. return 'ViewportDepthNode';
  12291. }
  12292. /**
  12293. * Constructs a new viewport depth node.
  12294. *
  12295. * @param {('depth'|'depthBase'|'linearDepth')} scope - The node's scope.
  12296. * @param {?Node} [valueNode=null] - The value node.
  12297. */
  12298. constructor( scope, valueNode = null ) {
  12299. super( 'float' );
  12300. /**
  12301. * The node behaves differently depending on which scope is selected.
  12302. *
  12303. * - `ViewportDepthNode.DEPTH_BASE`: Allows to define a value for the current fragment's depth.
  12304. * - `ViewportDepthNode.DEPTH`: Represents the depth value for the current fragment (`valueNode` is ignored).
  12305. * - `ViewportDepthNode.LINEAR_DEPTH`: Represents the linear (orthographic) depth value of the current fragment.
  12306. * If a `valueNode` is set, the scope can be used to convert perspective depth data to linear data.
  12307. *
  12308. * @type {('depth'|'depthBase'|'linearDepth')}
  12309. */
  12310. this.scope = scope;
  12311. /**
  12312. * Can be used to define a custom depth value.
  12313. * The property is ignored in the `ViewportDepthNode.DEPTH` scope.
  12314. *
  12315. * @type {?Node}
  12316. * @default null
  12317. */
  12318. this.valueNode = valueNode;
  12319. /**
  12320. * This flag can be used for type testing.
  12321. *
  12322. * @type {boolean}
  12323. * @readonly
  12324. * @default true
  12325. */
  12326. this.isViewportDepthNode = true;
  12327. }
  12328. generate( builder ) {
  12329. const { scope } = this;
  12330. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  12331. return builder.getFragDepth();
  12332. }
  12333. return super.generate( builder );
  12334. }
  12335. setup( { camera } ) {
  12336. const { scope } = this;
  12337. const value = this.valueNode;
  12338. let node = null;
  12339. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  12340. if ( value !== null ) {
  12341. node = depthBase().assign( value );
  12342. }
  12343. } else if ( scope === ViewportDepthNode.DEPTH ) {
  12344. if ( camera.isPerspectiveCamera ) {
  12345. node = viewZToPerspectiveDepth( positionView.z, cameraNear, cameraFar );
  12346. } else {
  12347. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  12348. }
  12349. } else if ( scope === ViewportDepthNode.LINEAR_DEPTH ) {
  12350. if ( value !== null ) {
  12351. if ( camera.isPerspectiveCamera ) {
  12352. const viewZ = perspectiveDepthToViewZ( value, cameraNear, cameraFar );
  12353. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  12354. } else {
  12355. node = value;
  12356. }
  12357. } else {
  12358. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  12359. }
  12360. }
  12361. return node;
  12362. }
  12363. }
  12364. ViewportDepthNode.DEPTH_BASE = 'depthBase';
  12365. ViewportDepthNode.DEPTH = 'depth';
  12366. ViewportDepthNode.LINEAR_DEPTH = 'linearDepth';
  12367. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  12368. /**
  12369. * TSL function for converting a viewZ value to an orthographic depth value.
  12370. *
  12371. * @tsl
  12372. * @function
  12373. * @param {Node<float>} viewZ - The viewZ node.
  12374. * @param {Node<float>} near - The camera's near value.
  12375. * @param {Node<float>} far - The camera's far value.
  12376. * @returns {Node<float>}
  12377. */
  12378. const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  12379. /**
  12380. * TSL function for converting an orthographic depth value to a viewZ value.
  12381. *
  12382. * @tsl
  12383. * @function
  12384. * @param {Node<float>} depth - The orthographic depth.
  12385. * @param {Node<float>} near - The camera's near value.
  12386. * @param {Node<float>} far - The camera's far value.
  12387. * @returns {Node<float>}
  12388. */
  12389. const orthographicDepthToViewZ = ( depth, near, far ) => near.sub( far ).mul( depth ).sub( near );
  12390. /**
  12391. * TSL function for converting a viewZ value to a perspective depth value.
  12392. *
  12393. * Note: {link https://twitter.com/gonnavis/status/1377183786949959682}.
  12394. *
  12395. * @tsl
  12396. * @function
  12397. * @param {Node<float>} viewZ - The viewZ node.
  12398. * @param {Node<float>} near - The camera's near value.
  12399. * @param {Node<float>} far - The camera's far value.
  12400. * @returns {Node<float>}
  12401. */
  12402. const viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( far.sub( near ).mul( viewZ ) );
  12403. /**
  12404. * TSL function for converting a perspective depth value to a viewZ value.
  12405. *
  12406. * @tsl
  12407. * @function
  12408. * @param {Node<float>} depth - The perspective depth.
  12409. * @param {Node<float>} near - The camera's near value.
  12410. * @param {Node<float>} far - The camera's far value.
  12411. * @returns {Node<float>}
  12412. */
  12413. const perspectiveDepthToViewZ = ( depth, near, far ) => near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  12414. /**
  12415. * TSL function for converting a viewZ value to a logarithmic depth value.
  12416. *
  12417. * @tsl
  12418. * @function
  12419. * @param {Node<float>} viewZ - The viewZ node.
  12420. * @param {Node<float>} near - The camera's near value.
  12421. * @param {Node<float>} far - The camera's far value.
  12422. * @returns {Node<float>}
  12423. */
  12424. const viewZToLogarithmicDepth = ( viewZ, near, far ) => {
  12425. // NOTE: viewZ must be negative--see explanation at the end of this comment block.
  12426. // The final logarithmic depth formula used here is adapted from one described in an
  12427. // article by Thatcher Ulrich (see http://tulrich.com/geekstuff/log_depth_buffer.txt),
  12428. // which was an improvement upon an earlier formula one described in an
  12429. // Outerra article (https://outerra.blogspot.com/2009/08/logarithmic-z-buffer.html).
  12430. // Ulrich's formula is the following:
  12431. // z = K * log( w / cameraNear ) / log( cameraFar / cameraNear )
  12432. // where K = 2^k - 1, and k is the number of bits in the depth buffer.
  12433. // The Outerra variant ignored the camera near plane (it assumed it was 0) and instead
  12434. // opted for a "C-constant" for resolution adjustment of objects near the camera.
  12435. // Outerra states: "Notice that the 'C' variant doesn’t use a near plane distance, it has it
  12436. // set at 0" (quote from https://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html).
  12437. // Ulrich's variant has the benefit of constant relative precision over the whole near-far range.
  12438. // It was debated here whether Outerra's "C-constant" or Ulrich's "near plane" variant should
  12439. // be used, and ultimately Ulrich's "near plane" version was chosen.
  12440. // Outerra eventually made another improvement to their original "C-constant" variant,
  12441. // but it still does not incorporate the camera near plane (for this version,
  12442. // see https://outerra.blogspot.com/2013/07/logarithmic-depth-buffer-optimizations.html).
  12443. // Here we make 4 changes to Ulrich's formula:
  12444. // 1. Clamp the camera near plane so we don't divide by 0.
  12445. // 2. Use log2 instead of log to avoid an extra multiply (shaders implement log using log2).
  12446. // 3. Assume K is 1 (K = maximum value in depth buffer; see Ulrich's formula above).
  12447. // 4. To maintain consistency with the functions "viewZToOrthographicDepth" and "viewZToPerspectiveDepth",
  12448. // we modify the formula here to use 'viewZ' instead of 'w'. The other functions expect a negative viewZ,
  12449. // so we do the same here, hence the 'viewZ.negate()' call.
  12450. // For visual representation of this depth curve, see https://www.desmos.com/calculator/uyqk0vex1u
  12451. near = near.max( 1e-6 ).toVar();
  12452. const numerator = log2( viewZ.negate().div( near ) );
  12453. const denominator = log2( far.div( near ) );
  12454. return numerator.div( denominator );
  12455. };
  12456. /**
  12457. * TSL function for converting a logarithmic depth value to a viewZ value.
  12458. *
  12459. * @tsl
  12460. * @function
  12461. * @param {Node<float>} depth - The logarithmic depth.
  12462. * @param {Node<float>} near - The camera's near value.
  12463. * @param {Node<float>} far - The camera's far value.
  12464. * @returns {Node<float>}
  12465. */
  12466. const logarithmicDepthToViewZ = ( depth, near, far ) => {
  12467. // NOTE: we add a 'negate()' call to the return value here to maintain consistency with
  12468. // the functions "orthographicDepthToViewZ" and "perspectiveDepthToViewZ" (they return
  12469. // a negative viewZ).
  12470. const exponent = depth.mul( log( far.div( near ) ) );
  12471. return float( Math.E ).pow( exponent ).mul( near ).negate();
  12472. };
  12473. /**
  12474. * TSL function for defining a value for the current fragment's depth.
  12475. *
  12476. * @tsl
  12477. * @function
  12478. * @param {Node<float>} value - The depth value to set.
  12479. * @returns {ViewportDepthNode<float>}
  12480. */
  12481. const depthBase = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH_BASE );
  12482. /**
  12483. * TSL object that represents the depth value for the current fragment.
  12484. *
  12485. * @tsl
  12486. * @type {ViewportDepthNode}
  12487. */
  12488. const depth = /*@__PURE__*/ nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  12489. /**
  12490. * TSL function for converting a perspective depth value to linear depth.
  12491. *
  12492. * @tsl
  12493. * @function
  12494. * @param {?Node<float>} [value=null] - The perspective depth. If `null` is provided, the current fragment's depth is used.
  12495. * @returns {ViewportDepthNode<float>}
  12496. */
  12497. const linearDepth = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.LINEAR_DEPTH ).setParameterLength( 0, 1 );
  12498. /**
  12499. * TSL object that represents the linear (orthographic) depth value of the current fragment
  12500. *
  12501. * @tsl
  12502. * @type {ViewportDepthNode}
  12503. */
  12504. const viewportLinearDepth = /*@__PURE__*/ linearDepth( viewportDepthTexture() );
  12505. depth.assign = ( value ) => depthBase( value );
  12506. /**
  12507. * This node is used in {@link NodeMaterial} to setup the clipping
  12508. * which can happen hardware-accelerated (if supported) and optionally
  12509. * use alpha-to-coverage for anti-aliasing clipped edges.
  12510. *
  12511. * @augments Node
  12512. */
  12513. class ClippingNode extends Node {
  12514. static get type() {
  12515. return 'ClippingNode';
  12516. }
  12517. /**
  12518. * Constructs a new clipping node.
  12519. *
  12520. * @param {('default'|'hardware'|'alphaToCoverage')} [scope='default'] - The node's scope. Similar to other nodes,
  12521. * the selected scope influences the behavior of the node and what type of code is generated.
  12522. */
  12523. constructor( scope = ClippingNode.DEFAULT ) {
  12524. super();
  12525. /**
  12526. * The node's scope. Similar to other nodes, the selected scope influences
  12527. * the behavior of the node and what type of code is generated.
  12528. *
  12529. * @type {('default'|'hardware'|'alphaToCoverage')}
  12530. */
  12531. this.scope = scope;
  12532. }
  12533. /**
  12534. * Setups the node depending on the selected scope.
  12535. *
  12536. * @param {NodeBuilder} builder - The current node builder.
  12537. * @return {Node} The result node.
  12538. */
  12539. setup( builder ) {
  12540. super.setup( builder );
  12541. const clippingContext = builder.clippingContext;
  12542. const { intersectionPlanes, unionPlanes } = clippingContext;
  12543. this.hardwareClipping = builder.material.hardwareClipping;
  12544. if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) {
  12545. return this.setupAlphaToCoverage( intersectionPlanes, unionPlanes );
  12546. } else if ( this.scope === ClippingNode.HARDWARE ) {
  12547. return this.setupHardwareClipping( unionPlanes, builder );
  12548. } else {
  12549. return this.setupDefault( intersectionPlanes, unionPlanes );
  12550. }
  12551. }
  12552. /**
  12553. * Setups alpha to coverage.
  12554. *
  12555. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  12556. * @param {Array<Vector4>} unionPlanes - The union planes.
  12557. * @return {Node} The result node.
  12558. */
  12559. setupAlphaToCoverage( intersectionPlanes, unionPlanes ) {
  12560. return Fn( () => {
  12561. const distanceToPlane = float().toVar( 'distanceToPlane' );
  12562. const distanceGradient = float().toVar( 'distanceToGradient' );
  12563. const clipOpacity = float( 1 ).toVar( 'clipOpacity' );
  12564. const numUnionPlanes = unionPlanes.length;
  12565. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  12566. const clippingPlanes = uniformArray( unionPlanes );
  12567. Loop( numUnionPlanes, ( { i } ) => {
  12568. const plane = clippingPlanes.element( i );
  12569. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  12570. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  12571. clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) );
  12572. } );
  12573. }
  12574. const numIntersectionPlanes = intersectionPlanes.length;
  12575. if ( numIntersectionPlanes > 0 ) {
  12576. const clippingPlanes = uniformArray( intersectionPlanes );
  12577. const intersectionClipOpacity = float( 1 ).toVar( 'intersectionClipOpacity' );
  12578. Loop( numIntersectionPlanes, ( { i } ) => {
  12579. const plane = clippingPlanes.element( i );
  12580. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  12581. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  12582. intersectionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() );
  12583. } );
  12584. clipOpacity.mulAssign( intersectionClipOpacity.oneMinus() );
  12585. }
  12586. diffuseColor.a.mulAssign( clipOpacity );
  12587. diffuseColor.a.equal( 0.0 ).discard();
  12588. } )();
  12589. }
  12590. /**
  12591. * Setups the default clipping.
  12592. *
  12593. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  12594. * @param {Array<Vector4>} unionPlanes - The union planes.
  12595. * @return {Node} The result node.
  12596. */
  12597. setupDefault( intersectionPlanes, unionPlanes ) {
  12598. return Fn( () => {
  12599. const numUnionPlanes = unionPlanes.length;
  12600. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  12601. const clippingPlanes = uniformArray( unionPlanes );
  12602. Loop( numUnionPlanes, ( { i } ) => {
  12603. const plane = clippingPlanes.element( i );
  12604. positionView.dot( plane.xyz ).greaterThan( plane.w ).discard();
  12605. } );
  12606. }
  12607. const numIntersectionPlanes = intersectionPlanes.length;
  12608. if ( numIntersectionPlanes > 0 ) {
  12609. const clippingPlanes = uniformArray( intersectionPlanes );
  12610. const clipped = bool( true ).toVar( 'clipped' );
  12611. Loop( numIntersectionPlanes, ( { i } ) => {
  12612. const plane = clippingPlanes.element( i );
  12613. clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) );
  12614. } );
  12615. clipped.discard();
  12616. }
  12617. } )();
  12618. }
  12619. /**
  12620. * Setups hardware clipping.
  12621. *
  12622. * @param {Array<Vector4>} unionPlanes - The union planes.
  12623. * @param {NodeBuilder} builder - The current node builder.
  12624. * @return {Node} The result node.
  12625. */
  12626. setupHardwareClipping( unionPlanes, builder ) {
  12627. const numUnionPlanes = unionPlanes.length;
  12628. builder.enableHardwareClipping( numUnionPlanes );
  12629. return Fn( () => {
  12630. const clippingPlanes = uniformArray( unionPlanes );
  12631. const hw_clip_distances = builtin( builder.getClipDistance() );
  12632. Loop( numUnionPlanes, ( { i } ) => {
  12633. const plane = clippingPlanes.element( i );
  12634. const distance = positionView.dot( plane.xyz ).sub( plane.w ).negate();
  12635. hw_clip_distances.element( i ).assign( distance );
  12636. } );
  12637. } )();
  12638. }
  12639. }
  12640. ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage';
  12641. ClippingNode.DEFAULT = 'default';
  12642. ClippingNode.HARDWARE = 'hardware';
  12643. /**
  12644. * TSL function for setting up the default clipping logic.
  12645. *
  12646. * @tsl
  12647. * @function
  12648. * @returns {ClippingNode}
  12649. */
  12650. const clipping = () => nodeObject( new ClippingNode() );
  12651. /**
  12652. * TSL function for setting up alpha to coverage.
  12653. *
  12654. * @tsl
  12655. * @function
  12656. * @returns {ClippingNode}
  12657. */
  12658. const clippingAlpha = () => nodeObject( new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE ) );
  12659. /**
  12660. * TSL function for setting up hardware-based clipping.
  12661. *
  12662. * @tsl
  12663. * @function
  12664. * @returns {ClippingNode}
  12665. */
  12666. const hardwareClipping = () => nodeObject( new ClippingNode( ClippingNode.HARDWARE ) );
  12667. // See: https://casual-effects.com/research/Wyman2017Hashed/index.html
  12668. const ALPHA_HASH_SCALE = 0.05; // Derived from trials only, and may be changed.
  12669. const hash2D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  12670. 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 ) ) ) ) ) );
  12671. } );
  12672. const hash3D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  12673. return hash2D( vec2( hash2D( value.xy ), value.z ) );
  12674. } );
  12675. const getAlphaHashThreshold = /*@__PURE__*/ Fn( ( [ position ] ) => {
  12676. // Find the discretized derivatives of our coordinates
  12677. const maxDeriv = max$1(
  12678. length( dFdx( position.xyz ) ),
  12679. length( dFdy( position.xyz ) )
  12680. );
  12681. const pixScale = float( 1 ).div( float( ALPHA_HASH_SCALE ).mul( maxDeriv ) ).toVar( 'pixScale' );
  12682. // Find two nearest log-discretized noise scales
  12683. const pixScales = vec2(
  12684. exp2( floor( log2( pixScale ) ) ),
  12685. exp2( ceil( log2( pixScale ) ) )
  12686. );
  12687. // Compute alpha thresholds at our two noise scales
  12688. const alpha = vec2(
  12689. hash3D( floor( pixScales.x.mul( position.xyz ) ) ),
  12690. hash3D( floor( pixScales.y.mul( position.xyz ) ) ),
  12691. );
  12692. // Factor to interpolate lerp with
  12693. const lerpFactor = fract( log2( pixScale ) );
  12694. // Interpolate alpha threshold from noise at two scales
  12695. const x = add( mul( lerpFactor.oneMinus(), alpha.x ), mul( lerpFactor, alpha.y ) );
  12696. // Pass into CDF to compute uniformly distrib threshold
  12697. const a = min$1( lerpFactor, lerpFactor.oneMinus() );
  12698. const cases = vec3(
  12699. x.mul( x ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ),
  12700. x.sub( mul( 0.5, a ) ).div( sub( 1.0, a ) ),
  12701. sub( 1.0, sub( 1.0, x ).mul( sub( 1.0, x ) ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ) ) );
  12702. // Find our final, uniformly distributed alpha threshold (ατ)
  12703. const threshold = x.lessThan( a.oneMinus() ).select( x.lessThan( a ).select( cases.x, cases.y ), cases.z );
  12704. // Avoids ατ == 0. Could also do ατ =1-ατ
  12705. return clamp( threshold, 1.0e-6, 1.0 );
  12706. } ).setLayout( {
  12707. name: 'getAlphaHashThreshold',
  12708. type: 'float',
  12709. inputs: [
  12710. { name: 'position', type: 'vec3' }
  12711. ]
  12712. } );
  12713. /**
  12714. * An attribute node for representing vertex colors.
  12715. *
  12716. * @augments AttributeNode
  12717. */
  12718. class VertexColorNode extends AttributeNode {
  12719. static get type() {
  12720. return 'VertexColorNode';
  12721. }
  12722. /**
  12723. * Constructs a new vertex color node.
  12724. *
  12725. * @param {number} index - The attribute index.
  12726. */
  12727. constructor( index ) {
  12728. super( null, 'vec4' );
  12729. /**
  12730. * This flag can be used for type testing.
  12731. *
  12732. * @type {boolean}
  12733. * @readonly
  12734. * @default true
  12735. */
  12736. this.isVertexColorNode = true;
  12737. /**
  12738. * The attribute index to enable more than one sets of vertex colors.
  12739. *
  12740. * @type {number}
  12741. * @default 0
  12742. */
  12743. this.index = index;
  12744. }
  12745. /**
  12746. * Overwrites the default implementation by honoring the attribute index.
  12747. *
  12748. * @param {NodeBuilder} builder - The current node builder.
  12749. * @return {string} The attribute name.
  12750. */
  12751. getAttributeName( /*builder*/ ) {
  12752. const index = this.index;
  12753. return 'color' + ( index > 0 ? index : '' );
  12754. }
  12755. generate( builder ) {
  12756. const attributeName = this.getAttributeName( builder );
  12757. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  12758. let result;
  12759. if ( geometryAttribute === true ) {
  12760. result = super.generate( builder );
  12761. } else {
  12762. // Vertex color fallback should be white
  12763. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  12764. }
  12765. return result;
  12766. }
  12767. serialize( data ) {
  12768. super.serialize( data );
  12769. data.index = this.index;
  12770. }
  12771. deserialize( data ) {
  12772. super.deserialize( data );
  12773. this.index = data.index;
  12774. }
  12775. }
  12776. /**
  12777. * TSL function for creating a reference node.
  12778. *
  12779. * @tsl
  12780. * @function
  12781. * @param {number} [index=0] - The attribute index.
  12782. * @returns {VertexColorNode}
  12783. */
  12784. const vertexColor = ( index = 0 ) => nodeObject( new VertexColorNode( index ) );
  12785. /**
  12786. * Represents a "Color Burn" blend mode.
  12787. *
  12788. * It's designed to darken the base layer's colors based on the color of the blend layer.
  12789. * It significantly increases the contrast of the base layer, making the colors more vibrant and saturated.
  12790. * The darker the color in the blend layer, the stronger the darkening and contrast effect on the base layer.
  12791. *
  12792. * @tsl
  12793. * @function
  12794. * @param {Node<vec3>} base - The base color.
  12795. * @param {Node<vec3>} blend - The blend color. A white (#ffffff) blend color does not alter the base color.
  12796. * @return {Node<vec3>} The result.
  12797. */
  12798. const blendBurn = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  12799. return min$1( 1.0, base.oneMinus().div( blend ) ).oneMinus();
  12800. } ).setLayout( {
  12801. name: 'blendBurn',
  12802. type: 'vec3',
  12803. inputs: [
  12804. { name: 'base', type: 'vec3' },
  12805. { name: 'blend', type: 'vec3' }
  12806. ]
  12807. } );
  12808. /**
  12809. * Represents a "Color Dodge" blend mode.
  12810. *
  12811. * It's designed to lighten the base layer's colors based on the color of the blend layer.
  12812. * It significantly increases the brightness of the base layer, making the colors lighter and more vibrant.
  12813. * The brighter the color in the blend layer, the stronger the lightening and contrast effect on the base layer.
  12814. *
  12815. * @tsl
  12816. * @function
  12817. * @param {Node<vec3>} base - The base color.
  12818. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  12819. * @return {Node<vec3>} The result.
  12820. */
  12821. const blendDodge = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  12822. return min$1( base.div( blend.oneMinus() ), 1.0 );
  12823. } ).setLayout( {
  12824. name: 'blendDodge',
  12825. type: 'vec3',
  12826. inputs: [
  12827. { name: 'base', type: 'vec3' },
  12828. { name: 'blend', type: 'vec3' }
  12829. ]
  12830. } );
  12831. /**
  12832. * Represents a "Screen" blend mode.
  12833. *
  12834. * Similar to `blendDodge()`, this mode also lightens the base layer's colors based on the color of the blend layer.
  12835. * The "Screen" blend mode is better for general brightening whereas the "Dodge" results in more subtle and nuanced
  12836. * effects.
  12837. *
  12838. * @tsl
  12839. * @function
  12840. * @param {Node<vec3>} base - The base color.
  12841. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  12842. * @return {Node<vec3>} The result.
  12843. */
  12844. const blendScreen = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  12845. return base.oneMinus().mul( blend.oneMinus() ).oneMinus();
  12846. } ).setLayout( {
  12847. name: 'blendScreen',
  12848. type: 'vec3',
  12849. inputs: [
  12850. { name: 'base', type: 'vec3' },
  12851. { name: 'blend', type: 'vec3' }
  12852. ]
  12853. } );
  12854. /**
  12855. * Represents a "Overlay" blend mode.
  12856. *
  12857. * It's designed to increase the contrast of the base layer based on the color of the blend layer.
  12858. * It amplifies the existing colors and contrast in the base layer, making lighter areas lighter and darker areas darker.
  12859. * The color of the blend layer significantly influences the resulting contrast and color shift in the base layer.
  12860. *
  12861. * @tsl
  12862. * @function
  12863. * @param {Node<vec3>} base - The base color.
  12864. * @param {Node<vec3>} blend - The blend color
  12865. * @return {Node<vec3>} The result.
  12866. */
  12867. const blendOverlay = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  12868. return mix( base.mul( 2.0 ).mul( blend ), base.oneMinus().mul( 2.0 ).mul( blend.oneMinus() ).oneMinus(), step( 0.5, base ) );
  12869. } ).setLayout( {
  12870. name: 'blendOverlay',
  12871. type: 'vec3',
  12872. inputs: [
  12873. { name: 'base', type: 'vec3' },
  12874. { name: 'blend', type: 'vec3' }
  12875. ]
  12876. } );
  12877. /**
  12878. * This function blends two color based on their alpha values by replicating the behavior of `THREE.NormalBlending`.
  12879. * It assumes both input colors have non-premultiplied alpha.
  12880. *
  12881. * @tsl
  12882. * @function
  12883. * @param {Node<vec4>} base - The base color.
  12884. * @param {Node<vec4>} blend - The blend color
  12885. * @return {Node<vec4>} The result.
  12886. */
  12887. const blendColor = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  12888. const outAlpha = blend.a.add( base.a.mul( blend.a.oneMinus() ) );
  12889. return vec4( blend.rgb.mul( blend.a ).add( base.rgb.mul( base.a ).mul( blend.a.oneMinus() ) ).div( outAlpha ), outAlpha );
  12890. } ).setLayout( {
  12891. name: 'blendColor',
  12892. type: 'vec4',
  12893. inputs: [
  12894. { name: 'base', type: 'vec4' },
  12895. { name: 'blend', type: 'vec4' }
  12896. ]
  12897. } );
  12898. /**
  12899. * Premultiplies the RGB channels of a color by its alpha channel.
  12900. *
  12901. * This function is useful for converting a non-premultiplied alpha color
  12902. * into a premultiplied alpha format, where the RGB values are scaled
  12903. * by the alpha value. Premultiplied alpha is often used in graphics
  12904. * rendering for certain operations, such as compositing and image processing.
  12905. *
  12906. * @tsl
  12907. * @function
  12908. * @param {Node<vec4>} color - The input color with non-premultiplied alpha.
  12909. * @return {Node<vec4>} The color with premultiplied alpha.
  12910. */
  12911. const premultiplyAlpha = /*@__PURE__*/ Fn( ( [ color ] ) => {
  12912. return vec4( color.rgb.mul( color.a ), color.a );
  12913. }, { color: 'vec4', return: 'vec4' } );
  12914. /**
  12915. * Unpremultiplies the RGB channels of a color by its alpha channel.
  12916. *
  12917. * This function is useful for converting a premultiplied alpha color
  12918. * back into a non-premultiplied alpha format, where the RGB values are
  12919. * divided by the alpha value. Unpremultiplied alpha is often used in graphics
  12920. * rendering for certain operations, such as compositing and image processing.
  12921. *
  12922. * @tsl
  12923. * @function
  12924. * @param {Node<vec4>} color - The input color with premultiplied alpha.
  12925. * @return {Node<vec4>} The color with non-premultiplied alpha.
  12926. */
  12927. const unpremultiplyAlpha = /*@__PURE__*/ Fn( ( [ color ] ) => {
  12928. If( color.a.equal( 0.0 ), () => vec4( 0.0 ) );
  12929. return vec4( color.rgb.div( color.a ), color.a );
  12930. }, { color: 'vec4', return: 'vec4' } );
  12931. // Deprecated
  12932. /**
  12933. * @tsl
  12934. * @function
  12935. * @deprecated since r171. Use {@link blendBurn} instead.
  12936. *
  12937. * @param {...any} params
  12938. * @returns {Function}
  12939. */
  12940. const burn = ( ...params ) => { // @deprecated, r171
  12941. console.warn( 'THREE.TSL: "burn" has been renamed. Use "blendBurn" instead.' );
  12942. return blendBurn( params );
  12943. };
  12944. /**
  12945. * @tsl
  12946. * @function
  12947. * @deprecated since r171. Use {@link blendDodge} instead.
  12948. *
  12949. * @param {...any} params
  12950. * @returns {Function}
  12951. */
  12952. const dodge = ( ...params ) => { // @deprecated, r171
  12953. console.warn( 'THREE.TSL: "dodge" has been renamed. Use "blendDodge" instead.' );
  12954. return blendDodge( params );
  12955. };
  12956. /**
  12957. * @tsl
  12958. * @function
  12959. * @deprecated since r171. Use {@link blendScreen} instead.
  12960. *
  12961. * @param {...any} params
  12962. * @returns {Function}
  12963. */
  12964. const screen = ( ...params ) => { // @deprecated, r171
  12965. console.warn( 'THREE.TSL: "screen" has been renamed. Use "blendScreen" instead.' );
  12966. return blendScreen( params );
  12967. };
  12968. /**
  12969. * @tsl
  12970. * @function
  12971. * @deprecated since r171. Use {@link blendOverlay} instead.
  12972. *
  12973. * @param {...any} params
  12974. * @returns {Function}
  12975. */
  12976. const overlay = ( ...params ) => { // @deprecated, r171
  12977. console.warn( 'THREE.TSL: "overlay" has been renamed. Use "blendOverlay" instead.' );
  12978. return blendOverlay( params );
  12979. };
  12980. /**
  12981. * Base class for all node materials.
  12982. *
  12983. * @augments Material
  12984. */
  12985. class NodeMaterial extends Material {
  12986. static get type() {
  12987. return 'NodeMaterial';
  12988. }
  12989. /**
  12990. * Represents the type of the node material.
  12991. *
  12992. * @type {string}
  12993. */
  12994. get type() {
  12995. return this.constructor.type;
  12996. }
  12997. set type( _value ) { /* */ }
  12998. /**
  12999. * Constructs a new node material.
  13000. */
  13001. constructor() {
  13002. super();
  13003. /**
  13004. * This flag can be used for type testing.
  13005. *
  13006. * @type {boolean}
  13007. * @readonly
  13008. * @default true
  13009. */
  13010. this.isNodeMaterial = true;
  13011. /**
  13012. * Whether this material is affected by fog or not.
  13013. *
  13014. * @type {boolean}
  13015. * @default true
  13016. */
  13017. this.fog = true;
  13018. /**
  13019. * Whether this material is affected by lights or not.
  13020. *
  13021. * @type {boolean}
  13022. * @default false
  13023. */
  13024. this.lights = false;
  13025. /**
  13026. * Whether this material uses hardware clipping or not.
  13027. * This property is managed by the engine and should not be
  13028. * modified by apps.
  13029. *
  13030. * @type {boolean}
  13031. * @default false
  13032. */
  13033. this.hardwareClipping = false;
  13034. /**
  13035. * Node materials which set their `lights` property to `true`
  13036. * are affected by all lights of the scene. Sometimes selective
  13037. * lighting is wanted which means only _some_ lights in the scene
  13038. * affect a material. This can be achieved by creating an instance
  13039. * of {@link LightsNode} with a list of selective
  13040. * lights and assign the node to this property.
  13041. *
  13042. * ```js
  13043. * const customLightsNode = lights( [ light1, light2 ] );
  13044. * material.lightsNode = customLightsNode;
  13045. * ```
  13046. *
  13047. * @type {?LightsNode}
  13048. * @default null
  13049. */
  13050. this.lightsNode = null;
  13051. /**
  13052. * The environment of node materials can be defined by an environment
  13053. * map assigned to the `envMap` property or by `Scene.environment`
  13054. * if the node material is a PBR material. This node property allows to overwrite
  13055. * the default behavior and define the environment with a custom node.
  13056. *
  13057. * ```js
  13058. * material.envNode = pmremTexture( renderTarget.texture );
  13059. * ```
  13060. *
  13061. * @type {?Node<vec3>}
  13062. * @default null
  13063. */
  13064. this.envNode = null;
  13065. /**
  13066. * The lighting of node materials might be influenced by ambient occlusion.
  13067. * The default AO is inferred from an ambient occlusion map assigned to `aoMap`
  13068. * and the respective `aoMapIntensity`. This node property allows to overwrite
  13069. * the default and define the ambient occlusion with a custom node instead.
  13070. *
  13071. * If you don't want to overwrite the diffuse color but modify the existing
  13072. * values instead, use {@link materialAO}.
  13073. *
  13074. * @type {?Node<float>}
  13075. * @default null
  13076. */
  13077. this.aoNode = null;
  13078. /**
  13079. * The diffuse color of node materials is by default inferred from the
  13080. * `color` and `map` properties. This node property allows to overwrite the default
  13081. * and define the diffuse color with a node instead.
  13082. *
  13083. * ```js
  13084. * material.colorNode = color( 0xff0000 ); // define red color
  13085. * ```
  13086. *
  13087. * If you don't want to overwrite the diffuse color but modify the existing
  13088. * values instead, use {@link materialColor}.
  13089. *
  13090. * ```js
  13091. * material.colorNode = materialColor.mul( color( 0xff0000 ) ); // give diffuse colors a red tint
  13092. * ```
  13093. *
  13094. * @type {?Node<vec3>}
  13095. * @default null
  13096. */
  13097. this.colorNode = null;
  13098. /**
  13099. * The normals of node materials are by default inferred from the `normalMap`/`normalScale`
  13100. * or `bumpMap`/`bumpScale` properties. This node property allows to overwrite the default
  13101. * and define the normals with a node instead.
  13102. *
  13103. * If you don't want to overwrite the normals but modify the existing values instead,
  13104. * use {@link materialNormal}.
  13105. *
  13106. * @type {?Node<vec3>}
  13107. * @default null
  13108. */
  13109. this.normalNode = null;
  13110. /**
  13111. * The opacity of node materials is by default inferred from the `opacity`
  13112. * and `alphaMap` properties. This node property allows to overwrite the default
  13113. * and define the opacity with a node instead.
  13114. *
  13115. * If you don't want to overwrite the normals but modify the existing
  13116. * value instead, use {@link materialOpacity}.
  13117. *
  13118. * @type {?Node<float>}
  13119. * @default null
  13120. */
  13121. this.opacityNode = null;
  13122. /**
  13123. * This node can be used to implement a variety of filter-like effects. The idea is
  13124. * to store the current rendering into a texture e.g. via `viewportSharedTexture()`, use it
  13125. * to create an arbitrary effect and then assign the node composition to this property.
  13126. * Everything behind the object using this material will now be affected by a filter.
  13127. *
  13128. * ```js
  13129. * const material = new NodeMaterial()
  13130. * material.transparent = true;
  13131. *
  13132. * // everything behind the object will be monochromatic
  13133. * material.backdropNode = saturation( viewportSharedTexture().rgb, 0 );
  13134. * ```
  13135. *
  13136. * Backdrop computations are part of the lighting so only lit materials can use this property.
  13137. *
  13138. * @type {?Node<vec3>}
  13139. * @default null
  13140. */
  13141. this.backdropNode = null;
  13142. /**
  13143. * This node allows to modulate the influence of `backdropNode` to the outgoing light.
  13144. *
  13145. * @type {?Node<float>}
  13146. * @default null
  13147. */
  13148. this.backdropAlphaNode = null;
  13149. /**
  13150. * The alpha test of node materials is by default inferred from the `alphaTest`
  13151. * property. This node property allows to overwrite the default and define the
  13152. * alpha test with a node instead.
  13153. *
  13154. * If you don't want to overwrite the alpha test but modify the existing
  13155. * value instead, use {@link materialAlphaTest}.
  13156. *
  13157. * @type {?Node<float>}
  13158. * @default null
  13159. */
  13160. this.alphaTestNode = null;
  13161. /**
  13162. * Discards the fragment if the mask value is `false`.
  13163. *
  13164. * @type {?Node<bool>}
  13165. * @default null
  13166. */
  13167. this.maskNode = null;
  13168. /**
  13169. * The local vertex positions are computed based on multiple factors like the
  13170. * attribute data, morphing or skinning. This node property allows to overwrite
  13171. * the default and define local vertex positions with nodes instead.
  13172. *
  13173. * If you don't want to overwrite the vertex positions but modify the existing
  13174. * values instead, use {@link positionLocal}.
  13175. *
  13176. *```js
  13177. * material.positionNode = positionLocal.add( displace );
  13178. * ```
  13179. *
  13180. * @type {?Node<vec3>}
  13181. * @default null
  13182. */
  13183. this.positionNode = null;
  13184. /**
  13185. * This node property is intended for logic which modifies geometry data once or per animation step.
  13186. * Apps usually place such logic randomly in initialization routines or in the animation loop.
  13187. * `geometryNode` is intended as a dedicated API so there is an intended spot where geometry modifications
  13188. * can be implemented.
  13189. *
  13190. * The idea is to assign a `Fn` definition that holds the geometry modification logic. A typical example
  13191. * would be a GPU based particle system that provides a node material for usage on app level. The particle
  13192. * simulation would be implemented as compute shaders and managed inside a `Fn` function. This function is
  13193. * eventually assigned to `geometryNode`.
  13194. *
  13195. * @type {?Function}
  13196. * @default null
  13197. */
  13198. this.geometryNode = null;
  13199. /**
  13200. * Allows to overwrite depth values in the fragment shader.
  13201. *
  13202. * @type {?Node<float>}
  13203. * @default null
  13204. */
  13205. this.depthNode = null;
  13206. /**
  13207. * Allows to overwrite the position used for shadow map rendering which
  13208. * is by default {@link positionWorld}, the vertex position
  13209. * in world space.
  13210. *
  13211. * @type {?Node<float>}
  13212. * @default null
  13213. */
  13214. this.receivedShadowPositionNode = null;
  13215. /**
  13216. * Allows to overwrite the geometry position used for shadow map projection which
  13217. * is by default {@link positionLocal}, the vertex position in local space.
  13218. *
  13219. * @type {?Node<float>}
  13220. * @default null
  13221. */
  13222. this.castShadowPositionNode = null;
  13223. /**
  13224. * This node can be used to influence how an object using this node material
  13225. * receive shadows.
  13226. *
  13227. * ```js
  13228. * const totalShadows = float( 1 ).toVar();
  13229. * material.receivedShadowNode = Fn( ( [ shadow ] ) => {
  13230. * totalShadows.mulAssign( shadow );
  13231. * //return float( 1 ); // bypass received shadows
  13232. * return shadow.mix( color( 0xff0000 ), 1 ); // modify shadow color
  13233. * } );
  13234. *
  13235. * @type {?(Function|FunctionNode<vec4>)}
  13236. * @default null
  13237. */
  13238. this.receivedShadowNode = null;
  13239. /**
  13240. * This node can be used to influence how an object using this node material
  13241. * casts shadows. To apply a color to shadows, you can simply do:
  13242. *
  13243. * ```js
  13244. * material.castShadowNode = vec4( 1, 0, 0, 1 );
  13245. * ```
  13246. *
  13247. * Which can be nice to fake colored shadows of semi-transparent objects. It
  13248. * is also common to use the property with `Fn` function so checks are performed
  13249. * per fragment.
  13250. *
  13251. * ```js
  13252. * materialCustomShadow.castShadowNode = Fn( () => {
  13253. * hash( vertexIndex ).greaterThan( 0.5 ).discard();
  13254. * return materialColor;
  13255. * } )();
  13256. * ```
  13257. *
  13258. * @type {?Node<vec4>}
  13259. * @default null
  13260. */
  13261. this.castShadowNode = null;
  13262. /**
  13263. * This node can be used to define the final output of the material.
  13264. *
  13265. * TODO: Explain the differences to `fragmentNode`.
  13266. *
  13267. * @type {?Node<vec4>}
  13268. * @default null
  13269. */
  13270. this.outputNode = null;
  13271. /**
  13272. * MRT configuration is done on renderer or pass level. This node allows to
  13273. * overwrite what values are written into MRT targets on material level. This
  13274. * can be useful for implementing selective FX features that should only affect
  13275. * specific objects.
  13276. *
  13277. * @type {?MRTNode}
  13278. * @default null
  13279. */
  13280. this.mrtNode = null;
  13281. /**
  13282. * This node property can be used if you need complete freedom in implementing
  13283. * the fragment shader. Assigning a node will replace the built-in material
  13284. * logic used in the fragment stage.
  13285. *
  13286. * @type {?Node<vec4>}
  13287. * @default null
  13288. */
  13289. this.fragmentNode = null;
  13290. /**
  13291. * This node property can be used if you need complete freedom in implementing
  13292. * the vertex shader. Assigning a node will replace the built-in material logic
  13293. * used in the vertex stage.
  13294. *
  13295. * @type {?Node<vec4>}
  13296. * @default null
  13297. */
  13298. this.vertexNode = null;
  13299. // Deprecated properties
  13300. Object.defineProperty( this, 'shadowPositionNode', { // @deprecated, r176
  13301. get: () => {
  13302. return this.receivedShadowPositionNode;
  13303. },
  13304. set: ( value ) => {
  13305. console.warn( 'THREE.NodeMaterial: ".shadowPositionNode" was renamed to ".receivedShadowPositionNode".' );
  13306. this.receivedShadowPositionNode = value;
  13307. }
  13308. } );
  13309. }
  13310. /**
  13311. * Allows to define a custom cache key that influence the material key computation
  13312. * for render objects.
  13313. *
  13314. * @return {string} The custom cache key.
  13315. */
  13316. customProgramCacheKey() {
  13317. return this.type + getCacheKey$1( this );
  13318. }
  13319. /**
  13320. * Builds this material with the given node builder.
  13321. *
  13322. * @param {NodeBuilder} builder - The current node builder.
  13323. */
  13324. build( builder ) {
  13325. this.setup( builder );
  13326. }
  13327. /**
  13328. * Setups a node material observer with the given builder.
  13329. *
  13330. * @param {NodeBuilder} builder - The current node builder.
  13331. * @return {NodeMaterialObserver} The node material observer.
  13332. */
  13333. setupObserver( builder ) {
  13334. return new NodeMaterialObserver( builder );
  13335. }
  13336. /**
  13337. * Setups the vertex and fragment stage of this node material.
  13338. *
  13339. * @param {NodeBuilder} builder - The current node builder.
  13340. */
  13341. setup( builder ) {
  13342. builder.context.setupNormal = () => subBuild( this.setupNormal( builder ), 'NORMAL', 'vec3' );
  13343. builder.context.setupPositionView = () => this.setupPositionView( builder );
  13344. builder.context.setupModelViewProjection = () => this.setupModelViewProjection( builder );
  13345. const renderer = builder.renderer;
  13346. const renderTarget = renderer.getRenderTarget();
  13347. // < VERTEX STAGE >
  13348. builder.addStack();
  13349. const mvp = subBuild( this.setupVertex( builder ), 'VERTEX' );
  13350. const vertexNode = this.vertexNode || mvp;
  13351. builder.stack.outputNode = vertexNode;
  13352. this.setupHardwareClipping( builder );
  13353. if ( this.geometryNode !== null ) {
  13354. builder.stack.outputNode = builder.stack.outputNode.bypass( this.geometryNode );
  13355. }
  13356. builder.addFlow( 'vertex', builder.removeStack() );
  13357. // < FRAGMENT STAGE >
  13358. builder.addStack();
  13359. let resultNode;
  13360. const clippingNode = this.setupClipping( builder );
  13361. if ( this.depthWrite === true || this.depthTest === true ) {
  13362. // only write depth if depth buffer is configured
  13363. if ( renderTarget !== null ) {
  13364. if ( renderTarget.depthBuffer === true ) this.setupDepth( builder );
  13365. } else {
  13366. if ( renderer.depth === true ) this.setupDepth( builder );
  13367. }
  13368. }
  13369. if ( this.fragmentNode === null ) {
  13370. this.setupDiffuseColor( builder );
  13371. this.setupVariants( builder );
  13372. const outgoingLightNode = this.setupLighting( builder );
  13373. if ( clippingNode !== null ) builder.stack.add( clippingNode );
  13374. // force unsigned floats - useful for RenderTargets
  13375. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  13376. resultNode = this.setupOutput( builder, basicOutput );
  13377. // OUTPUT NODE
  13378. output.assign( resultNode );
  13379. //
  13380. const isCustomOutput = this.outputNode !== null;
  13381. if ( isCustomOutput ) resultNode = this.outputNode;
  13382. // MRT
  13383. if ( renderTarget !== null ) {
  13384. const mrt = renderer.getMRT();
  13385. const materialMRT = this.mrtNode;
  13386. if ( mrt !== null ) {
  13387. if ( isCustomOutput ) output.assign( resultNode );
  13388. resultNode = mrt;
  13389. if ( materialMRT !== null ) {
  13390. resultNode = mrt.merge( materialMRT );
  13391. }
  13392. } else if ( materialMRT !== null ) {
  13393. resultNode = materialMRT;
  13394. }
  13395. }
  13396. } else {
  13397. let fragmentNode = this.fragmentNode;
  13398. if ( fragmentNode.isOutputStructNode !== true ) {
  13399. fragmentNode = vec4( fragmentNode );
  13400. }
  13401. resultNode = this.setupOutput( builder, fragmentNode );
  13402. }
  13403. builder.stack.outputNode = resultNode;
  13404. builder.addFlow( 'fragment', builder.removeStack() );
  13405. // < OBSERVER >
  13406. builder.observer = this.setupObserver( builder );
  13407. }
  13408. /**
  13409. * Setups the clipping node.
  13410. *
  13411. * @param {NodeBuilder} builder - The current node builder.
  13412. * @return {ClippingNode} The clipping node.
  13413. */
  13414. setupClipping( builder ) {
  13415. if ( builder.clippingContext === null ) return null;
  13416. const { unionPlanes, intersectionPlanes } = builder.clippingContext;
  13417. let result = null;
  13418. if ( unionPlanes.length > 0 || intersectionPlanes.length > 0 ) {
  13419. const samples = builder.renderer.samples;
  13420. if ( this.alphaToCoverage && samples > 1 ) {
  13421. // to be added to flow when the color/alpha value has been determined
  13422. result = clippingAlpha();
  13423. } else {
  13424. builder.stack.add( clipping() );
  13425. }
  13426. }
  13427. return result;
  13428. }
  13429. /**
  13430. * Setups the hardware clipping if available on the current device.
  13431. *
  13432. * @param {NodeBuilder} builder - The current node builder.
  13433. */
  13434. setupHardwareClipping( builder ) {
  13435. this.hardwareClipping = false;
  13436. if ( builder.clippingContext === null ) return;
  13437. const candidateCount = builder.clippingContext.unionPlanes.length;
  13438. // 8 planes supported by WebGL ANGLE_clip_cull_distance and WebGPU clip-distances
  13439. if ( candidateCount > 0 && candidateCount <= 8 && builder.isAvailable( 'clipDistance' ) ) {
  13440. builder.stack.add( hardwareClipping() );
  13441. this.hardwareClipping = true;
  13442. }
  13443. return;
  13444. }
  13445. /**
  13446. * Setups the depth of this material.
  13447. *
  13448. * @param {NodeBuilder} builder - The current node builder.
  13449. */
  13450. setupDepth( builder ) {
  13451. const { renderer, camera } = builder;
  13452. // Depth
  13453. let depthNode = this.depthNode;
  13454. if ( depthNode === null ) {
  13455. const mrt = renderer.getMRT();
  13456. if ( mrt && mrt.has( 'depth' ) ) {
  13457. depthNode = mrt.get( 'depth' );
  13458. } else if ( renderer.logarithmicDepthBuffer === true ) {
  13459. if ( camera.isPerspectiveCamera ) {
  13460. depthNode = viewZToLogarithmicDepth( positionView.z, cameraNear, cameraFar );
  13461. } else {
  13462. depthNode = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  13463. }
  13464. }
  13465. }
  13466. if ( depthNode !== null ) {
  13467. depth.assign( depthNode ).toStack();
  13468. }
  13469. }
  13470. /**
  13471. * Setups the position node in view space. This method exists
  13472. * so derived node materials can modify the implementation e.g. sprite materials.
  13473. *
  13474. * @param {NodeBuilder} builder - The current node builder.
  13475. * @return {Node<vec3>} The position in view space.
  13476. */
  13477. setupPositionView( /*builder*/ ) {
  13478. return modelViewMatrix.mul( positionLocal ).xyz;
  13479. }
  13480. /**
  13481. * Setups the position in clip space.
  13482. *
  13483. * @param {NodeBuilder} builder - The current node builder.
  13484. * @return {Node<vec4>} The position in view space.
  13485. */
  13486. setupModelViewProjection( /*builder*/ ) {
  13487. return cameraProjectionMatrix.mul( positionView );
  13488. }
  13489. /**
  13490. * Setups the logic for the vertex stage.
  13491. *
  13492. * @param {NodeBuilder} builder - The current node builder.
  13493. * @return {Node<vec4>} The position in clip space.
  13494. */
  13495. setupVertex( builder ) {
  13496. builder.addStack();
  13497. this.setupPosition( builder );
  13498. builder.context.vertex = builder.removeStack();
  13499. return modelViewProjection;
  13500. }
  13501. /**
  13502. * Setups the computation of the position in local space.
  13503. *
  13504. * @param {NodeBuilder} builder - The current node builder.
  13505. * @return {Node<vec3>} The position in local space.
  13506. */
  13507. setupPosition( builder ) {
  13508. const { object, geometry } = builder;
  13509. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  13510. morphReference( object ).toStack();
  13511. }
  13512. if ( object.isSkinnedMesh === true ) {
  13513. skinning( object ).toStack();
  13514. }
  13515. if ( this.displacementMap ) {
  13516. const displacementMap = materialReference( 'displacementMap', 'texture' );
  13517. const displacementScale = materialReference( 'displacementScale', 'float' );
  13518. const displacementBias = materialReference( 'displacementBias', 'float' );
  13519. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  13520. }
  13521. if ( object.isBatchedMesh ) {
  13522. batch( object ).toStack();
  13523. }
  13524. if ( ( object.isInstancedMesh && object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  13525. instancedMesh( object ).toStack();
  13526. }
  13527. if ( this.positionNode !== null ) {
  13528. positionLocal.assign( subBuild( this.positionNode, 'POSITION', 'vec3' ) );
  13529. }
  13530. return positionLocal;
  13531. }
  13532. /**
  13533. * Setups the computation of the material's diffuse color.
  13534. *
  13535. * @param {NodeBuilder} builder - The current node builder.
  13536. * @param {BufferGeometry} geometry - The geometry.
  13537. */
  13538. setupDiffuseColor( { object, geometry } ) {
  13539. // MASK
  13540. if ( this.maskNode !== null ) {
  13541. // Discard if the mask is `false`
  13542. bool( this.maskNode ).not().discard();
  13543. }
  13544. // COLOR
  13545. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  13546. // VERTEX COLORS
  13547. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  13548. colorNode = colorNode.mul( vertexColor() );
  13549. }
  13550. // INSTANCED COLORS
  13551. if ( object.instanceColor ) {
  13552. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  13553. colorNode = instanceColor.mul( colorNode );
  13554. }
  13555. if ( object.isBatchedMesh && object._colorsTexture ) {
  13556. const batchColor = varyingProperty( 'vec3', 'vBatchColor' );
  13557. colorNode = batchColor.mul( colorNode );
  13558. }
  13559. // DIFFUSE COLOR
  13560. diffuseColor.assign( colorNode );
  13561. // OPACITY
  13562. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  13563. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  13564. // ALPHA TEST
  13565. let alphaTestNode = null;
  13566. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  13567. alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  13568. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  13569. }
  13570. // ALPHA HASH
  13571. if ( this.alphaHash === true ) {
  13572. diffuseColor.a.lessThan( getAlphaHashThreshold( positionLocal ) ).discard();
  13573. }
  13574. // OPAQUE
  13575. const isOpaque = this.transparent === false && this.blending === NormalBlending && this.alphaToCoverage === false;
  13576. if ( isOpaque ) {
  13577. diffuseColor.a.assign( 1.0 );
  13578. } else if ( alphaTestNode === null ) {
  13579. diffuseColor.a.lessThanEqual( 0 ).discard();
  13580. }
  13581. }
  13582. /**
  13583. * Abstract interface method that can be implemented by derived materials
  13584. * to setup material-specific node variables.
  13585. *
  13586. * @abstract
  13587. * @param {NodeBuilder} builder - The current node builder.
  13588. */
  13589. setupVariants( /*builder*/ ) {
  13590. // Interface function.
  13591. }
  13592. /**
  13593. * Setups the outgoing light node variable
  13594. *
  13595. * @return {Node<vec3>} The outgoing light node.
  13596. */
  13597. setupOutgoingLight() {
  13598. return ( this.lights === true ) ? vec3( 0 ) : diffuseColor.rgb;
  13599. }
  13600. /**
  13601. * Setups the normal node from the material.
  13602. *
  13603. * @return {Node<vec3>} The normal node.
  13604. */
  13605. setupNormal() {
  13606. return this.normalNode ? vec3( this.normalNode ) : materialNormal;
  13607. }
  13608. /**
  13609. * Setups the environment node from the material.
  13610. *
  13611. * @param {NodeBuilder} builder - The current node builder.
  13612. * @return {Node<vec4>} The environment node.
  13613. */
  13614. setupEnvironment( /*builder*/ ) {
  13615. let node = null;
  13616. if ( this.envNode ) {
  13617. node = this.envNode;
  13618. } else if ( this.envMap ) {
  13619. node = this.envMap.isCubeTexture ? materialReference( 'envMap', 'cubeTexture' ) : materialReference( 'envMap', 'texture' );
  13620. }
  13621. return node;
  13622. }
  13623. /**
  13624. * Setups the light map node from the material.
  13625. *
  13626. * @param {NodeBuilder} builder - The current node builder.
  13627. * @return {Node<vec3>} The light map node.
  13628. */
  13629. setupLightMap( builder ) {
  13630. let node = null;
  13631. if ( builder.material.lightMap ) {
  13632. node = new IrradianceNode( materialLightMap );
  13633. }
  13634. return node;
  13635. }
  13636. /**
  13637. * Setups the lights node based on the scene, environment and material.
  13638. *
  13639. * @param {NodeBuilder} builder - The current node builder.
  13640. * @return {LightsNode} The lights node.
  13641. */
  13642. setupLights( builder ) {
  13643. const materialLightsNode = [];
  13644. //
  13645. const envNode = this.setupEnvironment( builder );
  13646. if ( envNode && envNode.isLightingNode ) {
  13647. materialLightsNode.push( envNode );
  13648. }
  13649. const lightMapNode = this.setupLightMap( builder );
  13650. if ( lightMapNode && lightMapNode.isLightingNode ) {
  13651. materialLightsNode.push( lightMapNode );
  13652. }
  13653. if ( this.aoNode !== null || builder.material.aoMap ) {
  13654. const aoNode = this.aoNode !== null ? this.aoNode : materialAO;
  13655. materialLightsNode.push( new AONode( aoNode ) );
  13656. }
  13657. let lightsN = this.lightsNode || builder.lightsNode;
  13658. if ( materialLightsNode.length > 0 ) {
  13659. lightsN = builder.renderer.lighting.createNode( [ ...lightsN.getLights(), ...materialLightsNode ] );
  13660. }
  13661. return lightsN;
  13662. }
  13663. /**
  13664. * This method should be implemented by most derived materials
  13665. * since it defines the material's lighting model.
  13666. *
  13667. * @abstract
  13668. * @param {NodeBuilder} builder - The current node builder.
  13669. * @return {LightingModel} The lighting model.
  13670. */
  13671. setupLightingModel( /*builder*/ ) {
  13672. // Interface function.
  13673. }
  13674. /**
  13675. * Setups the outgoing light node.
  13676. *
  13677. * @param {NodeBuilder} builder - The current node builder.
  13678. * @return {Node<vec3>} The outgoing light node.
  13679. */
  13680. setupLighting( builder ) {
  13681. const { material } = builder;
  13682. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  13683. // OUTGOING LIGHT
  13684. const lights = this.lights === true || this.lightsNode !== null;
  13685. const lightsNode = lights ? this.setupLights( builder ) : null;
  13686. let outgoingLightNode = this.setupOutgoingLight( builder );
  13687. if ( lightsNode && lightsNode.getScope().hasLights ) {
  13688. const lightingModel = this.setupLightingModel( builder ) || null;
  13689. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  13690. } else if ( backdropNode !== null ) {
  13691. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  13692. }
  13693. // EMISSIVE
  13694. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  13695. emissive.assign( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  13696. outgoingLightNode = outgoingLightNode.add( emissive );
  13697. }
  13698. return outgoingLightNode;
  13699. }
  13700. /**
  13701. * Setup the fog.
  13702. *
  13703. * @param {NodeBuilder} builder - The current node builder.
  13704. * @param {Node<vec4>} outputNode - The existing output node.
  13705. * @return {Node<vec4>} The output node.
  13706. */
  13707. setupFog( builder, outputNode ) {
  13708. const fogNode = builder.fogNode;
  13709. if ( fogNode ) {
  13710. output.assign( outputNode );
  13711. outputNode = vec4( fogNode.toStack() );
  13712. }
  13713. return outputNode;
  13714. }
  13715. /**
  13716. * Setups premultiplied alpha.
  13717. *
  13718. * @param {NodeBuilder} builder - The current node builder.
  13719. * @param {Node<vec4>} outputNode - The existing output node.
  13720. * @return {Node<vec4>} The output node.
  13721. */
  13722. setupPremultipliedAlpha( builder, outputNode ) {
  13723. return premultiplyAlpha( outputNode );
  13724. }
  13725. /**
  13726. * Setups the output node.
  13727. *
  13728. * @param {NodeBuilder} builder - The current node builder.
  13729. * @param {Node<vec4>} outputNode - The existing output node.
  13730. * @return {Node<vec4>} The output node.
  13731. */
  13732. setupOutput( builder, outputNode ) {
  13733. // FOG
  13734. if ( this.fog === true ) {
  13735. outputNode = this.setupFog( builder, outputNode );
  13736. }
  13737. // PREMULTIPLIED ALPHA
  13738. if ( this.premultipliedAlpha === true ) {
  13739. outputNode = this.setupPremultipliedAlpha( builder, outputNode );
  13740. }
  13741. return outputNode;
  13742. }
  13743. /**
  13744. * Most classic material types have a node pendant e.g. for `MeshBasicMaterial`
  13745. * there is `MeshBasicNodeMaterial`. This utility method is intended for
  13746. * defining all material properties of the classic type in the node type.
  13747. *
  13748. * @param {Material} material - The material to copy properties with their values to this node material.
  13749. */
  13750. setDefaultValues( material ) {
  13751. // This approach is to reuse the native refreshUniforms*
  13752. // and turn available the use of features like transmission and environment in core
  13753. for ( const property in material ) {
  13754. const value = material[ property ];
  13755. if ( this[ property ] === undefined ) {
  13756. this[ property ] = value;
  13757. if ( value && value.clone ) this[ property ] = value.clone();
  13758. }
  13759. }
  13760. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  13761. for ( const key in descriptors ) {
  13762. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  13763. descriptors[ key ].get !== undefined ) {
  13764. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  13765. }
  13766. }
  13767. }
  13768. /**
  13769. * Serializes this material to JSON.
  13770. *
  13771. * @param {?(Object|string)} meta - The meta information for serialization.
  13772. * @return {Object} The serialized node.
  13773. */
  13774. toJSON( meta ) {
  13775. const isRoot = ( meta === undefined || typeof meta === 'string' );
  13776. if ( isRoot ) {
  13777. meta = {
  13778. textures: {},
  13779. images: {},
  13780. nodes: {}
  13781. };
  13782. }
  13783. const data = Material.prototype.toJSON.call( this, meta );
  13784. const nodeChildren = getNodeChildren( this );
  13785. data.inputNodes = {};
  13786. for ( const { property, childNode } of nodeChildren ) {
  13787. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  13788. }
  13789. // TODO: Copied from Object3D.toJSON
  13790. function extractFromCache( cache ) {
  13791. const values = [];
  13792. for ( const key in cache ) {
  13793. const data = cache[ key ];
  13794. delete data.metadata;
  13795. values.push( data );
  13796. }
  13797. return values;
  13798. }
  13799. if ( isRoot ) {
  13800. const textures = extractFromCache( meta.textures );
  13801. const images = extractFromCache( meta.images );
  13802. const nodes = extractFromCache( meta.nodes );
  13803. if ( textures.length > 0 ) data.textures = textures;
  13804. if ( images.length > 0 ) data.images = images;
  13805. if ( nodes.length > 0 ) data.nodes = nodes;
  13806. }
  13807. return data;
  13808. }
  13809. /**
  13810. * Copies the properties of the given node material to this instance.
  13811. *
  13812. * @param {NodeMaterial} source - The material to copy.
  13813. * @return {NodeMaterial} A reference to this node material.
  13814. */
  13815. copy( source ) {
  13816. this.lightsNode = source.lightsNode;
  13817. this.envNode = source.envNode;
  13818. this.colorNode = source.colorNode;
  13819. this.normalNode = source.normalNode;
  13820. this.opacityNode = source.opacityNode;
  13821. this.backdropNode = source.backdropNode;
  13822. this.backdropAlphaNode = source.backdropAlphaNode;
  13823. this.alphaTestNode = source.alphaTestNode;
  13824. this.maskNode = source.maskNode;
  13825. this.positionNode = source.positionNode;
  13826. this.geometryNode = source.geometryNode;
  13827. this.depthNode = source.depthNode;
  13828. this.receivedShadowPositionNode = source.receivedShadowPositionNode;
  13829. this.castShadowPositionNode = source.castShadowPositionNode;
  13830. this.receivedShadowNode = source.receivedShadowNode;
  13831. this.castShadowNode = source.castShadowNode;
  13832. this.outputNode = source.outputNode;
  13833. this.mrtNode = source.mrtNode;
  13834. this.fragmentNode = source.fragmentNode;
  13835. this.vertexNode = source.vertexNode;
  13836. return super.copy( source );
  13837. }
  13838. }
  13839. const _defaultValues$d = /*@__PURE__*/ new LineBasicMaterial();
  13840. /**
  13841. * Node material version of {@link LineBasicMaterial}.
  13842. *
  13843. * @augments NodeMaterial
  13844. */
  13845. class LineBasicNodeMaterial extends NodeMaterial {
  13846. static get type() {
  13847. return 'LineBasicNodeMaterial';
  13848. }
  13849. /**
  13850. * Constructs a new line basic node material.
  13851. *
  13852. * @param {Object} [parameters] - The configuration parameter.
  13853. */
  13854. constructor( parameters ) {
  13855. super();
  13856. /**
  13857. * This flag can be used for type testing.
  13858. *
  13859. * @type {boolean}
  13860. * @readonly
  13861. * @default true
  13862. */
  13863. this.isLineBasicNodeMaterial = true;
  13864. this.setDefaultValues( _defaultValues$d );
  13865. this.setValues( parameters );
  13866. }
  13867. }
  13868. const _defaultValues$c = /*@__PURE__*/ new LineDashedMaterial();
  13869. /**
  13870. * Node material version of {@link LineDashedMaterial}.
  13871. *
  13872. * @augments NodeMaterial
  13873. */
  13874. class LineDashedNodeMaterial extends NodeMaterial {
  13875. static get type() {
  13876. return 'LineDashedNodeMaterial';
  13877. }
  13878. /**
  13879. * Constructs a new line dashed node material.
  13880. *
  13881. * @param {Object} [parameters] - The configuration parameter.
  13882. */
  13883. constructor( parameters ) {
  13884. super();
  13885. /**
  13886. * This flag can be used for type testing.
  13887. *
  13888. * @type {boolean}
  13889. * @readonly
  13890. * @default true
  13891. */
  13892. this.isLineDashedNodeMaterial = true;
  13893. this.setDefaultValues( _defaultValues$c );
  13894. /**
  13895. * The dash offset.
  13896. *
  13897. * @type {number}
  13898. * @default 0
  13899. */
  13900. this.dashOffset = 0;
  13901. /**
  13902. * The offset of dash materials is by default inferred from the `dashOffset`
  13903. * property. This node property allows to overwrite the default
  13904. * and define the offset with a node instead.
  13905. *
  13906. * If you don't want to overwrite the offset but modify the existing
  13907. * value instead, use {@link materialLineDashOffset}.
  13908. *
  13909. * @type {?Node<float>}
  13910. * @default null
  13911. */
  13912. this.offsetNode = null;
  13913. /**
  13914. * The scale of dash materials is by default inferred from the `scale`
  13915. * property. This node property allows to overwrite the default
  13916. * and define the scale with a node instead.
  13917. *
  13918. * If you don't want to overwrite the scale but modify the existing
  13919. * value instead, use {@link materialLineScale}.
  13920. *
  13921. * @type {?Node<float>}
  13922. * @default null
  13923. */
  13924. this.dashScaleNode = null;
  13925. /**
  13926. * The dash size of dash materials is by default inferred from the `dashSize`
  13927. * property. This node property allows to overwrite the default
  13928. * and define the dash size with a node instead.
  13929. *
  13930. * If you don't want to overwrite the dash size but modify the existing
  13931. * value instead, use {@link materialLineDashSize}.
  13932. *
  13933. * @type {?Node<float>}
  13934. * @default null
  13935. */
  13936. this.dashSizeNode = null;
  13937. /**
  13938. * The gap size of dash materials is by default inferred from the `gapSize`
  13939. * property. This node property allows to overwrite the default
  13940. * and define the gap size with a node instead.
  13941. *
  13942. * If you don't want to overwrite the gap size but modify the existing
  13943. * value instead, use {@link materialLineGapSize}.
  13944. *
  13945. * @type {?Node<float>}
  13946. * @default null
  13947. */
  13948. this.gapSizeNode = null;
  13949. this.setValues( parameters );
  13950. }
  13951. /**
  13952. * Setups the dash specific node variables.
  13953. *
  13954. * @param {NodeBuilder} builder - The current node builder.
  13955. */
  13956. setupVariants( /* builder */ ) {
  13957. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  13958. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  13959. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  13960. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  13961. dashSize.assign( dashSizeNode );
  13962. gapSize.assign( gapSizeNode );
  13963. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  13964. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  13965. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  13966. }
  13967. }
  13968. let _sharedFramebuffer = null;
  13969. /**
  13970. * `ViewportTextureNode` creates an internal texture for each node instance. This module
  13971. * shares a texture across all instances of `ViewportSharedTextureNode`. It should
  13972. * be the first choice when using data of the default/screen framebuffer for performance reasons.
  13973. *
  13974. * @augments ViewportTextureNode
  13975. */
  13976. class ViewportSharedTextureNode extends ViewportTextureNode {
  13977. static get type() {
  13978. return 'ViewportSharedTextureNode';
  13979. }
  13980. /**
  13981. * Constructs a new viewport shared texture node.
  13982. *
  13983. * @param {Node} [uvNode=screenUV] - The uv node.
  13984. * @param {?Node} [levelNode=null] - The level node.
  13985. */
  13986. constructor( uvNode = screenUV, levelNode = null ) {
  13987. if ( _sharedFramebuffer === null ) {
  13988. _sharedFramebuffer = new FramebufferTexture();
  13989. }
  13990. super( uvNode, levelNode, _sharedFramebuffer );
  13991. }
  13992. updateReference() {
  13993. return this;
  13994. }
  13995. }
  13996. /**
  13997. * TSL function for creating a shared viewport texture node.
  13998. *
  13999. * @tsl
  14000. * @function
  14001. * @param {?Node} [uvNode=screenUV] - The uv node.
  14002. * @param {?Node} [levelNode=null] - The level node.
  14003. * @returns {ViewportSharedTextureNode}
  14004. */
  14005. const viewportSharedTexture = /*@__PURE__*/ nodeProxy( ViewportSharedTextureNode ).setParameterLength( 0, 2 );
  14006. const _defaultValues$b = /*@__PURE__*/ new LineDashedMaterial();
  14007. /**
  14008. * This node material can be used to render lines with a size larger than one
  14009. * by representing them as instanced meshes.
  14010. *
  14011. * @augments NodeMaterial
  14012. */
  14013. class Line2NodeMaterial extends NodeMaterial {
  14014. static get type() {
  14015. return 'Line2NodeMaterial';
  14016. }
  14017. /**
  14018. * Constructs a new node material for wide line rendering.
  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.isLine2NodeMaterial = true;
  14032. this.setDefaultValues( _defaultValues$b );
  14033. /**
  14034. * Whether vertex colors should be used or not.
  14035. *
  14036. * @type {boolean}
  14037. * @default false
  14038. */
  14039. this.useColor = parameters.vertexColors;
  14040. /**
  14041. * The dash offset.
  14042. *
  14043. * @type {number}
  14044. * @default 0
  14045. */
  14046. this.dashOffset = 0;
  14047. /**
  14048. * Defines the lines color.
  14049. *
  14050. * @type {?Node<vec3>}
  14051. * @default null
  14052. */
  14053. this.lineColorNode = null;
  14054. /**
  14055. * Defines the offset.
  14056. *
  14057. * @type {?Node<float>}
  14058. * @default null
  14059. */
  14060. this.offsetNode = null;
  14061. /**
  14062. * Defines the dash scale.
  14063. *
  14064. * @type {?Node<float>}
  14065. * @default null
  14066. */
  14067. this.dashScaleNode = null;
  14068. /**
  14069. * Defines the dash size.
  14070. *
  14071. * @type {?Node<float>}
  14072. * @default null
  14073. */
  14074. this.dashSizeNode = null;
  14075. /**
  14076. * Defines the gap size.
  14077. *
  14078. * @type {?Node<float>}
  14079. * @default null
  14080. */
  14081. this.gapSizeNode = null;
  14082. /**
  14083. * Blending is set to `NoBlending` since transparency
  14084. * is not supported, yet.
  14085. *
  14086. * @type {number}
  14087. * @default 0
  14088. */
  14089. this.blending = NoBlending;
  14090. this._useDash = parameters.dashed;
  14091. this._useAlphaToCoverage = true;
  14092. this._useWorldUnits = false;
  14093. this.setValues( parameters );
  14094. }
  14095. /**
  14096. * Setups the vertex and fragment stage of this node material.
  14097. *
  14098. * @param {NodeBuilder} builder - The current node builder.
  14099. */
  14100. setup( builder ) {
  14101. const { renderer } = builder;
  14102. const useAlphaToCoverage = this._useAlphaToCoverage;
  14103. const useColor = this.useColor;
  14104. const useDash = this._useDash;
  14105. const useWorldUnits = this._useWorldUnits;
  14106. const trimSegment = Fn( ( { start, end } ) => {
  14107. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  14108. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  14109. const nearEstimate = b.mul( -0.5 ).div( a );
  14110. const alpha = nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  14111. return vec4( mix( start.xyz, end.xyz, alpha ), end.w );
  14112. } ).setLayout( {
  14113. name: 'trimSegment',
  14114. type: 'vec4',
  14115. inputs: [
  14116. { name: 'start', type: 'vec4' },
  14117. { name: 'end', type: 'vec4' }
  14118. ]
  14119. } );
  14120. this.vertexNode = Fn( () => {
  14121. const instanceStart = attribute( 'instanceStart' );
  14122. const instanceEnd = attribute( 'instanceEnd' );
  14123. // camera space
  14124. const start = vec4( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ).toVar( 'start' );
  14125. const end = vec4( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) ).toVar( 'end' );
  14126. if ( useDash ) {
  14127. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  14128. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  14129. const instanceDistanceStart = attribute( 'instanceDistanceStart' );
  14130. const instanceDistanceEnd = attribute( 'instanceDistanceEnd' );
  14131. let lineDistance = positionGeometry.y.lessThan( 0.5 ).select( dashScaleNode.mul( instanceDistanceStart ), dashScaleNode.mul( instanceDistanceEnd ) );
  14132. lineDistance = lineDistance.add( offsetNode );
  14133. varyingProperty( 'float', 'lineDistance' ).assign( lineDistance );
  14134. }
  14135. if ( useWorldUnits ) {
  14136. varyingProperty( 'vec3', 'worldStart' ).assign( start.xyz );
  14137. varyingProperty( 'vec3', 'worldEnd' ).assign( end.xyz );
  14138. }
  14139. const aspect = viewport.z.div( viewport.w );
  14140. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  14141. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  14142. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  14143. // perhaps there is a more elegant solution -- WestLangley
  14144. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( -1 ); // 4th entry in the 3rd column
  14145. If( perspective, () => {
  14146. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  14147. end.assign( trimSegment( { start: start, end: end } ) );
  14148. } ).ElseIf( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  14149. start.assign( trimSegment( { start: end, end: start } ) );
  14150. } );
  14151. } );
  14152. // clip space
  14153. const clipStart = cameraProjectionMatrix.mul( start );
  14154. const clipEnd = cameraProjectionMatrix.mul( end );
  14155. // ndc space
  14156. const ndcStart = clipStart.xyz.div( clipStart.w );
  14157. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  14158. // direction
  14159. const dir = ndcEnd.xy.sub( ndcStart.xy ).toVar();
  14160. // account for clip-space aspect ratio
  14161. dir.x.assign( dir.x.mul( aspect ) );
  14162. dir.assign( dir.normalize() );
  14163. const clip = vec4().toVar();
  14164. if ( useWorldUnits ) {
  14165. // get the offset direction as perpendicular to the view vector
  14166. const worldDir = end.xyz.sub( start.xyz ).normalize();
  14167. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  14168. const worldUp = worldDir.cross( tmpFwd ).normalize();
  14169. const worldFwd = worldDir.cross( worldUp );
  14170. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  14171. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).select( start, end ) );
  14172. // height offset
  14173. const hw = materialLineWidth.mul( 0.5 );
  14174. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).select( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  14175. // don't extend the line if we're rendering dashes because we
  14176. // won't be rendering the endcaps
  14177. if ( ! useDash ) {
  14178. // cap extension
  14179. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).select( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  14180. // add width to the box
  14181. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  14182. // endcaps
  14183. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  14184. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  14185. } );
  14186. }
  14187. // project the worldpos
  14188. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  14189. // shift the depth of the projected points so the line
  14190. // segments overlap neatly
  14191. const clipPose = vec3().toVar();
  14192. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).select( ndcStart, ndcEnd ) );
  14193. clip.z.assign( clipPose.z.mul( clip.w ) );
  14194. } else {
  14195. const offset = vec2( dir.y, dir.x.negate() ).toVar( 'offset' );
  14196. // undo aspect ratio adjustment
  14197. dir.x.assign( dir.x.div( aspect ) );
  14198. offset.x.assign( offset.x.div( aspect ) );
  14199. // sign flip
  14200. offset.assign( positionGeometry.x.lessThan( 0.0 ).select( offset.negate(), offset ) );
  14201. // endcaps
  14202. If( positionGeometry.y.lessThan( 0.0 ), () => {
  14203. offset.assign( offset.sub( dir ) );
  14204. } ).ElseIf( positionGeometry.y.greaterThan( 1.0 ), () => {
  14205. offset.assign( offset.add( dir ) );
  14206. } );
  14207. // adjust for linewidth
  14208. offset.assign( offset.mul( materialLineWidth ) );
  14209. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  14210. offset.assign( offset.div( viewport.w ) );
  14211. // select end
  14212. clip.assign( positionGeometry.y.lessThan( 0.5 ).select( clipStart, clipEnd ) );
  14213. // back to clip space
  14214. offset.assign( offset.mul( clip.w ) );
  14215. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  14216. }
  14217. return clip;
  14218. } )();
  14219. const closestLineToLine = Fn( ( { p1, p2, p3, p4 } ) => {
  14220. const p13 = p1.sub( p3 );
  14221. const p43 = p4.sub( p3 );
  14222. const p21 = p2.sub( p1 );
  14223. const d1343 = p13.dot( p43 );
  14224. const d4321 = p43.dot( p21 );
  14225. const d1321 = p13.dot( p21 );
  14226. const d4343 = p43.dot( p43 );
  14227. const d2121 = p21.dot( p21 );
  14228. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  14229. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  14230. const mua = numer.div( denom ).clamp();
  14231. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  14232. return vec2( mua, mub );
  14233. } );
  14234. this.colorNode = Fn( () => {
  14235. const vUv = uv$1();
  14236. if ( useDash ) {
  14237. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  14238. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  14239. dashSize.assign( dashSizeNode );
  14240. gapSize.assign( gapSizeNode );
  14241. const vLineDistance = varyingProperty( 'float', 'lineDistance' );
  14242. vUv.y.lessThan( -1 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  14243. vLineDistance.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  14244. }
  14245. const alpha = float( 1 ).toVar( 'alpha' );
  14246. if ( useWorldUnits ) {
  14247. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  14248. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  14249. // Find the closest points on the view ray and the line segment
  14250. const rayEnd = varyingProperty( 'vec4', 'worldPos' ).xyz.normalize().mul( 1e5 );
  14251. const lineDir = worldEnd.sub( worldStart );
  14252. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  14253. const p1 = worldStart.add( lineDir.mul( params.x ) );
  14254. const p2 = rayEnd.mul( params.y );
  14255. const delta = p1.sub( p2 );
  14256. const len = delta.length();
  14257. const norm = len.div( materialLineWidth );
  14258. if ( ! useDash ) {
  14259. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  14260. const dnorm = norm.fwidth();
  14261. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  14262. } else {
  14263. norm.greaterThan( 0.5 ).discard();
  14264. }
  14265. }
  14266. } else {
  14267. // round endcaps
  14268. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  14269. const a = vUv.x;
  14270. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  14271. const len2 = a.mul( a ).add( b.mul( b ) );
  14272. const dlen = float( len2.fwidth() ).toVar( 'dlen' );
  14273. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  14274. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  14275. } );
  14276. } else {
  14277. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  14278. const a = vUv.x;
  14279. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  14280. const len2 = a.mul( a ).add( b.mul( b ) );
  14281. len2.greaterThan( 1.0 ).discard();
  14282. } );
  14283. }
  14284. }
  14285. let lineColorNode;
  14286. if ( this.lineColorNode ) {
  14287. lineColorNode = this.lineColorNode;
  14288. } else {
  14289. if ( useColor ) {
  14290. const instanceColorStart = attribute( 'instanceColorStart' );
  14291. const instanceColorEnd = attribute( 'instanceColorEnd' );
  14292. const instanceColor = positionGeometry.y.lessThan( 0.5 ).select( instanceColorStart, instanceColorEnd );
  14293. lineColorNode = instanceColor.mul( materialColor );
  14294. } else {
  14295. lineColorNode = materialColor;
  14296. }
  14297. }
  14298. return vec4( lineColorNode, alpha );
  14299. } )();
  14300. if ( this.transparent ) {
  14301. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  14302. this.outputNode = vec4( this.colorNode.rgb.mul( opacityNode ).add( viewportSharedTexture().rgb.mul( opacityNode.oneMinus() ) ), this.colorNode.a );
  14303. }
  14304. super.setup( builder );
  14305. }
  14306. /**
  14307. * Whether the lines should sized in world units or not.
  14308. * When set to `false` the unit is pixel.
  14309. *
  14310. * @type {boolean}
  14311. * @default false
  14312. */
  14313. get worldUnits() {
  14314. return this._useWorldUnits;
  14315. }
  14316. set worldUnits( value ) {
  14317. if ( this._useWorldUnits !== value ) {
  14318. this._useWorldUnits = value;
  14319. this.needsUpdate = true;
  14320. }
  14321. }
  14322. /**
  14323. * Whether the lines should be dashed or not.
  14324. *
  14325. * @type {boolean}
  14326. * @default false
  14327. */
  14328. get dashed() {
  14329. return this._useDash;
  14330. }
  14331. set dashed( value ) {
  14332. if ( this._useDash !== value ) {
  14333. this._useDash = value;
  14334. this.needsUpdate = true;
  14335. }
  14336. }
  14337. /**
  14338. * Whether alpha to coverage should be used or not.
  14339. *
  14340. * @type {boolean}
  14341. * @default true
  14342. */
  14343. get alphaToCoverage() {
  14344. return this._useAlphaToCoverage;
  14345. }
  14346. set alphaToCoverage( value ) {
  14347. if ( this._useAlphaToCoverage !== value ) {
  14348. this._useAlphaToCoverage = value;
  14349. this.needsUpdate = true;
  14350. }
  14351. }
  14352. }
  14353. /**
  14354. * Packs a direction vector into a color value.
  14355. *
  14356. * @tsl
  14357. * @function
  14358. * @param {Node<vec3>} node - The direction to pack.
  14359. * @return {Node<vec3>} The color.
  14360. */
  14361. const directionToColor = ( node ) => nodeObject( node ).mul( 0.5 ).add( 0.5 );
  14362. /**
  14363. * Unpacks a color value into a direction vector.
  14364. *
  14365. * @tsl
  14366. * @function
  14367. * @param {Node<vec3>} node - The color to unpack.
  14368. * @return {Node<vec3>} The direction.
  14369. */
  14370. const colorToDirection = ( node ) => nodeObject( node ).mul( 2.0 ).sub( 1 );
  14371. const _defaultValues$a = /*@__PURE__*/ new MeshNormalMaterial();
  14372. /**
  14373. * Node material version of {@link MeshNormalMaterial}.
  14374. *
  14375. * @augments NodeMaterial
  14376. */
  14377. class MeshNormalNodeMaterial extends NodeMaterial {
  14378. static get type() {
  14379. return 'MeshNormalNodeMaterial';
  14380. }
  14381. /**
  14382. * Constructs a new mesh normal node material.
  14383. *
  14384. * @param {Object} [parameters] - The configuration parameter.
  14385. */
  14386. constructor( parameters ) {
  14387. super();
  14388. /**
  14389. * This flag can be used for type testing.
  14390. *
  14391. * @type {boolean}
  14392. * @readonly
  14393. * @default true
  14394. */
  14395. this.isMeshNormalNodeMaterial = true;
  14396. this.setDefaultValues( _defaultValues$a );
  14397. this.setValues( parameters );
  14398. }
  14399. /**
  14400. * Overwrites the default implementation by computing the diffuse color
  14401. * based on the normal data.
  14402. */
  14403. setupDiffuseColor() {
  14404. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  14405. // By convention, a normal packed to RGB is in sRGB color space. Convert it to working color space.
  14406. diffuseColor.assign( colorSpaceToWorking( vec4( directionToColor( normalView ), opacityNode ), SRGBColorSpace ) );
  14407. }
  14408. }
  14409. /**
  14410. * TSL function for creating an equirect uv node.
  14411. *
  14412. * Can be used to compute texture coordinates for projecting an
  14413. * equirectangular texture onto a mesh for using it as the scene's
  14414. * background.
  14415. *
  14416. * ```js
  14417. * scene.backgroundNode = texture( equirectTexture, equirectUV() );
  14418. * ```
  14419. *
  14420. * @tsl
  14421. * @function
  14422. * @param {?Node<vec3>} [dirNode=positionWorldDirection] - A direction vector for sampling which is by default `positionWorldDirection`.
  14423. * @returns {Node<vec2>}
  14424. */
  14425. const equirectUV = /*@__PURE__*/ Fn( ( [ dir = positionWorldDirection ] ) => {
  14426. const u = dir.z.atan( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  14427. const v = dir.y.clamp( -1, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  14428. return vec2( u, v );
  14429. } );
  14430. // @TODO: Consider rename WebGLCubeRenderTarget to just CubeRenderTarget
  14431. /**
  14432. * This class represents a cube render target. It is a special version
  14433. * of `WebGLCubeRenderTarget` which is compatible with `WebGPURenderer`.
  14434. *
  14435. * @augments WebGLCubeRenderTarget
  14436. */
  14437. class CubeRenderTarget extends WebGLCubeRenderTarget {
  14438. /**
  14439. * Constructs a new cube render target.
  14440. *
  14441. * @param {number} [size=1] - The size of the render target.
  14442. * @param {RenderTarget~Options} [options] - The configuration object.
  14443. */
  14444. constructor( size = 1, options = {} ) {
  14445. super( size, options );
  14446. /**
  14447. * This flag can be used for type testing.
  14448. *
  14449. * @type {boolean}
  14450. * @readonly
  14451. * @default true
  14452. */
  14453. this.isCubeRenderTarget = true;
  14454. }
  14455. /**
  14456. * Converts the given equirectangular texture to a cube map.
  14457. *
  14458. * @param {Renderer} renderer - The renderer.
  14459. * @param {Texture} texture - The equirectangular texture.
  14460. * @return {CubeRenderTarget} A reference to this cube render target.
  14461. */
  14462. fromEquirectangularTexture( renderer, texture$1 ) {
  14463. const currentMinFilter = texture$1.minFilter;
  14464. const currentGenerateMipmaps = texture$1.generateMipmaps;
  14465. texture$1.generateMipmaps = true;
  14466. this.texture.type = texture$1.type;
  14467. this.texture.colorSpace = texture$1.colorSpace;
  14468. this.texture.generateMipmaps = texture$1.generateMipmaps;
  14469. this.texture.minFilter = texture$1.minFilter;
  14470. this.texture.magFilter = texture$1.magFilter;
  14471. const geometry = new BoxGeometry( 5, 5, 5 );
  14472. const uvNode = equirectUV( positionWorldDirection );
  14473. const material = new NodeMaterial();
  14474. material.colorNode = texture( texture$1, uvNode, 0 );
  14475. material.side = BackSide;
  14476. material.blending = NoBlending;
  14477. const mesh = new Mesh( geometry, material );
  14478. const scene = new Scene();
  14479. scene.add( mesh );
  14480. // Avoid blurred poles
  14481. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  14482. const camera = new CubeCamera( 1, 10, this );
  14483. const currentMRT = renderer.getMRT();
  14484. renderer.setMRT( null );
  14485. camera.update( renderer, scene );
  14486. renderer.setMRT( currentMRT );
  14487. texture$1.minFilter = currentMinFilter;
  14488. texture$1.currentGenerateMipmaps = currentGenerateMipmaps;
  14489. mesh.geometry.dispose();
  14490. mesh.material.dispose();
  14491. return this;
  14492. }
  14493. }
  14494. const _cache$1 = new WeakMap();
  14495. /**
  14496. * This node can be used to automatically convert environment maps in the
  14497. * equirectangular format into the cube map format.
  14498. *
  14499. * @augments TempNode
  14500. */
  14501. class CubeMapNode extends TempNode {
  14502. static get type() {
  14503. return 'CubeMapNode';
  14504. }
  14505. /**
  14506. * Constructs a new cube map node.
  14507. *
  14508. * @param {Node} envNode - The node representing the environment map.
  14509. */
  14510. constructor( envNode ) {
  14511. super( 'vec3' );
  14512. /**
  14513. * The node representing the environment map.
  14514. *
  14515. * @type {Node}
  14516. */
  14517. this.envNode = envNode;
  14518. /**
  14519. * A reference to the internal cube texture.
  14520. *
  14521. * @private
  14522. * @type {?CubeTexture}
  14523. * @default null
  14524. */
  14525. this._cubeTexture = null;
  14526. /**
  14527. * A reference to the internal cube texture node.
  14528. *
  14529. * @private
  14530. * @type {CubeTextureNode}
  14531. */
  14532. this._cubeTextureNode = cubeTexture( null );
  14533. const defaultTexture = new CubeTexture();
  14534. defaultTexture.isRenderTargetTexture = true;
  14535. /**
  14536. * A default cube texture that acts as a placeholder.
  14537. * It is used when the conversion from equirectangular to cube
  14538. * map has not finished yet for a given texture.
  14539. *
  14540. * @private
  14541. * @type {CubeTexture}
  14542. */
  14543. this._defaultTexture = defaultTexture;
  14544. /**
  14545. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  14546. * the texture once per render in its {@link CubeMapNode#updateBefore} method.
  14547. *
  14548. * @type {string}
  14549. * @default 'render'
  14550. */
  14551. this.updateBeforeType = NodeUpdateType.RENDER;
  14552. }
  14553. updateBefore( frame ) {
  14554. const { renderer, material } = frame;
  14555. const envNode = this.envNode;
  14556. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  14557. const texture = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  14558. if ( texture && texture.isTexture ) {
  14559. const mapping = texture.mapping;
  14560. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  14561. // check for converted cubemap map
  14562. if ( _cache$1.has( texture ) ) {
  14563. const cubeMap = _cache$1.get( texture );
  14564. mapTextureMapping( cubeMap, texture.mapping );
  14565. this._cubeTexture = cubeMap;
  14566. } else {
  14567. // create cube map from equirectangular map
  14568. const image = texture.image;
  14569. if ( isEquirectangularMapReady$1( image ) ) {
  14570. const renderTarget = new CubeRenderTarget( image.height );
  14571. renderTarget.fromEquirectangularTexture( renderer, texture );
  14572. mapTextureMapping( renderTarget.texture, texture.mapping );
  14573. this._cubeTexture = renderTarget.texture;
  14574. _cache$1.set( texture, renderTarget.texture );
  14575. texture.addEventListener( 'dispose', onTextureDispose );
  14576. } else {
  14577. // default cube texture as fallback when equirectangular texture is not yet loaded
  14578. this._cubeTexture = this._defaultTexture;
  14579. }
  14580. }
  14581. //
  14582. this._cubeTextureNode.value = this._cubeTexture;
  14583. } else {
  14584. // envNode already refers to a cube map
  14585. this._cubeTextureNode = this.envNode;
  14586. }
  14587. }
  14588. }
  14589. }
  14590. setup( builder ) {
  14591. this.updateBefore( builder );
  14592. return this._cubeTextureNode;
  14593. }
  14594. }
  14595. /**
  14596. * Returns true if the given equirectangular image has been fully loaded
  14597. * and is ready for further processing.
  14598. *
  14599. * @private
  14600. * @param {Image} image - The equirectangular image to check.
  14601. * @return {boolean} Whether the image is ready or not.
  14602. */
  14603. function isEquirectangularMapReady$1( image ) {
  14604. if ( image === null || image === undefined ) return false;
  14605. return image.height > 0;
  14606. }
  14607. /**
  14608. * This function is executed when `dispose()` is called on the equirectangular
  14609. * texture. In this case, the generated cube map with its render target
  14610. * is deleted as well.
  14611. *
  14612. * @private
  14613. * @param {Object} event - The event object.
  14614. */
  14615. function onTextureDispose( event ) {
  14616. const texture = event.target;
  14617. texture.removeEventListener( 'dispose', onTextureDispose );
  14618. const renderTarget = _cache$1.get( texture );
  14619. if ( renderTarget !== undefined ) {
  14620. _cache$1.delete( texture );
  14621. renderTarget.dispose();
  14622. }
  14623. }
  14624. /**
  14625. * This function makes sure the generated cube map uses the correct
  14626. * texture mapping that corresponds to the equirectangular original.
  14627. *
  14628. * @private
  14629. * @param {Texture} texture - The cube texture.
  14630. * @param {number} mapping - The original texture mapping.
  14631. */
  14632. function mapTextureMapping( texture, mapping ) {
  14633. if ( mapping === EquirectangularReflectionMapping ) {
  14634. texture.mapping = CubeReflectionMapping;
  14635. } else if ( mapping === EquirectangularRefractionMapping ) {
  14636. texture.mapping = CubeRefractionMapping;
  14637. }
  14638. }
  14639. /**
  14640. * TSL function for creating a cube map node.
  14641. *
  14642. * @tsl
  14643. * @function
  14644. * @param {Node} envNode - The node representing the environment map.
  14645. * @returns {CubeMapNode}
  14646. */
  14647. const cubeMapNode = /*@__PURE__*/ nodeProxy( CubeMapNode ).setParameterLength( 1 );
  14648. /**
  14649. * Represents a basic model for Image-based lighting (IBL). The environment
  14650. * is defined via environment maps in the equirectangular or cube map format.
  14651. * `BasicEnvironmentNode` is intended for non-PBR materials like {@link MeshBasicNodeMaterial}
  14652. * or {@link MeshPhongNodeMaterial}.
  14653. *
  14654. * @augments LightingNode
  14655. */
  14656. class BasicEnvironmentNode extends LightingNode {
  14657. static get type() {
  14658. return 'BasicEnvironmentNode';
  14659. }
  14660. /**
  14661. * Constructs a new basic environment node.
  14662. *
  14663. * @param {Node} [envNode=null] - A node representing the environment.
  14664. */
  14665. constructor( envNode = null ) {
  14666. super();
  14667. /**
  14668. * A node representing the environment.
  14669. *
  14670. * @type {Node}
  14671. * @default null
  14672. */
  14673. this.envNode = envNode;
  14674. }
  14675. setup( builder ) {
  14676. // environment property is used in the finish() method of BasicLightingModel
  14677. builder.context.environment = cubeMapNode( this.envNode );
  14678. }
  14679. }
  14680. /**
  14681. * A specific version of {@link IrradianceNode} that is only relevant
  14682. * for {@link MeshBasicNodeMaterial}. Since the material is unlit, it
  14683. * requires a special scaling factor for the light map.
  14684. *
  14685. * @augments LightingNode
  14686. */
  14687. class BasicLightMapNode extends LightingNode {
  14688. static get type() {
  14689. return 'BasicLightMapNode';
  14690. }
  14691. /**
  14692. * Constructs a new basic light map node.
  14693. *
  14694. * @param {?Node<vec3>} [lightMapNode=null] - The light map node.
  14695. */
  14696. constructor( lightMapNode = null ) {
  14697. super();
  14698. /**
  14699. * The light map node.
  14700. *
  14701. * @type {?Node<vec3>}
  14702. */
  14703. this.lightMapNode = lightMapNode;
  14704. }
  14705. setup( builder ) {
  14706. // irradianceLightMap property is used in the indirectDiffuse() method of BasicLightingModel
  14707. const RECIPROCAL_PI = float( 1 / Math.PI );
  14708. builder.context.irradianceLightMap = this.lightMapNode.mul( RECIPROCAL_PI );
  14709. }
  14710. }
  14711. /**
  14712. * Abstract class for implementing lighting models. The module defines
  14713. * multiple methods that concrete lighting models can implement. These
  14714. * methods are executed at different points during the light evaluation
  14715. * process.
  14716. */
  14717. class LightingModel {
  14718. /**
  14719. * This method is intended for setting up lighting model and context data
  14720. * which are later used in the evaluation process.
  14721. *
  14722. * @abstract
  14723. * @param {NodeBuilder} builder - The current node builder.
  14724. */
  14725. start( builder ) {
  14726. // lights ( direct )
  14727. builder.lightsNode.setupLights( builder, builder.lightsNode.getLightNodes( builder ) );
  14728. // indirect
  14729. this.indirect( builder );
  14730. }
  14731. /**
  14732. * This method is intended for executing final tasks like final updates
  14733. * to the outgoing light.
  14734. *
  14735. * @abstract
  14736. * @param {NodeBuilder} builder - The current node builder.
  14737. */
  14738. finish( /*builder*/ ) { }
  14739. /**
  14740. * This method is intended for implementing the direct light term and
  14741. * executed during the build process of directional, point and spot light nodes.
  14742. *
  14743. * @abstract
  14744. * @param {Object} lightData - The light data.
  14745. * @param {NodeBuilder} builder - The current node builder.
  14746. */
  14747. direct( /*lightData, builder*/ ) { }
  14748. /**
  14749. * This method is intended for implementing the direct light term for
  14750. * rect area light nodes.
  14751. *
  14752. * @abstract
  14753. * @param {Object} lightData - The light data.
  14754. * @param {NodeBuilder} builder - The current node builder.
  14755. */
  14756. directRectArea( /*lightData, builder*/ ) {}
  14757. /**
  14758. * This method is intended for implementing the indirect light term.
  14759. *
  14760. * @abstract
  14761. * @param {NodeBuilder} builder - The current node builder.
  14762. */
  14763. indirect( /*builder*/ ) { }
  14764. /**
  14765. * This method is intended for implementing the ambient occlusion term.
  14766. * Unlike other methods, this method must be called manually by the lighting
  14767. * model in its indirect term.
  14768. *
  14769. * @abstract
  14770. * @param {NodeBuilder} builder - The current node builder.
  14771. */
  14772. ambientOcclusion( /*input, stack, builder*/ ) { }
  14773. }
  14774. /**
  14775. * Represents the lighting model for unlit materials. The only light contribution
  14776. * is baked indirect lighting modulated with ambient occlusion and the material's
  14777. * diffuse color. Environment mapping is supported. Used in {@link MeshBasicNodeMaterial}.
  14778. *
  14779. * @augments LightingModel
  14780. */
  14781. class BasicLightingModel extends LightingModel {
  14782. /**
  14783. * Constructs a new basic lighting model.
  14784. */
  14785. constructor() {
  14786. super();
  14787. }
  14788. /**
  14789. * Implements the baked indirect lighting with its modulation.
  14790. *
  14791. * @param {NodeBuilder} builder - The current node builder.
  14792. */
  14793. indirect( { context } ) {
  14794. const ambientOcclusion = context.ambientOcclusion;
  14795. const reflectedLight = context.reflectedLight;
  14796. const irradianceLightMap = context.irradianceLightMap;
  14797. reflectedLight.indirectDiffuse.assign( vec4( 0.0 ) );
  14798. // accumulation (baked indirect lighting only)
  14799. if ( irradianceLightMap ) {
  14800. reflectedLight.indirectDiffuse.addAssign( irradianceLightMap );
  14801. } else {
  14802. reflectedLight.indirectDiffuse.addAssign( vec4( 1.0, 1.0, 1.0, 0.0 ) );
  14803. }
  14804. // modulation
  14805. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  14806. reflectedLight.indirectDiffuse.mulAssign( diffuseColor.rgb );
  14807. }
  14808. /**
  14809. * Implements the environment mapping.
  14810. *
  14811. * @param {NodeBuilder} builder - The current node builder.
  14812. */
  14813. finish( builder ) {
  14814. const { material, context } = builder;
  14815. const outgoingLight = context.outgoingLight;
  14816. const envNode = builder.context.environment;
  14817. if ( envNode ) {
  14818. switch ( material.combine ) {
  14819. case MultiplyOperation:
  14820. outgoingLight.rgb.assign( mix( outgoingLight.rgb, outgoingLight.rgb.mul( envNode.rgb ), materialSpecularStrength.mul( materialReflectivity ) ) );
  14821. break;
  14822. case MixOperation:
  14823. outgoingLight.rgb.assign( mix( outgoingLight.rgb, envNode.rgb, materialSpecularStrength.mul( materialReflectivity ) ) );
  14824. break;
  14825. case AddOperation:
  14826. outgoingLight.rgb.addAssign( envNode.rgb.mul( materialSpecularStrength.mul( materialReflectivity ) ) );
  14827. break;
  14828. default:
  14829. console.warn( 'THREE.BasicLightingModel: Unsupported .combine value:', material.combine );
  14830. break;
  14831. }
  14832. }
  14833. }
  14834. }
  14835. const _defaultValues$9 = /*@__PURE__*/ new MeshBasicMaterial();
  14836. /**
  14837. * Node material version of {@link MeshBasicMaterial}.
  14838. *
  14839. * @augments NodeMaterial
  14840. */
  14841. class MeshBasicNodeMaterial extends NodeMaterial {
  14842. static get type() {
  14843. return 'MeshBasicNodeMaterial';
  14844. }
  14845. /**
  14846. * Constructs a new mesh basic node material.
  14847. *
  14848. * @param {Object} [parameters] - The configuration parameter.
  14849. */
  14850. constructor( parameters ) {
  14851. super();
  14852. /**
  14853. * This flag can be used for type testing.
  14854. *
  14855. * @type {boolean}
  14856. * @readonly
  14857. * @default true
  14858. */
  14859. this.isMeshBasicNodeMaterial = true;
  14860. /**
  14861. * Although the basic material is by definition unlit, we set
  14862. * this property to `true` since we use a lighting model to compute
  14863. * the outgoing light of the fragment shader.
  14864. *
  14865. * @type {boolean}
  14866. * @default true
  14867. */
  14868. this.lights = true;
  14869. this.setDefaultValues( _defaultValues$9 );
  14870. this.setValues( parameters );
  14871. }
  14872. /**
  14873. * Basic materials are not affected by normal and bump maps so we
  14874. * return by default {@link normalViewGeometry}.
  14875. *
  14876. * @return {Node<vec3>} The normal node.
  14877. */
  14878. setupNormal() {
  14879. return directionToFaceDirection( normalViewGeometry ); // see #28839
  14880. }
  14881. /**
  14882. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  14883. * to implement the default environment mapping.
  14884. *
  14885. * @param {NodeBuilder} builder - The current node builder.
  14886. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  14887. */
  14888. setupEnvironment( builder ) {
  14889. const envNode = super.setupEnvironment( builder );
  14890. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  14891. }
  14892. /**
  14893. * This method must be overwritten since light maps are evaluated
  14894. * with a special scaling factor for basic materials.
  14895. *
  14896. * @param {NodeBuilder} builder - The current node builder.
  14897. * @return {?BasicLightMapNode<vec3>} The light map node.
  14898. */
  14899. setupLightMap( builder ) {
  14900. let node = null;
  14901. if ( builder.material.lightMap ) {
  14902. node = new BasicLightMapNode( materialLightMap );
  14903. }
  14904. return node;
  14905. }
  14906. /**
  14907. * The material overwrites this method because `lights` is set to `true` but
  14908. * we still want to return the diffuse color as the outgoing light.
  14909. *
  14910. * @return {Node<vec3>} The outgoing light node.
  14911. */
  14912. setupOutgoingLight() {
  14913. return diffuseColor.rgb;
  14914. }
  14915. /**
  14916. * Setups the lighting model.
  14917. *
  14918. * @return {BasicLightingModel} The lighting model.
  14919. */
  14920. setupLightingModel() {
  14921. return new BasicLightingModel();
  14922. }
  14923. }
  14924. const F_Schlick = /*@__PURE__*/ Fn( ( { f0, f90, dotVH } ) => {
  14925. // Original approximation by Christophe Schlick '94
  14926. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  14927. // Optimized variant (presented by Epic at SIGGRAPH '13)
  14928. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  14929. const fresnel = dotVH.mul( -5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  14930. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  14931. } ); // validated
  14932. const BRDF_Lambert = /*@__PURE__*/ Fn( ( inputs ) => {
  14933. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  14934. } ); // validated
  14935. const G_BlinnPhong_Implicit = () => float( 0.25 );
  14936. const D_BlinnPhong = /*@__PURE__*/ Fn( ( { dotNH } ) => {
  14937. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  14938. } );
  14939. const BRDF_BlinnPhong = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  14940. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  14941. const dotNH = normalView.dot( halfDir ).clamp();
  14942. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  14943. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  14944. const G = G_BlinnPhong_Implicit();
  14945. const D = D_BlinnPhong( { dotNH } );
  14946. return F.mul( G ).mul( D );
  14947. } );
  14948. /**
  14949. * Represents the lighting model for a phong material. Used in {@link MeshPhongNodeMaterial}.
  14950. *
  14951. * @augments BasicLightingModel
  14952. */
  14953. class PhongLightingModel extends BasicLightingModel {
  14954. /**
  14955. * Constructs a new phong lighting model.
  14956. *
  14957. * @param {boolean} [specular=true] - Whether specular is supported or not.
  14958. */
  14959. constructor( specular = true ) {
  14960. super();
  14961. /**
  14962. * Whether specular is supported or not. Set this to `false` if you are
  14963. * looking for a Lambert-like material meaning a material for non-shiny
  14964. * surfaces, without specular highlights.
  14965. *
  14966. * @type {boolean}
  14967. * @default true
  14968. */
  14969. this.specular = specular;
  14970. }
  14971. /**
  14972. * Implements the direct lighting. The specular portion is optional an can be controlled
  14973. * with the {@link PhongLightingModel#specular} flag.
  14974. *
  14975. * @param {Object} lightData - The light data.
  14976. */
  14977. direct( { lightDirection, lightColor, reflectedLight } ) {
  14978. const dotNL = normalView.dot( lightDirection ).clamp();
  14979. const irradiance = dotNL.mul( lightColor );
  14980. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  14981. if ( this.specular === true ) {
  14982. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  14983. }
  14984. }
  14985. /**
  14986. * Implements the indirect lighting.
  14987. *
  14988. * @param {NodeBuilder} builder - The current node builder.
  14989. */
  14990. indirect( builder ) {
  14991. const { ambientOcclusion, irradiance, reflectedLight } = builder.context;
  14992. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  14993. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  14994. }
  14995. }
  14996. const _defaultValues$8 = /*@__PURE__*/ new MeshLambertMaterial();
  14997. /**
  14998. * Node material version of {@link MeshLambertMaterial}.
  14999. *
  15000. * @augments NodeMaterial
  15001. */
  15002. class MeshLambertNodeMaterial extends NodeMaterial {
  15003. static get type() {
  15004. return 'MeshLambertNodeMaterial';
  15005. }
  15006. /**
  15007. * Constructs a new mesh lambert node material.
  15008. *
  15009. * @param {Object} [parameters] - The configuration parameter.
  15010. */
  15011. constructor( parameters ) {
  15012. super();
  15013. /**
  15014. * This flag can be used for type testing.
  15015. *
  15016. * @type {boolean}
  15017. * @readonly
  15018. * @default true
  15019. */
  15020. this.isMeshLambertNodeMaterial = true;
  15021. /**
  15022. * Set to `true` because lambert materials react on lights.
  15023. *
  15024. * @type {boolean}
  15025. * @default true
  15026. */
  15027. this.lights = true;
  15028. this.setDefaultValues( _defaultValues$8 );
  15029. this.setValues( parameters );
  15030. }
  15031. /**
  15032. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  15033. * to implement the default environment mapping.
  15034. *
  15035. * @param {NodeBuilder} builder - The current node builder.
  15036. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  15037. */
  15038. setupEnvironment( builder ) {
  15039. const envNode = super.setupEnvironment( builder );
  15040. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  15041. }
  15042. /**
  15043. * Setups the lighting model.
  15044. *
  15045. * @return {PhongLightingModel} The lighting model.
  15046. */
  15047. setupLightingModel( /*builder*/ ) {
  15048. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  15049. }
  15050. }
  15051. const _defaultValues$7 = /*@__PURE__*/ new MeshPhongMaterial();
  15052. /**
  15053. * Node material version of {@link MeshPhongMaterial}.
  15054. *
  15055. * @augments NodeMaterial
  15056. */
  15057. class MeshPhongNodeMaterial extends NodeMaterial {
  15058. static get type() {
  15059. return 'MeshPhongNodeMaterial';
  15060. }
  15061. /**
  15062. * Constructs a new mesh lambert node material.
  15063. *
  15064. * @param {Object} [parameters] - The configuration parameter.
  15065. */
  15066. constructor( parameters ) {
  15067. super();
  15068. /**
  15069. * This flag can be used for type testing.
  15070. *
  15071. * @type {boolean}
  15072. * @readonly
  15073. * @default true
  15074. */
  15075. this.isMeshPhongNodeMaterial = true;
  15076. /**
  15077. * Set to `true` because phong materials react on lights.
  15078. *
  15079. * @type {boolean}
  15080. * @default true
  15081. */
  15082. this.lights = true;
  15083. /**
  15084. * The shininess of phong materials is by default inferred from the `shininess`
  15085. * property. This node property allows to overwrite the default
  15086. * and define the shininess with a node instead.
  15087. *
  15088. * If you don't want to overwrite the shininess but modify the existing
  15089. * value instead, use {@link materialShininess}.
  15090. *
  15091. * @type {?Node<float>}
  15092. * @default null
  15093. */
  15094. this.shininessNode = null;
  15095. /**
  15096. * The specular color of phong materials is by default inferred from the
  15097. * `specular` property. This node property allows to overwrite the default
  15098. * and define the specular color with a node instead.
  15099. *
  15100. * If you don't want to overwrite the specular color but modify the existing
  15101. * value instead, use {@link materialSpecular}.
  15102. *
  15103. * @type {?Node<vec3>}
  15104. * @default null
  15105. */
  15106. this.specularNode = null;
  15107. this.setDefaultValues( _defaultValues$7 );
  15108. this.setValues( parameters );
  15109. }
  15110. /**
  15111. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  15112. * to implement the default environment mapping.
  15113. *
  15114. * @param {NodeBuilder} builder - The current node builder.
  15115. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  15116. */
  15117. setupEnvironment( builder ) {
  15118. const envNode = super.setupEnvironment( builder );
  15119. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  15120. }
  15121. /**
  15122. * Setups the lighting model.
  15123. *
  15124. * @return {PhongLightingModel} The lighting model.
  15125. */
  15126. setupLightingModel( /*builder*/ ) {
  15127. return new PhongLightingModel();
  15128. }
  15129. /**
  15130. * Setups the phong specific node variables.
  15131. *
  15132. * @param {NodeBuilder} builder - The current node builder.
  15133. */
  15134. setupVariants( /*builder*/ ) {
  15135. // SHININESS
  15136. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  15137. shininess.assign( shininessNode );
  15138. // SPECULAR COLOR
  15139. const specularNode = this.specularNode || materialSpecular;
  15140. specularColor.assign( specularNode );
  15141. }
  15142. copy( source ) {
  15143. this.shininessNode = source.shininessNode;
  15144. this.specularNode = source.specularNode;
  15145. return super.copy( source );
  15146. }
  15147. }
  15148. const getGeometryRoughness = /*@__PURE__*/ Fn( ( builder ) => {
  15149. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  15150. return float( 0 );
  15151. }
  15152. const dxy = normalViewGeometry.dFdx().abs().max( normalViewGeometry.dFdy().abs() );
  15153. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  15154. return geometryRoughness;
  15155. } );
  15156. const getRoughness = /*@__PURE__*/ Fn( ( inputs ) => {
  15157. const { roughness } = inputs;
  15158. const geometryRoughness = getGeometryRoughness();
  15159. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  15160. roughnessFactor = roughnessFactor.add( geometryRoughness );
  15161. roughnessFactor = roughnessFactor.min( 1.0 );
  15162. return roughnessFactor;
  15163. } );
  15164. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  15165. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  15166. const V_GGX_SmithCorrelated = /*@__PURE__*/ Fn( ( { alpha, dotNL, dotNV } ) => {
  15167. const a2 = alpha.pow2();
  15168. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  15169. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  15170. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  15171. } ).setLayout( {
  15172. name: 'V_GGX_SmithCorrelated',
  15173. type: 'float',
  15174. inputs: [
  15175. { name: 'alpha', type: 'float' },
  15176. { name: 'dotNL', type: 'float' },
  15177. { name: 'dotNV', type: 'float' }
  15178. ]
  15179. } ); // validated
  15180. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  15181. const V_GGX_SmithCorrelated_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  15182. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  15183. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  15184. const v = div( 0.5, gv.add( gl ) );
  15185. return v.saturate();
  15186. } ).setLayout( {
  15187. name: 'V_GGX_SmithCorrelated_Anisotropic',
  15188. type: 'float',
  15189. inputs: [
  15190. { name: 'alphaT', type: 'float', qualifier: 'in' },
  15191. { name: 'alphaB', type: 'float', qualifier: 'in' },
  15192. { name: 'dotTV', type: 'float', qualifier: 'in' },
  15193. { name: 'dotBV', type: 'float', qualifier: 'in' },
  15194. { name: 'dotTL', type: 'float', qualifier: 'in' },
  15195. { name: 'dotBL', type: 'float', qualifier: 'in' },
  15196. { name: 'dotNV', type: 'float', qualifier: 'in' },
  15197. { name: 'dotNL', type: 'float', qualifier: 'in' }
  15198. ]
  15199. } );
  15200. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  15201. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  15202. // alpha is "roughness squared" in Disney’s reparameterization
  15203. const D_GGX = /*@__PURE__*/ Fn( ( { alpha, dotNH } ) => {
  15204. const a2 = alpha.pow2();
  15205. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  15206. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  15207. } ).setLayout( {
  15208. name: 'D_GGX',
  15209. type: 'float',
  15210. inputs: [
  15211. { name: 'alpha', type: 'float' },
  15212. { name: 'dotNH', type: 'float' }
  15213. ]
  15214. } ); // validated
  15215. const RECIPROCAL_PI = /*@__PURE__*/ float( 1 / Math.PI );
  15216. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  15217. const D_GGX_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  15218. const a2 = alphaT.mul( alphaB );
  15219. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  15220. const v2 = v.dot( v );
  15221. const w2 = a2.div( v2 );
  15222. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  15223. } ).setLayout( {
  15224. name: 'D_GGX_Anisotropic',
  15225. type: 'float',
  15226. inputs: [
  15227. { name: 'alphaT', type: 'float', qualifier: 'in' },
  15228. { name: 'alphaB', type: 'float', qualifier: 'in' },
  15229. { name: 'dotNH', type: 'float', qualifier: 'in' },
  15230. { name: 'dotTH', type: 'float', qualifier: 'in' },
  15231. { name: 'dotBH', type: 'float', qualifier: 'in' }
  15232. ]
  15233. } );
  15234. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  15235. const BRDF_GGX = /*@__PURE__*/ Fn( ( { lightDirection, f0, f90, roughness, f, normalView: normalView$1 = normalView, USE_IRIDESCENCE, USE_ANISOTROPY } ) => {
  15236. const alpha = roughness.pow2(); // UE4's roughness
  15237. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  15238. const dotNL = normalView$1.dot( lightDirection ).clamp();
  15239. const dotNV = normalView$1.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  15240. const dotNH = normalView$1.dot( halfDir ).clamp();
  15241. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  15242. let F = F_Schlick( { f0, f90, dotVH } );
  15243. let V, D;
  15244. if ( defined( USE_IRIDESCENCE ) ) {
  15245. F = iridescence.mix( F, f );
  15246. }
  15247. if ( defined( USE_ANISOTROPY ) ) {
  15248. const dotTL = anisotropyT.dot( lightDirection );
  15249. const dotTV = anisotropyT.dot( positionViewDirection );
  15250. const dotTH = anisotropyT.dot( halfDir );
  15251. const dotBL = anisotropyB.dot( lightDirection );
  15252. const dotBV = anisotropyB.dot( positionViewDirection );
  15253. const dotBH = anisotropyB.dot( halfDir );
  15254. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  15255. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  15256. } else {
  15257. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  15258. D = D_GGX( { alpha, dotNH } );
  15259. }
  15260. return F.mul( V ).mul( D );
  15261. } ); // validated
  15262. // Analytical approximation of the DFG LUT, one half of the
  15263. // split-sum approximation used in indirect specular lighting.
  15264. // via 'environmentBRDF' from "Physically Based Shading on Mobile"
  15265. // https://www.unrealengine.com/blog/physically-based-shading-on-mobile
  15266. const DFGApprox = /*@__PURE__*/ Fn( ( { roughness, dotNV } ) => {
  15267. const c0 = vec4( -1, -0.0275, -0.572, 0.022 );
  15268. const c1 = vec4( 1, 0.0425, 1.04, -0.04 );
  15269. const r = roughness.mul( c0 ).add( c1 );
  15270. const a004 = r.x.mul( r.x ).min( dotNV.mul( -9.28 ).exp2() ).mul( r.x ).add( r.y );
  15271. const fab = vec2( -1.04, 1.04 ).mul( a004 ).add( r.zw );
  15272. return fab;
  15273. } ).setLayout( {
  15274. name: 'DFGApprox',
  15275. type: 'vec2',
  15276. inputs: [
  15277. { name: 'roughness', type: 'float' },
  15278. { name: 'dotNV', type: 'vec3' }
  15279. ]
  15280. } );
  15281. const EnvironmentBRDF = /*@__PURE__*/ Fn( ( inputs ) => {
  15282. const { dotNV, specularColor, specularF90, roughness } = inputs;
  15283. const fab = DFGApprox( { dotNV, roughness } );
  15284. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  15285. } );
  15286. const Schlick_to_F0 = /*@__PURE__*/ Fn( ( { f, f90, dotVH } ) => {
  15287. const x = dotVH.oneMinus().saturate();
  15288. const x2 = x.mul( x );
  15289. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  15290. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  15291. } ).setLayout( {
  15292. name: 'Schlick_to_F0',
  15293. type: 'vec3',
  15294. inputs: [
  15295. { name: 'f', type: 'vec3' },
  15296. { name: 'f90', type: 'float' },
  15297. { name: 'dotVH', type: 'float' }
  15298. ]
  15299. } );
  15300. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  15301. const D_Charlie = /*@__PURE__*/ Fn( ( { roughness, dotNH } ) => {
  15302. const alpha = roughness.pow2();
  15303. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  15304. const invAlpha = float( 1.0 ).div( alpha );
  15305. const cos2h = dotNH.pow2();
  15306. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  15307. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  15308. } ).setLayout( {
  15309. name: 'D_Charlie',
  15310. type: 'float',
  15311. inputs: [
  15312. { name: 'roughness', type: 'float' },
  15313. { name: 'dotNH', type: 'float' }
  15314. ]
  15315. } );
  15316. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  15317. const V_Neubelt = /*@__PURE__*/ Fn( ( { dotNV, dotNL } ) => {
  15318. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  15319. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  15320. } ).setLayout( {
  15321. name: 'V_Neubelt',
  15322. type: 'float',
  15323. inputs: [
  15324. { name: 'dotNV', type: 'float' },
  15325. { name: 'dotNL', type: 'float' }
  15326. ]
  15327. } );
  15328. const BRDF_Sheen = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  15329. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  15330. const dotNL = normalView.dot( lightDirection ).clamp();
  15331. const dotNV = normalView.dot( positionViewDirection ).clamp();
  15332. const dotNH = normalView.dot( halfDir ).clamp();
  15333. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  15334. const V = V_Neubelt( { dotNV, dotNL } );
  15335. return sheen.mul( D ).mul( V );
  15336. } );
  15337. // Rect Area Light
  15338. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  15339. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  15340. // code: https://github.com/selfshadow/ltc_code/
  15341. const LTC_Uv = /*@__PURE__*/ Fn( ( { N, V, roughness } ) => {
  15342. const LUT_SIZE = 64.0;
  15343. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  15344. const LUT_BIAS = 0.5 / LUT_SIZE;
  15345. const dotNV = N.dot( V ).saturate();
  15346. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  15347. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  15348. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  15349. return uv;
  15350. } ).setLayout( {
  15351. name: 'LTC_Uv',
  15352. type: 'vec2',
  15353. inputs: [
  15354. { name: 'N', type: 'vec3' },
  15355. { name: 'V', type: 'vec3' },
  15356. { name: 'roughness', type: 'float' }
  15357. ]
  15358. } );
  15359. const LTC_ClippedSphereFormFactor = /*@__PURE__*/ Fn( ( { f } ) => {
  15360. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  15361. // An approximation of the form factor of a horizon-clipped rectangle.
  15362. const l = f.length();
  15363. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  15364. } ).setLayout( {
  15365. name: 'LTC_ClippedSphereFormFactor',
  15366. type: 'float',
  15367. inputs: [
  15368. { name: 'f', type: 'vec3' }
  15369. ]
  15370. } );
  15371. const LTC_EdgeVectorFormFactor = /*@__PURE__*/ Fn( ( { v1, v2 } ) => {
  15372. const x = v1.dot( v2 );
  15373. const y = x.abs().toVar();
  15374. // rational polynomial approximation to theta / sin( theta ) / 2PI
  15375. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  15376. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  15377. const v = a.div( b );
  15378. const theta_sintheta = x.greaterThan( 0.0 ).select( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  15379. return v1.cross( v2 ).mul( theta_sintheta );
  15380. } ).setLayout( {
  15381. name: 'LTC_EdgeVectorFormFactor',
  15382. type: 'vec3',
  15383. inputs: [
  15384. { name: 'v1', type: 'vec3' },
  15385. { name: 'v2', type: 'vec3' }
  15386. ]
  15387. } );
  15388. const LTC_Evaluate = /*@__PURE__*/ Fn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  15389. // bail if point is on back side of plane of light
  15390. // assumes ccw winding order of light vertices
  15391. const v1 = p1.sub( p0 ).toVar();
  15392. const v2 = p3.sub( p0 ).toVar();
  15393. const lightNormal = v1.cross( v2 );
  15394. const result = vec3().toVar();
  15395. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  15396. // construct orthonormal basis around N
  15397. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  15398. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  15399. // compute transform
  15400. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  15401. // transform rect
  15402. // & project rect onto sphere
  15403. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  15404. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  15405. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  15406. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  15407. // calculate vector form factor
  15408. const vectorFormFactor = vec3( 0 ).toVar();
  15409. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  15410. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  15411. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  15412. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  15413. // adjust for horizon clipping
  15414. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  15415. } );
  15416. return result;
  15417. } ).setLayout( {
  15418. name: 'LTC_Evaluate',
  15419. type: 'vec3',
  15420. inputs: [
  15421. { name: 'N', type: 'vec3' },
  15422. { name: 'V', type: 'vec3' },
  15423. { name: 'P', type: 'vec3' },
  15424. { name: 'mInv', type: 'mat3' },
  15425. { name: 'p0', type: 'vec3' },
  15426. { name: 'p1', type: 'vec3' },
  15427. { name: 'p2', type: 'vec3' },
  15428. { name: 'p3', type: 'vec3' }
  15429. ]
  15430. } );
  15431. const LTC_Evaluate_Volume = /*@__PURE__*/ Fn( ( { P, p0, p1, p2, p3 } ) => {
  15432. // bail if point is on back side of plane of light
  15433. // assumes ccw winding order of light vertices
  15434. const v1 = p1.sub( p0 ).toVar();
  15435. const v2 = p3.sub( p0 ).toVar();
  15436. const lightNormal = v1.cross( v2 );
  15437. const result = vec3().toVar();
  15438. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  15439. // transform rect
  15440. // & project rect onto sphere
  15441. const coords0 = p0.sub( P ).normalize().toVar();
  15442. const coords1 = p1.sub( P ).normalize().toVar();
  15443. const coords2 = p2.sub( P ).normalize().toVar();
  15444. const coords3 = p3.sub( P ).normalize().toVar();
  15445. // calculate vector form factor
  15446. const vectorFormFactor = vec3( 0 ).toVar();
  15447. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  15448. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  15449. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  15450. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  15451. // adjust for horizon clipping
  15452. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor.abs() } ) ) );
  15453. } );
  15454. return result;
  15455. } ).setLayout( {
  15456. name: 'LTC_Evaluate',
  15457. type: 'vec3',
  15458. inputs: [
  15459. { name: 'P', type: 'vec3' },
  15460. { name: 'p0', type: 'vec3' },
  15461. { name: 'p1', type: 'vec3' },
  15462. { name: 'p2', type: 'vec3' },
  15463. { name: 'p3', type: 'vec3' }
  15464. ]
  15465. } );
  15466. // Mipped Bicubic Texture Filtering by N8
  15467. // https://www.shadertoy.com/view/Dl2SDW
  15468. const bC = 1.0 / 6.0;
  15469. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  15470. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  15471. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( -3, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  15472. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  15473. const g0 = ( a ) => w0( a ).add( w1( a ) );
  15474. const g1 = ( a ) => w2( a ).add( w3( a ) );
  15475. // h0 and h1 are the two offset functions
  15476. const h0 = ( a ) => add( -1, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  15477. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  15478. const bicubic = ( textureNode, texelSize, lod ) => {
  15479. const uv = textureNode.uvNode;
  15480. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  15481. const iuv = floor( uvScaled );
  15482. const fuv = fract( uvScaled );
  15483. const g0x = g0( fuv.x );
  15484. const g1x = g1( fuv.x );
  15485. const h0x = h0( fuv.x );
  15486. const h1x = h1( fuv.x );
  15487. const h0y = h0( fuv.y );
  15488. const h1y = h1( fuv.y );
  15489. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  15490. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  15491. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  15492. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  15493. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.sample( p0 ).level( lod ) ), g1x.mul( textureNode.sample( p1 ).level( lod ) ) ) );
  15494. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.sample( p2 ).level( lod ) ), g1x.mul( textureNode.sample( p3 ).level( lod ) ) ) );
  15495. return a.add( b );
  15496. };
  15497. /**
  15498. * Applies mipped bicubic texture filtering to the given texture node.
  15499. *
  15500. * @tsl
  15501. * @function
  15502. * @param {TextureNode} textureNode - The texture node that should be filtered.
  15503. * @param {Node<float>} lodNode - Defines the LOD to sample from.
  15504. * @return {Node} The filtered texture sample.
  15505. */
  15506. const textureBicubicLevel = /*@__PURE__*/ Fn( ( [ textureNode, lodNode ] ) => {
  15507. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  15508. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  15509. const fLodSizeInv = div( 1.0, fLodSize );
  15510. const cLodSizeInv = div( 1.0, cLodSize );
  15511. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  15512. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  15513. return fract( lodNode ).mix( fSample, cSample );
  15514. } );
  15515. /**
  15516. * Applies mipped bicubic texture filtering to the given texture node.
  15517. *
  15518. * @tsl
  15519. * @function
  15520. * @param {TextureNode} textureNode - The texture node that should be filtered.
  15521. * @param {Node<float>} [strength] - Defines the strength of the bicubic filtering.
  15522. * @return {Node} The filtered texture sample.
  15523. */
  15524. const textureBicubic = /*@__PURE__*/ Fn( ( [ textureNode, strength ] ) => {
  15525. const lod = strength.mul( maxMipLevel( textureNode ) );
  15526. return textureBicubicLevel( textureNode, lod );
  15527. } );
  15528. //
  15529. // Transmission
  15530. //
  15531. const getVolumeTransmissionRay = /*@__PURE__*/ Fn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  15532. // Direction of refracted light.
  15533. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  15534. // Compute rotation-independent scaling of the model matrix.
  15535. const modelScale = vec3(
  15536. length( modelMatrix[ 0 ].xyz ),
  15537. length( modelMatrix[ 1 ].xyz ),
  15538. length( modelMatrix[ 2 ].xyz )
  15539. );
  15540. // The thickness is specified in local space.
  15541. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  15542. } ).setLayout( {
  15543. name: 'getVolumeTransmissionRay',
  15544. type: 'vec3',
  15545. inputs: [
  15546. { name: 'n', type: 'vec3' },
  15547. { name: 'v', type: 'vec3' },
  15548. { name: 'thickness', type: 'float' },
  15549. { name: 'ior', type: 'float' },
  15550. { name: 'modelMatrix', type: 'mat4' }
  15551. ]
  15552. } );
  15553. const applyIorToRoughness = /*@__PURE__*/ Fn( ( [ roughness, ior ] ) => {
  15554. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  15555. // an IOR of 1.5 results in the default amount of microfacet refraction.
  15556. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  15557. } ).setLayout( {
  15558. name: 'applyIorToRoughness',
  15559. type: 'float',
  15560. inputs: [
  15561. { name: 'roughness', type: 'float' },
  15562. { name: 'ior', type: 'float' }
  15563. ]
  15564. } );
  15565. const viewportBackSideTexture = /*@__PURE__*/ viewportMipTexture();
  15566. const viewportFrontSideTexture = /*@__PURE__*/ viewportMipTexture();
  15567. const getTransmissionSample = /*@__PURE__*/ Fn( ( [ fragCoord, roughness, ior ], { material } ) => {
  15568. const vTexture = material.side === BackSide ? viewportBackSideTexture : viewportFrontSideTexture;
  15569. const transmissionSample = vTexture.sample( fragCoord );
  15570. //const transmissionSample = viewportMipTexture( fragCoord );
  15571. const lod = log2( screenSize.x ).mul( applyIorToRoughness( roughness, ior ) );
  15572. return textureBicubicLevel( transmissionSample, lod );
  15573. } );
  15574. const volumeAttenuation = /*@__PURE__*/ Fn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  15575. If( attenuationDistance.notEqual( 0 ), () => {
  15576. // Compute light attenuation using Beer's law.
  15577. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  15578. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  15579. return transmittance;
  15580. } );
  15581. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  15582. return vec3( 1.0 );
  15583. } ).setLayout( {
  15584. name: 'volumeAttenuation',
  15585. type: 'vec3',
  15586. inputs: [
  15587. { name: 'transmissionDistance', type: 'float' },
  15588. { name: 'attenuationColor', type: 'vec3' },
  15589. { name: 'attenuationDistance', type: 'float' }
  15590. ]
  15591. } );
  15592. const getIBLVolumeRefraction = /*@__PURE__*/ Fn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  15593. let transmittedLight, transmittance;
  15594. if ( dispersion ) {
  15595. transmittedLight = vec4().toVar();
  15596. transmittance = vec3().toVar();
  15597. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  15598. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  15599. Loop( { start: 0, end: 3 }, ( { i } ) => {
  15600. const ior = iors.element( i );
  15601. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  15602. const refractedRayExit = position.add( transmissionRay );
  15603. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  15604. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  15605. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  15606. refractionCoords.addAssign( 1.0 );
  15607. refractionCoords.divAssign( 2.0 );
  15608. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  15609. // Sample framebuffer to get pixel the refracted ray hits.
  15610. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  15611. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  15612. transmittedLight.a.addAssign( transmissionSample.a );
  15613. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  15614. } );
  15615. transmittedLight.a.divAssign( 3.0 );
  15616. } else {
  15617. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  15618. const refractedRayExit = position.add( transmissionRay );
  15619. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  15620. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  15621. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  15622. refractionCoords.addAssign( 1.0 );
  15623. refractionCoords.divAssign( 2.0 );
  15624. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  15625. // Sample framebuffer to get pixel the refracted ray hits.
  15626. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  15627. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  15628. }
  15629. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  15630. const dotNV = n.dot( v ).clamp();
  15631. // Get the specular component.
  15632. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  15633. dotNV,
  15634. specularColor,
  15635. specularF90,
  15636. roughness
  15637. } ) );
  15638. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  15639. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  15640. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  15641. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  15642. } );
  15643. //
  15644. // Iridescence
  15645. //
  15646. // XYZ to linear-sRGB color space
  15647. const XYZ_TO_REC709 = /*@__PURE__*/ mat3(
  15648. 3.2404542, -0.969266, 0.0556434,
  15649. -1.5371385, 1.8760108, -0.2040259,
  15650. -0.4985314, 0.0415560, 1.0572252
  15651. );
  15652. // Assume air interface for top
  15653. // Note: We don't handle the case fresnel0 == 1
  15654. const Fresnel0ToIor = ( fresnel0 ) => {
  15655. const sqrtF0 = fresnel0.sqrt();
  15656. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  15657. };
  15658. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  15659. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  15660. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  15661. };
  15662. // Fresnel equations for dielectric/dielectric interfaces.
  15663. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  15664. // Evaluation XYZ sensitivity curves in Fourier space
  15665. const evalSensitivity = ( OPD, shift ) => {
  15666. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  15667. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  15668. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  15669. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  15670. 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() );
  15671. 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() );
  15672. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  15673. const rgb = XYZ_TO_REC709.mul( xyz );
  15674. return rgb;
  15675. };
  15676. const evalIridescence = /*@__PURE__*/ Fn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  15677. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  15678. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  15679. // Evaluate the cosTheta on the base layer (Snell law)
  15680. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( cosTheta1.pow2().oneMinus() );
  15681. // Handle TIR:
  15682. const cosTheta2Sq = sinTheta2Sq.oneMinus();
  15683. If( cosTheta2Sq.lessThan( 0 ), () => {
  15684. return vec3( 1.0 );
  15685. } );
  15686. const cosTheta2 = cosTheta2Sq.sqrt();
  15687. // First interface
  15688. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  15689. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  15690. //const R21 = R12;
  15691. const T121 = R12.oneMinus();
  15692. const phi12 = iridescenceIOR.lessThan( outsideIOR ).select( Math.PI, 0.0 );
  15693. const phi21 = float( Math.PI ).sub( phi12 );
  15694. // Second interface
  15695. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  15696. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  15697. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  15698. const phi23 = vec3(
  15699. baseIOR.x.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  15700. baseIOR.y.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  15701. baseIOR.z.lessThan( iridescenceIOR ).select( Math.PI, 0.0 )
  15702. );
  15703. // Phase shift
  15704. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  15705. const phi = vec3( phi21 ).add( phi23 );
  15706. // Compound terms
  15707. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  15708. const r123 = R123.sqrt();
  15709. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  15710. // Reflectance term for m = 0 (DC term amplitude)
  15711. const C0 = R12.add( Rs );
  15712. const I = C0.toVar();
  15713. // Reflectance term for m > 0 (pairs of diracs)
  15714. const Cm = Rs.sub( T121 ).toVar();
  15715. Loop( { start: 1, end: 2, condition: '<=', name: 'm' }, ( { m } ) => {
  15716. Cm.mulAssign( r123 );
  15717. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  15718. I.addAssign( Cm.mul( Sm ) );
  15719. } );
  15720. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  15721. return I.max( vec3( 0.0 ) );
  15722. } ).setLayout( {
  15723. name: 'evalIridescence',
  15724. type: 'vec3',
  15725. inputs: [
  15726. { name: 'outsideIOR', type: 'float' },
  15727. { name: 'eta2', type: 'float' },
  15728. { name: 'cosTheta1', type: 'float' },
  15729. { name: 'thinFilmThickness', type: 'float' },
  15730. { name: 'baseF0', type: 'vec3' }
  15731. ]
  15732. } );
  15733. //
  15734. // Sheen
  15735. //
  15736. // This is a curve-fit approximation to the "Charlie sheen" BRDF integrated over the hemisphere from
  15737. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF". The analysis can be found
  15738. // in the Sheen section of https://drive.google.com/file/d/1T0D1VSyR4AllqIJTQAraEIzjlb5h4FKH/view?usp=sharing
  15739. const IBLSheenBRDF = /*@__PURE__*/ Fn( ( { normal, viewDir, roughness } ) => {
  15740. const dotNV = normal.dot( viewDir ).saturate();
  15741. const r2 = roughness.pow2();
  15742. const a = select(
  15743. roughness.lessThan( 0.25 ),
  15744. float( -339.2 ).mul( r2 ).add( float( 161.4 ).mul( roughness ) ).sub( 25.9 ),
  15745. float( -8.48 ).mul( r2 ).add( float( 14.3 ).mul( roughness ) ).sub( 9.95 )
  15746. );
  15747. const b = select(
  15748. roughness.lessThan( 0.25 ),
  15749. float( 44.0 ).mul( r2 ).sub( float( 23.7 ).mul( roughness ) ).add( 3.26 ),
  15750. float( 1.97 ).mul( r2 ).sub( float( 3.27 ).mul( roughness ) ).add( 0.72 )
  15751. );
  15752. const DG = select( roughness.lessThan( 0.25 ), 0.0, float( 0.1 ).mul( roughness ).sub( 0.025 ) ).add( a.mul( dotNV ).add( b ).exp() );
  15753. return DG.mul( 1.0 / Math.PI ).saturate();
  15754. } );
  15755. const clearcoatF0 = vec3( 0.04 );
  15756. const clearcoatF90 = float( 1 );
  15757. /**
  15758. * Represents the lighting model for a PBR material.
  15759. *
  15760. * @augments LightingModel
  15761. */
  15762. class PhysicalLightingModel extends LightingModel {
  15763. /**
  15764. * Constructs a new physical lighting model.
  15765. *
  15766. * @param {boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  15767. * @param {boolean} [sheen=false] - Whether sheen is supported or not.
  15768. * @param {boolean} [iridescence=false] - Whether iridescence is supported or not.
  15769. * @param {boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  15770. * @param {boolean} [transmission=false] - Whether transmission is supported or not.
  15771. * @param {boolean} [dispersion=false] - Whether dispersion is supported or not.
  15772. */
  15773. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  15774. super();
  15775. /**
  15776. * Whether clearcoat is supported or not.
  15777. *
  15778. * @type {boolean}
  15779. * @default false
  15780. */
  15781. this.clearcoat = clearcoat;
  15782. /**
  15783. * Whether sheen is supported or not.
  15784. *
  15785. * @type {boolean}
  15786. * @default false
  15787. */
  15788. this.sheen = sheen;
  15789. /**
  15790. * Whether iridescence is supported or not.
  15791. *
  15792. * @type {boolean}
  15793. * @default false
  15794. */
  15795. this.iridescence = iridescence;
  15796. /**
  15797. * Whether anisotropy is supported or not.
  15798. *
  15799. * @type {boolean}
  15800. * @default false
  15801. */
  15802. this.anisotropy = anisotropy;
  15803. /**
  15804. * Whether transmission is supported or not.
  15805. *
  15806. * @type {boolean}
  15807. * @default false
  15808. */
  15809. this.transmission = transmission;
  15810. /**
  15811. * Whether dispersion is supported or not.
  15812. *
  15813. * @type {boolean}
  15814. * @default false
  15815. */
  15816. this.dispersion = dispersion;
  15817. /**
  15818. * The clear coat radiance.
  15819. *
  15820. * @type {?Node}
  15821. * @default null
  15822. */
  15823. this.clearcoatRadiance = null;
  15824. /**
  15825. * The clear coat specular direct.
  15826. *
  15827. * @type {?Node}
  15828. * @default null
  15829. */
  15830. this.clearcoatSpecularDirect = null;
  15831. /**
  15832. * The clear coat specular indirect.
  15833. *
  15834. * @type {?Node}
  15835. * @default null
  15836. */
  15837. this.clearcoatSpecularIndirect = null;
  15838. /**
  15839. * The sheen specular direct.
  15840. *
  15841. * @type {?Node}
  15842. * @default null
  15843. */
  15844. this.sheenSpecularDirect = null;
  15845. /**
  15846. * The sheen specular indirect.
  15847. *
  15848. * @type {?Node}
  15849. * @default null
  15850. */
  15851. this.sheenSpecularIndirect = null;
  15852. /**
  15853. * The iridescence Fresnel.
  15854. *
  15855. * @type {?Node}
  15856. * @default null
  15857. */
  15858. this.iridescenceFresnel = null;
  15859. /**
  15860. * The iridescence F0.
  15861. *
  15862. * @type {?Node}
  15863. * @default null
  15864. */
  15865. this.iridescenceF0 = null;
  15866. }
  15867. /**
  15868. * Depending on what features are requested, the method prepares certain node variables
  15869. * which are later used for lighting computations.
  15870. *
  15871. * @param {NodeBuilder} builder - The current node builder.
  15872. */
  15873. start( builder ) {
  15874. if ( this.clearcoat === true ) {
  15875. this.clearcoatRadiance = vec3().toVar( 'clearcoatRadiance' );
  15876. this.clearcoatSpecularDirect = vec3().toVar( 'clearcoatSpecularDirect' );
  15877. this.clearcoatSpecularIndirect = vec3().toVar( 'clearcoatSpecularIndirect' );
  15878. }
  15879. if ( this.sheen === true ) {
  15880. this.sheenSpecularDirect = vec3().toVar( 'sheenSpecularDirect' );
  15881. this.sheenSpecularIndirect = vec3().toVar( 'sheenSpecularIndirect' );
  15882. }
  15883. if ( this.iridescence === true ) {
  15884. const dotNVi = normalView.dot( positionViewDirection ).clamp();
  15885. this.iridescenceFresnel = evalIridescence( {
  15886. outsideIOR: float( 1.0 ),
  15887. eta2: iridescenceIOR,
  15888. cosTheta1: dotNVi,
  15889. thinFilmThickness: iridescenceThickness,
  15890. baseF0: specularColor
  15891. } );
  15892. this.iridescenceF0 = Schlick_to_F0( { f: this.iridescenceFresnel, f90: 1.0, dotVH: dotNVi } );
  15893. }
  15894. if ( this.transmission === true ) {
  15895. const position = positionWorld;
  15896. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  15897. const n = normalWorld;
  15898. const context = builder.context;
  15899. context.backdrop = getIBLVolumeRefraction(
  15900. n,
  15901. v,
  15902. roughness,
  15903. diffuseColor,
  15904. specularColor,
  15905. specularF90, // specularF90
  15906. position, // positionWorld
  15907. modelWorldMatrix, // modelMatrix
  15908. cameraViewMatrix, // viewMatrix
  15909. cameraProjectionMatrix, // projMatrix
  15910. ior,
  15911. thickness,
  15912. attenuationColor,
  15913. attenuationDistance,
  15914. this.dispersion ? dispersion : null
  15915. );
  15916. context.backdropAlpha = transmission;
  15917. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  15918. }
  15919. super.start( builder );
  15920. }
  15921. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  15922. // Approximates multi-scattering in order to preserve energy.
  15923. // http://www.jcgt.org/published/0008/01/03/
  15924. computeMultiscattering( singleScatter, multiScatter, specularF90 ) {
  15925. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  15926. const fab = DFGApprox( { roughness, dotNV } );
  15927. const Fr = this.iridescenceF0 ? iridescence.mix( specularColor, this.iridescenceF0 ) : specularColor;
  15928. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  15929. const Ess = fab.x.add( fab.y );
  15930. const Ems = Ess.oneMinus();
  15931. const Favg = specularColor.add( specularColor.oneMinus().mul( 0.047619 ) ); // 1/21
  15932. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  15933. singleScatter.addAssign( FssEss );
  15934. multiScatter.addAssign( Fms.mul( Ems ) );
  15935. }
  15936. /**
  15937. * Implements the direct light.
  15938. *
  15939. * @param {Object} lightData - The light data.
  15940. * @param {NodeBuilder} builder - The current node builder.
  15941. */
  15942. direct( { lightDirection, lightColor, reflectedLight }, /* builder */ ) {
  15943. const dotNL = normalView.dot( lightDirection ).clamp();
  15944. const irradiance = dotNL.mul( lightColor );
  15945. if ( this.sheen === true ) {
  15946. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  15947. }
  15948. if ( this.clearcoat === true ) {
  15949. const dotNLcc = clearcoatNormalView.dot( lightDirection ).clamp();
  15950. const ccIrradiance = dotNLcc.mul( lightColor );
  15951. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: clearcoatNormalView } ) ) );
  15952. }
  15953. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  15954. 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 } ) ) );
  15955. }
  15956. /**
  15957. * This method is intended for implementing the direct light term for
  15958. * rect area light nodes.
  15959. *
  15960. * @param {Object} input - The input data.
  15961. * @param {NodeBuilder} builder - The current node builder.
  15962. */
  15963. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 }, /* builder */ ) {
  15964. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  15965. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  15966. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  15967. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  15968. const N = normalView;
  15969. const V = positionViewDirection;
  15970. const P = positionView.toVar();
  15971. const uv = LTC_Uv( { N, V, roughness } );
  15972. const t1 = ltc_1.sample( uv ).toVar();
  15973. const t2 = ltc_2.sample( uv ).toVar();
  15974. const mInv = mat3(
  15975. vec3( t1.x, 0, t1.y ),
  15976. vec3( 0, 1, 0 ),
  15977. vec3( t1.z, 0, t1.w )
  15978. ).toVar();
  15979. // LTC Fresnel Approximation by Stephen Hill
  15980. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  15981. const fresnel = specularColor.mul( t2.x ).add( specularColor.oneMinus().mul( t2.y ) ).toVar();
  15982. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  15983. 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 } ) ) );
  15984. }
  15985. /**
  15986. * Implements the indirect lighting.
  15987. *
  15988. * @param {NodeBuilder} builder - The current node builder.
  15989. */
  15990. indirect( builder ) {
  15991. this.indirectDiffuse( builder );
  15992. this.indirectSpecular( builder );
  15993. this.ambientOcclusion( builder );
  15994. }
  15995. /**
  15996. * Implements the indirect diffuse term.
  15997. *
  15998. * @param {NodeBuilder} builder - The current node builder.
  15999. */
  16000. indirectDiffuse( builder ) {
  16001. const { irradiance, reflectedLight } = builder.context;
  16002. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  16003. }
  16004. /**
  16005. * Implements the indirect specular term.
  16006. *
  16007. * @param {NodeBuilder} builder - The current node builder.
  16008. */
  16009. indirectSpecular( builder ) {
  16010. const { radiance, iblIrradiance, reflectedLight } = builder.context;
  16011. if ( this.sheen === true ) {
  16012. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  16013. sheen,
  16014. IBLSheenBRDF( {
  16015. normal: normalView,
  16016. viewDir: positionViewDirection,
  16017. roughness: sheenRoughness
  16018. } )
  16019. ) );
  16020. }
  16021. if ( this.clearcoat === true ) {
  16022. const dotNVcc = clearcoatNormalView.dot( positionViewDirection ).clamp();
  16023. const clearcoatEnv = EnvironmentBRDF( {
  16024. dotNV: dotNVcc,
  16025. specularColor: clearcoatF0,
  16026. specularF90: clearcoatF90,
  16027. roughness: clearcoatRoughness
  16028. } );
  16029. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  16030. }
  16031. // Both indirect specular and indirect diffuse light accumulate here
  16032. const singleScattering = vec3().toVar( 'singleScattering' );
  16033. const multiScattering = vec3().toVar( 'multiScattering' );
  16034. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  16035. this.computeMultiscattering( singleScattering, multiScattering, specularF90 );
  16036. const totalScattering = singleScattering.add( multiScattering );
  16037. const diffuse = diffuseColor.mul( totalScattering.r.max( totalScattering.g ).max( totalScattering.b ).oneMinus() );
  16038. reflectedLight.indirectSpecular.addAssign( radiance.mul( singleScattering ) );
  16039. reflectedLight.indirectSpecular.addAssign( multiScattering.mul( cosineWeightedIrradiance ) );
  16040. reflectedLight.indirectDiffuse.addAssign( diffuse.mul( cosineWeightedIrradiance ) );
  16041. }
  16042. /**
  16043. * Implements the ambient occlusion term.
  16044. *
  16045. * @param {NodeBuilder} builder - The current node builder.
  16046. */
  16047. ambientOcclusion( builder ) {
  16048. const { ambientOcclusion, reflectedLight } = builder.context;
  16049. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  16050. const aoNV = dotNV.add( ambientOcclusion );
  16051. const aoExp = roughness.mul( -16 ).oneMinus().negate().exp2();
  16052. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  16053. if ( this.clearcoat === true ) {
  16054. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  16055. }
  16056. if ( this.sheen === true ) {
  16057. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  16058. }
  16059. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  16060. reflectedLight.indirectSpecular.mulAssign( aoNode );
  16061. }
  16062. /**
  16063. * Used for final lighting accumulations depending on the requested features.
  16064. *
  16065. * @param {NodeBuilder} builder - The current node builder.
  16066. */
  16067. finish( { context } ) {
  16068. const { outgoingLight } = context;
  16069. if ( this.clearcoat === true ) {
  16070. const dotNVcc = clearcoatNormalView.dot( positionViewDirection ).clamp();
  16071. const Fcc = F_Schlick( {
  16072. dotVH: dotNVcc,
  16073. f0: clearcoatF0,
  16074. f90: clearcoatF90
  16075. } );
  16076. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  16077. outgoingLight.assign( clearcoatLight );
  16078. }
  16079. if ( this.sheen === true ) {
  16080. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( 0.157 ).oneMinus();
  16081. const sheenLight = outgoingLight.mul( sheenEnergyComp ).add( this.sheenSpecularDirect, this.sheenSpecularIndirect );
  16082. outgoingLight.assign( sheenLight );
  16083. }
  16084. }
  16085. }
  16086. // These defines must match with PMREMGenerator
  16087. const cubeUV_r0 = /*@__PURE__*/ float( 1.0 );
  16088. const cubeUV_m0 = /*@__PURE__*/ float( -2 );
  16089. const cubeUV_r1 = /*@__PURE__*/ float( 0.8 );
  16090. const cubeUV_m1 = /*@__PURE__*/ float( -1 );
  16091. const cubeUV_r4 = /*@__PURE__*/ float( 0.4 );
  16092. const cubeUV_m4 = /*@__PURE__*/ float( 2.0 );
  16093. const cubeUV_r5 = /*@__PURE__*/ float( 0.305 );
  16094. const cubeUV_m5 = /*@__PURE__*/ float( 3.0 );
  16095. const cubeUV_r6 = /*@__PURE__*/ float( 0.21 );
  16096. const cubeUV_m6 = /*@__PURE__*/ float( 4.0 );
  16097. const cubeUV_minMipLevel = /*@__PURE__*/ float( 4.0 );
  16098. const cubeUV_minTileSize = /*@__PURE__*/ float( 16.0 );
  16099. // These shader functions convert between the UV coordinates of a single face of
  16100. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  16101. // sampling a textureCube (not generally normalized ).
  16102. const getFace = /*@__PURE__*/ Fn( ( [ direction ] ) => {
  16103. const absDirection = vec3( abs( direction ) ).toVar();
  16104. const face = float( -1 ).toVar();
  16105. If( absDirection.x.greaterThan( absDirection.z ), () => {
  16106. If( absDirection.x.greaterThan( absDirection.y ), () => {
  16107. face.assign( select( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  16108. } ).Else( () => {
  16109. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  16110. } );
  16111. } ).Else( () => {
  16112. If( absDirection.z.greaterThan( absDirection.y ), () => {
  16113. face.assign( select( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  16114. } ).Else( () => {
  16115. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  16116. } );
  16117. } );
  16118. return face;
  16119. } ).setLayout( {
  16120. name: 'getFace',
  16121. type: 'float',
  16122. inputs: [
  16123. { name: 'direction', type: 'vec3' }
  16124. ]
  16125. } );
  16126. // RH coordinate system; PMREM face-indexing convention
  16127. const getUV = /*@__PURE__*/ Fn( ( [ direction, face ] ) => {
  16128. const uv = vec2().toVar();
  16129. If( face.equal( 0.0 ), () => {
  16130. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  16131. } ).ElseIf( face.equal( 1.0 ), () => {
  16132. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  16133. } ).ElseIf( face.equal( 2.0 ), () => {
  16134. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  16135. } ).ElseIf( face.equal( 3.0 ), () => {
  16136. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  16137. } ).ElseIf( face.equal( 4.0 ), () => {
  16138. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  16139. } ).Else( () => {
  16140. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  16141. } );
  16142. return mul( 0.5, uv.add( 1.0 ) );
  16143. } ).setLayout( {
  16144. name: 'getUV',
  16145. type: 'vec2',
  16146. inputs: [
  16147. { name: 'direction', type: 'vec3' },
  16148. { name: 'face', type: 'float' }
  16149. ]
  16150. } );
  16151. const roughnessToMip = /*@__PURE__*/ Fn( ( [ roughness ] ) => {
  16152. const mip = float( 0.0 ).toVar();
  16153. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  16154. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  16155. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  16156. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  16157. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  16158. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  16159. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  16160. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  16161. } ).Else( () => {
  16162. mip.assign( float( -2 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  16163. } );
  16164. return mip;
  16165. } ).setLayout( {
  16166. name: 'roughnessToMip',
  16167. type: 'float',
  16168. inputs: [
  16169. { name: 'roughness', type: 'float' }
  16170. ]
  16171. } );
  16172. // RH coordinate system; PMREM face-indexing convention
  16173. const getDirection = /*@__PURE__*/ Fn( ( [ uv_immutable, face ] ) => {
  16174. const uv = uv_immutable.toVar();
  16175. uv.assign( mul( 2.0, uv ).sub( 1.0 ) );
  16176. const direction = vec3( uv, 1.0 ).toVar();
  16177. If( face.equal( 0.0 ), () => {
  16178. direction.assign( direction.zyx ); // ( 1, v, u ) pos x
  16179. } ).ElseIf( face.equal( 1.0 ), () => {
  16180. direction.assign( direction.xzy );
  16181. direction.xz.mulAssign( -1 ); // ( -u, 1, -v ) pos y
  16182. } ).ElseIf( face.equal( 2.0 ), () => {
  16183. direction.x.mulAssign( -1 ); // ( -u, v, 1 ) pos z
  16184. } ).ElseIf( face.equal( 3.0 ), () => {
  16185. direction.assign( direction.zyx );
  16186. direction.xz.mulAssign( -1 ); // ( -1, v, -u ) neg x
  16187. } ).ElseIf( face.equal( 4.0 ), () => {
  16188. direction.assign( direction.xzy );
  16189. direction.xy.mulAssign( -1 ); // ( -u, -1, v ) neg y
  16190. } ).ElseIf( face.equal( 5.0 ), () => {
  16191. direction.z.mulAssign( -1 ); // ( u, v, -1 ) neg zS
  16192. } );
  16193. return direction;
  16194. } ).setLayout( {
  16195. name: 'getDirection',
  16196. type: 'vec3',
  16197. inputs: [
  16198. { name: 'uv', type: 'vec2' },
  16199. { name: 'face', type: 'float' }
  16200. ]
  16201. } );
  16202. //
  16203. const textureCubeUV = /*@__PURE__*/ Fn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  16204. const roughness = float( roughness_immutable );
  16205. const sampleDir = vec3( sampleDir_immutable );
  16206. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  16207. const mipF = fract( mip );
  16208. const mipInt = floor( mip );
  16209. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  16210. If( mipF.notEqual( 0.0 ), () => {
  16211. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  16212. color0.assign( mix( color0, color1, mipF ) );
  16213. } );
  16214. return color0;
  16215. } );
  16216. const bilinearCubeUV = /*@__PURE__*/ Fn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  16217. const mipInt = float( mipInt_immutable ).toVar();
  16218. const direction = vec3( direction_immutable );
  16219. const face = float( getFace( direction ) ).toVar();
  16220. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  16221. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  16222. const faceSize = float( exp2( mipInt ) ).toVar();
  16223. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  16224. If( face.greaterThan( 2.0 ), () => {
  16225. uv.y.addAssign( faceSize );
  16226. face.subAssign( 3.0 );
  16227. } );
  16228. uv.x.addAssign( face.mul( faceSize ) );
  16229. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  16230. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  16231. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  16232. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  16233. return envMap.sample( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  16234. } );
  16235. const getSample = /*@__PURE__*/ Fn( ( { envMap, mipInt, outputDirection, theta, axis, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  16236. const cosTheta = cos( theta );
  16237. // Rodrigues' axis-angle rotation
  16238. const sampleDirection = outputDirection.mul( cosTheta )
  16239. .add( axis.cross( outputDirection ).mul( sin( theta ) ) )
  16240. .add( axis.mul( axis.dot( outputDirection ).mul( cosTheta.oneMinus() ) ) );
  16241. return bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  16242. } );
  16243. const blur = /*@__PURE__*/ Fn( ( { n, latitudinal, poleAxis, outputDirection, weights, samples, dTheta, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  16244. const axis = vec3( select( latitudinal, poleAxis, cross( poleAxis, outputDirection ) ) ).toVar();
  16245. If( axis.equal( vec3( 0.0 ) ), () => {
  16246. axis.assign( vec3( outputDirection.z, 0.0, outputDirection.x.negate() ) );
  16247. } );
  16248. axis.assign( normalize( axis ) );
  16249. const gl_FragColor = vec3().toVar();
  16250. gl_FragColor.addAssign( weights.element( 0 ).mul( getSample( { theta: 0.0, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  16251. Loop( { start: int( 1 ), end: n }, ( { i } ) => {
  16252. If( i.greaterThanEqual( samples ), () => {
  16253. Break();
  16254. } );
  16255. const theta = float( dTheta.mul( float( i ) ) ).toVar();
  16256. 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 } ) ) );
  16257. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  16258. } );
  16259. return vec4( gl_FragColor, 1 );
  16260. } );
  16261. const LOD_MIN = 4;
  16262. // The standard deviations (radians) associated with the extra mips. These are
  16263. // chosen to approximate a Trowbridge-Reitz distribution function times the
  16264. // geometric shadowing function. These sigma values squared must match the
  16265. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  16266. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  16267. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  16268. // samples and exit early, but not recompile the shader.
  16269. const MAX_SAMPLES = 20;
  16270. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  16271. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  16272. const _clearColor$2 = /*@__PURE__*/ new Color();
  16273. let _oldTarget = null;
  16274. let _oldActiveCubeFace = 0;
  16275. let _oldActiveMipmapLevel = 0;
  16276. // Golden Ratio
  16277. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  16278. const INV_PHI = 1 / PHI;
  16279. // Vertices of a dodecahedron (except the opposites, which represent the
  16280. // same axis), used as axis directions evenly spread on a sphere.
  16281. const _axisDirections = [
  16282. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  16283. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  16284. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  16285. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  16286. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  16287. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  16288. /*@__PURE__*/ new Vector3( -1, 1, -1 ),
  16289. /*@__PURE__*/ new Vector3( 1, 1, -1 ),
  16290. /*@__PURE__*/ new Vector3( -1, 1, 1 ),
  16291. /*@__PURE__*/ new Vector3( 1, 1, 1 )
  16292. ];
  16293. const _origin = /*@__PURE__*/ new Vector3();
  16294. // maps blur materials to their uniforms dictionary
  16295. const _uniformsMap = new WeakMap();
  16296. // WebGPU Face indices
  16297. const _faceLib = [
  16298. 3, 1, 5,
  16299. 0, 4, 2
  16300. ];
  16301. const _direction = /*@__PURE__*/ getDirection( uv$1(), attribute( 'faceIndex' ) ).normalize();
  16302. const _outputDirection = /*@__PURE__*/ vec3( _direction.x, _direction.y, _direction.z );
  16303. /**
  16304. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  16305. * (PMREM) from a cubeMap environment texture. This allows different levels of
  16306. * blur to be quickly accessed based on material roughness. It is packed into a
  16307. * special CubeUV format that allows us to perform custom interpolation so that
  16308. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  16309. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  16310. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  16311. * higher roughness levels. In this way we maintain resolution to smoothly
  16312. * interpolate diffuse lighting while limiting sampling computation.
  16313. *
  16314. * Paper: Fast, Accurate Image-Based Lighting:
  16315. * {@link https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view}
  16316. */
  16317. class PMREMGenerator {
  16318. /**
  16319. * Constructs a new PMREM generator.
  16320. *
  16321. * @param {Renderer} renderer - The renderer.
  16322. */
  16323. constructor( renderer ) {
  16324. this._renderer = renderer;
  16325. this._pingPongRenderTarget = null;
  16326. this._lodMax = 0;
  16327. this._cubeSize = 0;
  16328. this._lodPlanes = [];
  16329. this._sizeLods = [];
  16330. this._sigmas = [];
  16331. this._lodMeshes = [];
  16332. this._blurMaterial = null;
  16333. this._cubemapMaterial = null;
  16334. this._equirectMaterial = null;
  16335. this._backgroundBox = null;
  16336. }
  16337. get _hasInitialized() {
  16338. return this._renderer.hasInitialized();
  16339. }
  16340. /**
  16341. * Generates a PMREM from a supplied Scene, which can be faster than using an
  16342. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  16343. * in radians to be applied to the scene before PMREM generation. Optional near
  16344. * and far planes ensure the scene is rendered in its entirety.
  16345. *
  16346. * @param {Scene} scene - The scene to be captured.
  16347. * @param {number} [sigma=0] - The blur radius in radians.
  16348. * @param {number} [near=0.1] - The near plane distance.
  16349. * @param {number} [far=100] - The far plane distance.
  16350. * @param {Object} [options={}] - The configuration options.
  16351. * @param {number} [options.size=256] - The texture size of the PMREM.
  16352. * @param {Vector3} [options.renderTarget=origin] - The position of the internal cube camera that renders the scene.
  16353. * @param {?RenderTarget} [options.renderTarget=null] - The render target to use.
  16354. * @return {RenderTarget} The resulting PMREM.
  16355. * @see {@link PMREMGenerator#fromSceneAsync}
  16356. */
  16357. fromScene( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  16358. const {
  16359. size = 256,
  16360. position = _origin,
  16361. renderTarget = null,
  16362. } = options;
  16363. this._setSize( size );
  16364. if ( this._hasInitialized === false ) {
  16365. console.warn( 'THREE.PMREMGenerator: .fromScene() called before the backend is initialized. Try using .fromSceneAsync() instead.' );
  16366. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  16367. options.renderTarget = cubeUVRenderTarget;
  16368. this.fromSceneAsync( scene, sigma, near, far, options );
  16369. return cubeUVRenderTarget;
  16370. }
  16371. _oldTarget = this._renderer.getRenderTarget();
  16372. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  16373. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  16374. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  16375. cubeUVRenderTarget.depthBuffer = true;
  16376. this._init( cubeUVRenderTarget );
  16377. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position );
  16378. if ( sigma > 0 ) {
  16379. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  16380. }
  16381. this._applyPMREM( cubeUVRenderTarget );
  16382. this._cleanup( cubeUVRenderTarget );
  16383. return cubeUVRenderTarget;
  16384. }
  16385. /**
  16386. * Generates a PMREM from a supplied Scene, which can be faster than using an
  16387. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  16388. * in radians to be applied to the scene before PMREM generation. Optional near
  16389. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  16390. * is placed at the origin).
  16391. *
  16392. * @param {Scene} scene - The scene to be captured.
  16393. * @param {number} [sigma=0] - The blur radius in radians.
  16394. * @param {number} [near=0.1] - The near plane distance.
  16395. * @param {number} [far=100] - The far plane distance.
  16396. * @param {Object} [options={}] - The configuration options.
  16397. * @param {number} [options.size=256] - The texture size of the PMREM.
  16398. * @param {Vector3} [options.position=origin] - The position of the internal cube camera that renders the scene.
  16399. * @param {?RenderTarget} [options.renderTarget=null] - The render target to use.
  16400. * @return {Promise<RenderTarget>} A Promise that resolve with the PMREM when the generation has been finished.
  16401. * @see {@link PMREMGenerator#fromScene}
  16402. */
  16403. async fromSceneAsync( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  16404. if ( this._hasInitialized === false ) await this._renderer.init();
  16405. return this.fromScene( scene, sigma, near, far, options );
  16406. }
  16407. /**
  16408. * Generates a PMREM from an equirectangular texture, which can be either LDR
  16409. * or HDR. The ideal input image size is 1k (1024 x 512),
  16410. * as this matches best with the 256 x 256 cubemap output.
  16411. *
  16412. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  16413. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  16414. * @return {RenderTarget} The resulting PMREM.
  16415. * @see {@link PMREMGenerator#fromEquirectangularAsync}
  16416. */
  16417. fromEquirectangular( equirectangular, renderTarget = null ) {
  16418. if ( this._hasInitialized === false ) {
  16419. console.warn( 'THREE.PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using .fromEquirectangularAsync() instead.' );
  16420. this._setSizeFromTexture( equirectangular );
  16421. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  16422. this.fromEquirectangularAsync( equirectangular, cubeUVRenderTarget );
  16423. return cubeUVRenderTarget;
  16424. }
  16425. return this._fromTexture( equirectangular, renderTarget );
  16426. }
  16427. /**
  16428. * Generates a PMREM from an equirectangular texture, which can be either LDR
  16429. * or HDR. The ideal input image size is 1k (1024 x 512),
  16430. * as this matches best with the 256 x 256 cubemap output.
  16431. *
  16432. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  16433. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  16434. * @return {Promise<RenderTarget>} The resulting PMREM.
  16435. * @see {@link PMREMGenerator#fromEquirectangular}
  16436. */
  16437. async fromEquirectangularAsync( equirectangular, renderTarget = null ) {
  16438. if ( this._hasInitialized === false ) await this._renderer.init();
  16439. return this._fromTexture( equirectangular, renderTarget );
  16440. }
  16441. /**
  16442. * Generates a PMREM from an cubemap texture, which can be either LDR
  16443. * or HDR. The ideal input cube size is 256 x 256,
  16444. * as this matches best with the 256 x 256 cubemap output.
  16445. *
  16446. * @param {Texture} cubemap - The cubemap texture to be converted.
  16447. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  16448. * @return {RenderTarget} The resulting PMREM.
  16449. * @see {@link PMREMGenerator#fromCubemapAsync}
  16450. */
  16451. fromCubemap( cubemap, renderTarget = null ) {
  16452. if ( this._hasInitialized === false ) {
  16453. console.warn( 'THREE.PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead.' );
  16454. this._setSizeFromTexture( cubemap );
  16455. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  16456. this.fromCubemapAsync( cubemap, renderTarget );
  16457. return cubeUVRenderTarget;
  16458. }
  16459. return this._fromTexture( cubemap, renderTarget );
  16460. }
  16461. /**
  16462. * Generates a PMREM from an cubemap texture, which can be either LDR
  16463. * or HDR. The ideal input cube size is 256 x 256,
  16464. * with the 256 x 256 cubemap output.
  16465. *
  16466. * @param {Texture} cubemap - The cubemap texture to be converted.
  16467. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  16468. * @return {Promise<RenderTarget>} The resulting PMREM.
  16469. * @see {@link PMREMGenerator#fromCubemap}
  16470. */
  16471. async fromCubemapAsync( cubemap, renderTarget = null ) {
  16472. if ( this._hasInitialized === false ) await this._renderer.init();
  16473. return this._fromTexture( cubemap, renderTarget );
  16474. }
  16475. /**
  16476. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  16477. * your texture's network fetch for increased concurrency.
  16478. *
  16479. * @returns {Promise}
  16480. */
  16481. async compileCubemapShader() {
  16482. if ( this._cubemapMaterial === null ) {
  16483. this._cubemapMaterial = _getCubemapMaterial();
  16484. await this._compileMaterial( this._cubemapMaterial );
  16485. }
  16486. }
  16487. /**
  16488. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  16489. * your texture's network fetch for increased concurrency.
  16490. *
  16491. * @returns {Promise}
  16492. */
  16493. async compileEquirectangularShader() {
  16494. if ( this._equirectMaterial === null ) {
  16495. this._equirectMaterial = _getEquirectMaterial();
  16496. await this._compileMaterial( this._equirectMaterial );
  16497. }
  16498. }
  16499. /**
  16500. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  16501. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  16502. * one of them will cause any others to also become unusable.
  16503. */
  16504. dispose() {
  16505. this._dispose();
  16506. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  16507. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  16508. if ( this._backgroundBox !== null ) {
  16509. this._backgroundBox.geometry.dispose();
  16510. this._backgroundBox.material.dispose();
  16511. }
  16512. }
  16513. // private interface
  16514. _setSizeFromTexture( texture ) {
  16515. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  16516. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  16517. } else { // Equirectangular
  16518. this._setSize( texture.image.width / 4 );
  16519. }
  16520. }
  16521. _setSize( cubeSize ) {
  16522. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  16523. this._cubeSize = Math.pow( 2, this._lodMax );
  16524. }
  16525. _dispose() {
  16526. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  16527. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  16528. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  16529. this._lodPlanes[ i ].dispose();
  16530. }
  16531. }
  16532. _cleanup( outputTarget ) {
  16533. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  16534. outputTarget.scissorTest = false;
  16535. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  16536. }
  16537. _fromTexture( texture, renderTarget ) {
  16538. this._setSizeFromTexture( texture );
  16539. _oldTarget = this._renderer.getRenderTarget();
  16540. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  16541. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  16542. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  16543. this._init( cubeUVRenderTarget );
  16544. this._textureToCubeUV( texture, cubeUVRenderTarget );
  16545. this._applyPMREM( cubeUVRenderTarget );
  16546. this._cleanup( cubeUVRenderTarget );
  16547. return cubeUVRenderTarget;
  16548. }
  16549. _allocateTarget() {
  16550. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  16551. const height = 4 * this._cubeSize;
  16552. const cubeUVRenderTarget = _createRenderTarget( width, height );
  16553. return cubeUVRenderTarget;
  16554. }
  16555. _init( renderTarget ) {
  16556. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== renderTarget.width || this._pingPongRenderTarget.height !== renderTarget.height ) {
  16557. if ( this._pingPongRenderTarget !== null ) {
  16558. this._dispose();
  16559. }
  16560. this._pingPongRenderTarget = _createRenderTarget( renderTarget.width, renderTarget.height );
  16561. const { _lodMax } = this;
  16562. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas, lodMeshes: this._lodMeshes } = _createPlanes( _lodMax ) );
  16563. this._blurMaterial = _getBlurShader( _lodMax, renderTarget.width, renderTarget.height );
  16564. }
  16565. }
  16566. async _compileMaterial( material ) {
  16567. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  16568. await this._renderer.compile( tmpMesh, _flatCamera );
  16569. }
  16570. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position ) {
  16571. const cubeCamera = _cubeCamera;
  16572. cubeCamera.near = near;
  16573. cubeCamera.far = far;
  16574. // px, py, pz, nx, ny, nz
  16575. const upSign = [ 1, 1, 1, 1, -1, 1 ];
  16576. const forwardSign = [ 1, -1, 1, -1, 1, -1 ];
  16577. const renderer = this._renderer;
  16578. const originalAutoClear = renderer.autoClear;
  16579. renderer.getClearColor( _clearColor$2 );
  16580. renderer.autoClear = false;
  16581. let backgroundBox = this._backgroundBox;
  16582. if ( backgroundBox === null ) {
  16583. const backgroundMaterial = new MeshBasicMaterial( {
  16584. name: 'PMREM.Background',
  16585. side: BackSide,
  16586. depthWrite: false,
  16587. depthTest: false
  16588. } );
  16589. backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  16590. }
  16591. let useSolidColor = false;
  16592. const background = scene.background;
  16593. if ( background ) {
  16594. if ( background.isColor ) {
  16595. backgroundBox.material.color.copy( background );
  16596. scene.background = null;
  16597. useSolidColor = true;
  16598. }
  16599. } else {
  16600. backgroundBox.material.color.copy( _clearColor$2 );
  16601. useSolidColor = true;
  16602. }
  16603. renderer.setRenderTarget( cubeUVRenderTarget );
  16604. renderer.clear();
  16605. if ( useSolidColor ) {
  16606. renderer.render( backgroundBox, cubeCamera );
  16607. }
  16608. for ( let i = 0; i < 6; i ++ ) {
  16609. const col = i % 3;
  16610. if ( col === 0 ) {
  16611. cubeCamera.up.set( 0, upSign[ i ], 0 );
  16612. cubeCamera.position.set( position.x, position.y, position.z );
  16613. cubeCamera.lookAt( position.x + forwardSign[ i ], position.y, position.z );
  16614. } else if ( col === 1 ) {
  16615. cubeCamera.up.set( 0, 0, upSign[ i ] );
  16616. cubeCamera.position.set( position.x, position.y, position.z );
  16617. cubeCamera.lookAt( position.x, position.y + forwardSign[ i ], position.z );
  16618. } else {
  16619. cubeCamera.up.set( 0, upSign[ i ], 0 );
  16620. cubeCamera.position.set( position.x, position.y, position.z );
  16621. cubeCamera.lookAt( position.x, position.y, position.z + forwardSign[ i ] );
  16622. }
  16623. const size = this._cubeSize;
  16624. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  16625. renderer.render( scene, cubeCamera );
  16626. }
  16627. renderer.autoClear = originalAutoClear;
  16628. scene.background = background;
  16629. }
  16630. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  16631. const renderer = this._renderer;
  16632. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  16633. if ( isCubeTexture ) {
  16634. if ( this._cubemapMaterial === null ) {
  16635. this._cubemapMaterial = _getCubemapMaterial( texture );
  16636. }
  16637. } else {
  16638. if ( this._equirectMaterial === null ) {
  16639. this._equirectMaterial = _getEquirectMaterial( texture );
  16640. }
  16641. }
  16642. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  16643. material.fragmentNode.value = texture;
  16644. const mesh = this._lodMeshes[ 0 ];
  16645. mesh.material = material;
  16646. const size = this._cubeSize;
  16647. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  16648. renderer.setRenderTarget( cubeUVRenderTarget );
  16649. renderer.render( mesh, _flatCamera );
  16650. }
  16651. _applyPMREM( cubeUVRenderTarget ) {
  16652. const renderer = this._renderer;
  16653. const autoClear = renderer.autoClear;
  16654. renderer.autoClear = false;
  16655. const n = this._lodPlanes.length;
  16656. for ( let i = 1; i < n; i ++ ) {
  16657. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  16658. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  16659. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  16660. }
  16661. renderer.autoClear = autoClear;
  16662. }
  16663. /**
  16664. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  16665. * vertically and horizontally, but this breaks down on a cube. Here we apply
  16666. * the blur latitudinally (around the poles), and then longitudinally (towards
  16667. * the poles) to approximate the orthogonally-separable blur. It is least
  16668. * accurate at the poles, but still does a decent job.
  16669. *
  16670. * @private
  16671. * @param {RenderTarget} cubeUVRenderTarget - The cubemap render target.
  16672. * @param {number} lodIn - The input level-of-detail.
  16673. * @param {number} lodOut - The output level-of-detail.
  16674. * @param {number} sigma - The blur radius in radians.
  16675. * @param {Vector3} [poleAxis] - The pole axis.
  16676. */
  16677. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  16678. const pingPongRenderTarget = this._pingPongRenderTarget;
  16679. this._halfBlur(
  16680. cubeUVRenderTarget,
  16681. pingPongRenderTarget,
  16682. lodIn,
  16683. lodOut,
  16684. sigma,
  16685. 'latitudinal',
  16686. poleAxis );
  16687. this._halfBlur(
  16688. pingPongRenderTarget,
  16689. cubeUVRenderTarget,
  16690. lodOut,
  16691. lodOut,
  16692. sigma,
  16693. 'longitudinal',
  16694. poleAxis );
  16695. }
  16696. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  16697. const renderer = this._renderer;
  16698. const blurMaterial = this._blurMaterial;
  16699. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  16700. console.error( 'blur direction must be either latitudinal or longitudinal!' );
  16701. }
  16702. // Number of standard deviations at which to cut off the discrete approximation.
  16703. const STANDARD_DEVIATIONS = 3;
  16704. const blurMesh = this._lodMeshes[ lodOut ];
  16705. blurMesh.material = blurMaterial;
  16706. const blurUniforms = _uniformsMap.get( blurMaterial );
  16707. const pixels = this._sizeLods[ lodIn ] - 1;
  16708. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  16709. const sigmaPixels = sigmaRadians / radiansPerPixel;
  16710. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  16711. if ( samples > MAX_SAMPLES ) {
  16712. console.warn( `sigmaRadians, ${
  16713. sigmaRadians}, is too large and will clip, as it requested ${
  16714. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  16715. }
  16716. const weights = [];
  16717. let sum = 0;
  16718. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  16719. const x = i / sigmaPixels;
  16720. const weight = Math.exp( - x * x / 2 );
  16721. weights.push( weight );
  16722. if ( i === 0 ) {
  16723. sum += weight;
  16724. } else if ( i < samples ) {
  16725. sum += 2 * weight;
  16726. }
  16727. }
  16728. for ( let i = 0; i < weights.length; i ++ ) {
  16729. weights[ i ] = weights[ i ] / sum;
  16730. }
  16731. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  16732. blurUniforms.envMap.value = targetIn.texture;
  16733. blurUniforms.samples.value = samples;
  16734. blurUniforms.weights.array = weights;
  16735. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  16736. if ( poleAxis ) {
  16737. blurUniforms.poleAxis.value = poleAxis;
  16738. }
  16739. const { _lodMax } = this;
  16740. blurUniforms.dTheta.value = radiansPerPixel;
  16741. blurUniforms.mipInt.value = _lodMax - lodIn;
  16742. const outputSize = this._sizeLods[ lodOut ];
  16743. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  16744. const y = 4 * ( this._cubeSize - outputSize );
  16745. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  16746. renderer.setRenderTarget( targetOut );
  16747. renderer.render( blurMesh, _flatCamera );
  16748. }
  16749. }
  16750. function _createPlanes( lodMax ) {
  16751. const lodPlanes = [];
  16752. const sizeLods = [];
  16753. const sigmas = [];
  16754. const lodMeshes = [];
  16755. let lod = lodMax;
  16756. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  16757. for ( let i = 0; i < totalLods; i ++ ) {
  16758. const sizeLod = Math.pow( 2, lod );
  16759. sizeLods.push( sizeLod );
  16760. let sigma = 1.0 / sizeLod;
  16761. if ( i > lodMax - LOD_MIN ) {
  16762. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  16763. } else if ( i === 0 ) {
  16764. sigma = 0;
  16765. }
  16766. sigmas.push( sigma );
  16767. const texelSize = 1.0 / ( sizeLod - 2 );
  16768. const min = - texelSize;
  16769. const max = 1 + texelSize;
  16770. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  16771. const cubeFaces = 6;
  16772. const vertices = 6;
  16773. const positionSize = 3;
  16774. const uvSize = 2;
  16775. const faceIndexSize = 1;
  16776. const position = new Float32Array( positionSize * vertices * cubeFaces );
  16777. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  16778. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  16779. for ( let face = 0; face < cubeFaces; face ++ ) {
  16780. const x = ( face % 3 ) * 2 / 3 - 1;
  16781. const y = face > 2 ? 0 : -1;
  16782. const coordinates = [
  16783. x, y, 0,
  16784. x + 2 / 3, y, 0,
  16785. x + 2 / 3, y + 1, 0,
  16786. x, y, 0,
  16787. x + 2 / 3, y + 1, 0,
  16788. x, y + 1, 0
  16789. ];
  16790. const faceIdx = _faceLib[ face ];
  16791. position.set( coordinates, positionSize * vertices * faceIdx );
  16792. uv.set( uv1, uvSize * vertices * faceIdx );
  16793. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  16794. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  16795. }
  16796. const planes = new BufferGeometry();
  16797. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  16798. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  16799. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  16800. lodPlanes.push( planes );
  16801. lodMeshes.push( new Mesh( planes, null ) );
  16802. if ( lod > LOD_MIN ) {
  16803. lod --;
  16804. }
  16805. }
  16806. return { lodPlanes, sizeLods, sigmas, lodMeshes };
  16807. }
  16808. function _createRenderTarget( width, height ) {
  16809. const params = {
  16810. magFilter: LinearFilter,
  16811. minFilter: LinearFilter,
  16812. generateMipmaps: false,
  16813. type: HalfFloatType,
  16814. format: RGBAFormat,
  16815. colorSpace: LinearSRGBColorSpace,
  16816. //depthBuffer: false
  16817. };
  16818. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  16819. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  16820. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  16821. cubeUVRenderTarget.texture.isPMREMTexture = true;
  16822. cubeUVRenderTarget.scissorTest = true;
  16823. return cubeUVRenderTarget;
  16824. }
  16825. function _setViewport( target, x, y, width, height ) {
  16826. target.viewport.set( x, y, width, height );
  16827. target.scissor.set( x, y, width, height );
  16828. }
  16829. function _getMaterial( type ) {
  16830. const material = new NodeMaterial();
  16831. material.depthTest = false;
  16832. material.depthWrite = false;
  16833. material.blending = NoBlending;
  16834. material.name = `PMREM_${ type }`;
  16835. return material;
  16836. }
  16837. function _getBlurShader( lodMax, width, height ) {
  16838. const weights = uniformArray( new Array( MAX_SAMPLES ).fill( 0 ) );
  16839. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  16840. const dTheta = uniform( 0 );
  16841. const n = float( MAX_SAMPLES );
  16842. const latitudinal = uniform( 0 ); // false, bool
  16843. const samples = uniform( 1 ); // int
  16844. const envMap = texture( null );
  16845. const mipInt = uniform( 0 ); // int
  16846. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  16847. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  16848. const CUBEUV_MAX_MIP = float( lodMax );
  16849. const materialUniforms = {
  16850. n,
  16851. latitudinal,
  16852. weights,
  16853. poleAxis,
  16854. outputDirection: _outputDirection,
  16855. dTheta,
  16856. samples,
  16857. envMap,
  16858. mipInt,
  16859. CUBEUV_TEXEL_WIDTH,
  16860. CUBEUV_TEXEL_HEIGHT,
  16861. CUBEUV_MAX_MIP
  16862. };
  16863. const material = _getMaterial( 'blur' );
  16864. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  16865. _uniformsMap.set( material, materialUniforms );
  16866. return material;
  16867. }
  16868. function _getCubemapMaterial( envTexture ) {
  16869. const material = _getMaterial( 'cubemap' );
  16870. material.fragmentNode = cubeTexture( envTexture, _outputDirection );
  16871. return material;
  16872. }
  16873. function _getEquirectMaterial( envTexture ) {
  16874. const material = _getMaterial( 'equirect' );
  16875. material.fragmentNode = texture( envTexture, equirectUV( _outputDirection ), 0 );
  16876. return material;
  16877. }
  16878. const _cache = new WeakMap();
  16879. /**
  16880. * Generates the cubeUV size based on the given image height.
  16881. *
  16882. * @private
  16883. * @param {number} imageHeight - The image height.
  16884. * @return {{texelWidth: number,texelHeight: number, maxMip: number}} The result object.
  16885. */
  16886. function _generateCubeUVSize( imageHeight ) {
  16887. const maxMip = Math.log2( imageHeight ) - 2;
  16888. const texelHeight = 1.0 / imageHeight;
  16889. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  16890. return { texelWidth, texelHeight, maxMip };
  16891. }
  16892. /**
  16893. * Generates a PMREM from the given texture.
  16894. *
  16895. * @private
  16896. * @param {Texture} texture - The texture to create the PMREM for.
  16897. * @param {Renderer} renderer - The renderer.
  16898. * @param {PMREMGenerator} generator - The PMREM generator.
  16899. * @return {?Texture} The PMREM.
  16900. */
  16901. function _getPMREMFromTexture( texture, renderer, generator ) {
  16902. const cache = _getCache( renderer );
  16903. let cacheTexture = cache.get( texture );
  16904. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : -1;
  16905. if ( pmremVersion !== texture.pmremVersion ) {
  16906. const image = texture.image;
  16907. if ( texture.isCubeTexture ) {
  16908. if ( isCubeMapReady( image ) ) {
  16909. cacheTexture = generator.fromCubemap( texture, cacheTexture );
  16910. } else {
  16911. return null;
  16912. }
  16913. } else {
  16914. if ( isEquirectangularMapReady( image ) ) {
  16915. cacheTexture = generator.fromEquirectangular( texture, cacheTexture );
  16916. } else {
  16917. return null;
  16918. }
  16919. }
  16920. cacheTexture.pmremVersion = texture.pmremVersion;
  16921. cache.set( texture, cacheTexture );
  16922. }
  16923. return cacheTexture.texture;
  16924. }
  16925. /**
  16926. * Returns a cache that stores generated PMREMs for the respective textures.
  16927. * A cache must be maintained per renderer since PMREMs are render target textures
  16928. * which can't be shared across render contexts.
  16929. *
  16930. * @private
  16931. * @param {Renderer} renderer - The renderer.
  16932. * @return {WeakMap<Texture, Texture>} The PMREM cache.
  16933. */
  16934. function _getCache( renderer ) {
  16935. let rendererCache = _cache.get( renderer );
  16936. if ( rendererCache === undefined ) {
  16937. rendererCache = new WeakMap();
  16938. _cache.set( renderer, rendererCache );
  16939. }
  16940. return rendererCache;
  16941. }
  16942. /**
  16943. * This node represents a PMREM which is a special type of preprocessed
  16944. * environment map intended for PBR materials.
  16945. *
  16946. * ```js
  16947. * const material = new MeshStandardNodeMaterial();
  16948. * material.envNode = pmremTexture( envMap );
  16949. * ```
  16950. *
  16951. * @augments TempNode
  16952. */
  16953. class PMREMNode extends TempNode {
  16954. static get type() {
  16955. return 'PMREMNode';
  16956. }
  16957. /**
  16958. * Constructs a new function overloading node.
  16959. *
  16960. * @param {Texture} value - The input texture.
  16961. * @param {Node<vec2>} [uvNode=null] - The uv node.
  16962. * @param {Node<float>} [levelNode=null] - The level node.
  16963. */
  16964. constructor( value, uvNode = null, levelNode = null ) {
  16965. super( 'vec3' );
  16966. /**
  16967. * Reference to the input texture.
  16968. *
  16969. * @private
  16970. * @type {Texture}
  16971. */
  16972. this._value = value;
  16973. /**
  16974. * Reference to the generated PMREM.
  16975. *
  16976. * @private
  16977. * @type {Texture | null}
  16978. * @default null
  16979. */
  16980. this._pmrem = null;
  16981. /**
  16982. * The uv node.
  16983. *
  16984. * @type {Node<vec2>}
  16985. */
  16986. this.uvNode = uvNode;
  16987. /**
  16988. * The level node.
  16989. *
  16990. * @type {Node<float>}
  16991. */
  16992. this.levelNode = levelNode;
  16993. /**
  16994. * Reference to a PMREM generator.
  16995. *
  16996. * @private
  16997. * @type {?PMREMGenerator}
  16998. * @default null
  16999. */
  17000. this._generator = null;
  17001. const defaultTexture = new Texture();
  17002. defaultTexture.isRenderTargetTexture = true;
  17003. /**
  17004. * The texture node holding the generated PMREM.
  17005. *
  17006. * @private
  17007. * @type {TextureNode}
  17008. */
  17009. this._texture = texture( defaultTexture );
  17010. /**
  17011. * A uniform representing the PMREM's width.
  17012. *
  17013. * @private
  17014. * @type {UniformNode<float>}
  17015. */
  17016. this._width = uniform( 0 );
  17017. /**
  17018. * A uniform representing the PMREM's height.
  17019. *
  17020. * @private
  17021. * @type {UniformNode<float>}
  17022. */
  17023. this._height = uniform( 0 );
  17024. /**
  17025. * A uniform representing the PMREM's max Mip.
  17026. *
  17027. * @private
  17028. * @type {UniformNode<float>}
  17029. */
  17030. this._maxMip = uniform( 0 );
  17031. /**
  17032. * The `updateBeforeType` is set to `NodeUpdateType.RENDER`.
  17033. *
  17034. * @type {string}
  17035. * @default 'render'
  17036. */
  17037. this.updateBeforeType = NodeUpdateType.RENDER;
  17038. }
  17039. set value( value ) {
  17040. this._value = value;
  17041. this._pmrem = null;
  17042. }
  17043. /**
  17044. * The node's texture value.
  17045. *
  17046. * @type {Texture}
  17047. */
  17048. get value() {
  17049. return this._value;
  17050. }
  17051. /**
  17052. * Uses the given PMREM texture to update internal values.
  17053. *
  17054. * @param {Texture} texture - The PMREM texture.
  17055. */
  17056. updateFromTexture( texture ) {
  17057. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  17058. this._texture.value = texture;
  17059. this._width.value = cubeUVSize.texelWidth;
  17060. this._height.value = cubeUVSize.texelHeight;
  17061. this._maxMip.value = cubeUVSize.maxMip;
  17062. }
  17063. updateBefore( frame ) {
  17064. let pmrem = this._pmrem;
  17065. const pmremVersion = pmrem ? pmrem.pmremVersion : -1;
  17066. const texture = this._value;
  17067. if ( pmremVersion !== texture.pmremVersion ) {
  17068. if ( texture.isPMREMTexture === true ) {
  17069. pmrem = texture;
  17070. } else {
  17071. pmrem = _getPMREMFromTexture( texture, frame.renderer, this._generator );
  17072. }
  17073. if ( pmrem !== null ) {
  17074. this._pmrem = pmrem;
  17075. this.updateFromTexture( pmrem );
  17076. }
  17077. }
  17078. }
  17079. setup( builder ) {
  17080. if ( this._generator === null ) {
  17081. this._generator = new PMREMGenerator( builder.renderer );
  17082. }
  17083. this.updateBefore( builder );
  17084. //
  17085. let uvNode = this.uvNode;
  17086. if ( uvNode === null && builder.context.getUV ) {
  17087. uvNode = builder.context.getUV( this );
  17088. }
  17089. //
  17090. uvNode = materialEnvRotation.mul( vec3( uvNode.x, uvNode.y.negate(), uvNode.z ) );
  17091. //
  17092. let levelNode = this.levelNode;
  17093. if ( levelNode === null && builder.context.getTextureLevel ) {
  17094. levelNode = builder.context.getTextureLevel( this );
  17095. }
  17096. //
  17097. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  17098. }
  17099. dispose() {
  17100. super.dispose();
  17101. if ( this._generator !== null ) this._generator.dispose();
  17102. }
  17103. }
  17104. /**
  17105. * Returns `true` if the given cube map image has been fully loaded.
  17106. *
  17107. * @private
  17108. * @param {?Array<(Image|Object)>} [image] - The cube map image.
  17109. * @return {boolean} Whether the given cube map is ready or not.
  17110. */
  17111. function isCubeMapReady( image ) {
  17112. if ( image === null || image === undefined ) return false;
  17113. let count = 0;
  17114. const length = 6;
  17115. for ( let i = 0; i < length; i ++ ) {
  17116. if ( image[ i ] !== undefined ) count ++;
  17117. }
  17118. return count === length;
  17119. }
  17120. /**
  17121. * Returns `true` if the given equirectangular image has been fully loaded.
  17122. *
  17123. * @private
  17124. * @param {(Image|Object)} image - The equirectangular image.
  17125. * @return {boolean} Whether the given cube map is ready or not.
  17126. */
  17127. function isEquirectangularMapReady( image ) {
  17128. if ( image === null || image === undefined ) return false;
  17129. return image.height > 0;
  17130. }
  17131. /**
  17132. * TSL function for creating a PMREM node.
  17133. *
  17134. * @tsl
  17135. * @function
  17136. * @param {Texture} value - The input texture.
  17137. * @param {?Node<vec2>} [uvNode=null] - The uv node.
  17138. * @param {?Node<float>} [levelNode=null] - The level node.
  17139. * @returns {PMREMNode}
  17140. */
  17141. const pmremTexture = /*@__PURE__*/ nodeProxy( PMREMNode ).setParameterLength( 1, 3 );
  17142. const _envNodeCache = new WeakMap();
  17143. /**
  17144. * Represents a physical model for Image-based lighting (IBL). The environment
  17145. * is defined via environment maps in the equirectangular, cube map or cubeUV (PMREM) format.
  17146. * `EnvironmentNode` is intended for PBR materials like {@link MeshStandardNodeMaterial}.
  17147. *
  17148. * @augments LightingNode
  17149. */
  17150. class EnvironmentNode extends LightingNode {
  17151. static get type() {
  17152. return 'EnvironmentNode';
  17153. }
  17154. /**
  17155. * Constructs a new environment node.
  17156. *
  17157. * @param {Node} [envNode=null] - A node representing the environment.
  17158. */
  17159. constructor( envNode = null ) {
  17160. super();
  17161. /**
  17162. * A node representing the environment.
  17163. *
  17164. * @type {?Node}
  17165. * @default null
  17166. */
  17167. this.envNode = envNode;
  17168. }
  17169. setup( builder ) {
  17170. const { material } = builder;
  17171. let envNode = this.envNode;
  17172. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  17173. const value = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  17174. let cacheEnvNode = _envNodeCache.get( value );
  17175. if ( cacheEnvNode === undefined ) {
  17176. cacheEnvNode = pmremTexture( value );
  17177. _envNodeCache.set( value, cacheEnvNode );
  17178. }
  17179. envNode = cacheEnvNode;
  17180. }
  17181. //
  17182. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  17183. const radianceNormalView = useAnisotropy ? bentNormalView : normalView;
  17184. const radiance = envNode.context( createRadianceContext( roughness, radianceNormalView ) ).mul( materialEnvIntensity );
  17185. const irradiance = envNode.context( createIrradianceContext( normalWorld ) ).mul( Math.PI ).mul( materialEnvIntensity );
  17186. const isolateRadiance = cache( radiance );
  17187. const isolateIrradiance = cache( irradiance );
  17188. //
  17189. builder.context.radiance.addAssign( isolateRadiance );
  17190. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  17191. //
  17192. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  17193. if ( clearcoatRadiance ) {
  17194. const clearcoatRadianceContext = envNode.context( createRadianceContext( clearcoatRoughness, clearcoatNormalView ) ).mul( materialEnvIntensity );
  17195. const isolateClearcoatRadiance = cache( clearcoatRadianceContext );
  17196. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  17197. }
  17198. }
  17199. }
  17200. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  17201. let reflectVec = null;
  17202. return {
  17203. getUV: () => {
  17204. if ( reflectVec === null ) {
  17205. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  17206. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  17207. reflectVec = roughnessNode.mul( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  17208. reflectVec = reflectVec.transformDirection( cameraViewMatrix );
  17209. }
  17210. return reflectVec;
  17211. },
  17212. getTextureLevel: () => {
  17213. return roughnessNode;
  17214. }
  17215. };
  17216. };
  17217. const createIrradianceContext = ( normalWorldNode ) => {
  17218. return {
  17219. getUV: () => {
  17220. return normalWorldNode;
  17221. },
  17222. getTextureLevel: () => {
  17223. return float( 1.0 );
  17224. }
  17225. };
  17226. };
  17227. const _defaultValues$6 = /*@__PURE__*/ new MeshStandardMaterial();
  17228. /**
  17229. * Node material version of {@link MeshStandardMaterial}.
  17230. *
  17231. * @augments NodeMaterial
  17232. */
  17233. class MeshStandardNodeMaterial extends NodeMaterial {
  17234. static get type() {
  17235. return 'MeshStandardNodeMaterial';
  17236. }
  17237. /**
  17238. * Constructs a new mesh standard node material.
  17239. *
  17240. * @param {Object} [parameters] - The configuration parameter.
  17241. */
  17242. constructor( parameters ) {
  17243. super();
  17244. /**
  17245. * This flag can be used for type testing.
  17246. *
  17247. * @type {boolean}
  17248. * @readonly
  17249. * @default true
  17250. */
  17251. this.isMeshStandardNodeMaterial = true;
  17252. /**
  17253. * Set to `true` because standard materials react on lights.
  17254. *
  17255. * @type {boolean}
  17256. * @default true
  17257. */
  17258. this.lights = true;
  17259. /**
  17260. * The emissive color of standard materials is by default inferred from the `emissive`,
  17261. * `emissiveIntensity` and `emissiveMap` properties. This node property allows to
  17262. * overwrite the default and define the emissive color with a node instead.
  17263. *
  17264. * If you don't want to overwrite the emissive color but modify the existing
  17265. * value instead, use {@link materialEmissive}.
  17266. *
  17267. * @type {?Node<vec3>}
  17268. * @default null
  17269. */
  17270. this.emissiveNode = null;
  17271. /**
  17272. * The metalness of standard materials is by default inferred from the `metalness`,
  17273. * and `metalnessMap` properties. This node property allows to
  17274. * overwrite the default and define the metalness with a node instead.
  17275. *
  17276. * If you don't want to overwrite the metalness but modify the existing
  17277. * value instead, use {@link materialMetalness}.
  17278. *
  17279. * @type {?Node<float>}
  17280. * @default null
  17281. */
  17282. this.metalnessNode = null;
  17283. /**
  17284. * The roughness of standard materials is by default inferred from the `roughness`,
  17285. * and `roughnessMap` properties. This node property allows to
  17286. * overwrite the default and define the roughness with a node instead.
  17287. *
  17288. * If you don't want to overwrite the roughness but modify the existing
  17289. * value instead, use {@link materialRoughness}.
  17290. *
  17291. * @type {?Node<float>}
  17292. * @default null
  17293. */
  17294. this.roughnessNode = null;
  17295. this.setDefaultValues( _defaultValues$6 );
  17296. this.setValues( parameters );
  17297. }
  17298. /**
  17299. * Overwritten since this type of material uses {@link EnvironmentNode}
  17300. * to implement the PBR (PMREM based) environment mapping. Besides, the
  17301. * method honors `Scene.environment`.
  17302. *
  17303. * @param {NodeBuilder} builder - The current node builder.
  17304. * @return {?EnvironmentNode<vec3>} The environment node.
  17305. */
  17306. setupEnvironment( builder ) {
  17307. let envNode = super.setupEnvironment( builder );
  17308. if ( envNode === null && builder.environmentNode ) {
  17309. envNode = builder.environmentNode;
  17310. }
  17311. return envNode ? new EnvironmentNode( envNode ) : null;
  17312. }
  17313. /**
  17314. * Setups the lighting model.
  17315. *
  17316. * @return {PhysicalLightingModel} The lighting model.
  17317. */
  17318. setupLightingModel( /*builder*/ ) {
  17319. return new PhysicalLightingModel();
  17320. }
  17321. /**
  17322. * Setups the specular related node variables.
  17323. */
  17324. setupSpecular() {
  17325. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  17326. specularColor.assign( specularColorNode );
  17327. specularF90.assign( 1.0 );
  17328. }
  17329. /**
  17330. * Setups the standard specific node variables.
  17331. *
  17332. * @param {NodeBuilder} builder - The current node builder.
  17333. */
  17334. setupVariants() {
  17335. // METALNESS
  17336. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  17337. metalness.assign( metalnessNode );
  17338. // ROUGHNESS
  17339. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  17340. roughnessNode = getRoughness( { roughness: roughnessNode } );
  17341. roughness.assign( roughnessNode );
  17342. // SPECULAR COLOR
  17343. this.setupSpecular();
  17344. // DIFFUSE COLOR
  17345. diffuseColor.assign( vec4( diffuseColor.rgb.mul( metalnessNode.oneMinus() ), diffuseColor.a ) );
  17346. }
  17347. copy( source ) {
  17348. this.emissiveNode = source.emissiveNode;
  17349. this.metalnessNode = source.metalnessNode;
  17350. this.roughnessNode = source.roughnessNode;
  17351. return super.copy( source );
  17352. }
  17353. }
  17354. const _defaultValues$5 = /*@__PURE__*/ new MeshPhysicalMaterial();
  17355. /**
  17356. * Node material version of {@link MeshPhysicalMaterial}.
  17357. *
  17358. * @augments MeshStandardNodeMaterial
  17359. */
  17360. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  17361. static get type() {
  17362. return 'MeshPhysicalNodeMaterial';
  17363. }
  17364. /**
  17365. * Constructs a new mesh physical node material.
  17366. *
  17367. * @param {Object} [parameters] - The configuration parameter.
  17368. */
  17369. constructor( parameters ) {
  17370. super();
  17371. /**
  17372. * This flag can be used for type testing.
  17373. *
  17374. * @type {boolean}
  17375. * @readonly
  17376. * @default true
  17377. */
  17378. this.isMeshPhysicalNodeMaterial = true;
  17379. /**
  17380. * The clearcoat of physical materials is by default inferred from the `clearcoat`
  17381. * and `clearcoatMap` properties. This node property allows to overwrite the default
  17382. * and define the clearcoat with a node instead.
  17383. *
  17384. * If you don't want to overwrite the clearcoat but modify the existing
  17385. * value instead, use {@link materialClearcoat}.
  17386. *
  17387. * @type {?Node<float>}
  17388. * @default null
  17389. */
  17390. this.clearcoatNode = null;
  17391. /**
  17392. * The clearcoat roughness of physical materials is by default inferred from the `clearcoatRoughness`
  17393. * and `clearcoatRoughnessMap` properties. This node property allows to overwrite the default
  17394. * and define the clearcoat roughness with a node instead.
  17395. *
  17396. * If you don't want to overwrite the clearcoat roughness but modify the existing
  17397. * value instead, use {@link materialClearcoatRoughness}.
  17398. *
  17399. * @type {?Node<float>}
  17400. * @default null
  17401. */
  17402. this.clearcoatRoughnessNode = null;
  17403. /**
  17404. * The clearcoat normal of physical materials is by default inferred from the `clearcoatNormalMap`
  17405. * property. This node property allows to overwrite the default
  17406. * and define the clearcoat normal with a node instead.
  17407. *
  17408. * If you don't want to overwrite the clearcoat normal but modify the existing
  17409. * value instead, use {@link materialClearcoatNormal}.
  17410. *
  17411. * @type {?Node<vec3>}
  17412. * @default null
  17413. */
  17414. this.clearcoatNormalNode = null;
  17415. /**
  17416. * The sheen of physical materials is by default inferred from the `sheen`, `sheenColor`
  17417. * and `sheenColorMap` properties. This node property allows to overwrite the default
  17418. * and define the sheen with a node instead.
  17419. *
  17420. * If you don't want to overwrite the sheen but modify the existing
  17421. * value instead, use {@link materialSheen}.
  17422. *
  17423. * @type {?Node<vec3>}
  17424. * @default null
  17425. */
  17426. this.sheenNode = null;
  17427. /**
  17428. * The sheen roughness of physical materials is by default inferred from the `sheenRoughness` and
  17429. * `sheenRoughnessMap` properties. This node property allows to overwrite the default
  17430. * and define the sheen roughness with a node instead.
  17431. *
  17432. * If you don't want to overwrite the sheen roughness but modify the existing
  17433. * value instead, use {@link materialSheenRoughness}.
  17434. *
  17435. * @type {?Node<float>}
  17436. * @default null
  17437. */
  17438. this.sheenRoughnessNode = null;
  17439. /**
  17440. * The iridescence of physical materials is by default inferred from the `iridescence`
  17441. * property. This node property allows to overwrite the default
  17442. * and define the iridescence with a node instead.
  17443. *
  17444. * If you don't want to overwrite the iridescence but modify the existing
  17445. * value instead, use {@link materialIridescence}.
  17446. *
  17447. * @type {?Node<float>}
  17448. * @default null
  17449. */
  17450. this.iridescenceNode = null;
  17451. /**
  17452. * The iridescence IOR of physical materials is by default inferred from the `iridescenceIOR`
  17453. * property. This node property allows to overwrite the default
  17454. * and define the iridescence IOR with a node instead.
  17455. *
  17456. * If you don't want to overwrite the iridescence IOR but modify the existing
  17457. * value instead, use {@link materialIridescenceIOR}.
  17458. *
  17459. * @type {?Node<float>}
  17460. * @default null
  17461. */
  17462. this.iridescenceIORNode = null;
  17463. /**
  17464. * The iridescence thickness of physical materials is by default inferred from the `iridescenceThicknessRange`
  17465. * and `iridescenceThicknessMap` properties. This node property allows to overwrite the default
  17466. * and define the iridescence thickness with a node instead.
  17467. *
  17468. * If you don't want to overwrite the iridescence thickness but modify the existing
  17469. * value instead, use {@link materialIridescenceThickness}.
  17470. *
  17471. * @type {?Node<float>}
  17472. * @default null
  17473. */
  17474. this.iridescenceThicknessNode = null;
  17475. /**
  17476. * The specular intensity of physical materials is by default inferred from the `specularIntensity`
  17477. * and `specularIntensityMap` properties. This node property allows to overwrite the default
  17478. * and define the specular intensity with a node instead.
  17479. *
  17480. * If you don't want to overwrite the specular intensity but modify the existing
  17481. * value instead, use {@link materialSpecularIntensity}.
  17482. *
  17483. * @type {?Node<float>}
  17484. * @default null
  17485. */
  17486. this.specularIntensityNode = null;
  17487. /**
  17488. * The specular color of physical materials is by default inferred from the `specularColor`
  17489. * and `specularColorMap` properties. This node property allows to overwrite the default
  17490. * and define the specular color with a node instead.
  17491. *
  17492. * If you don't want to overwrite the specular color but modify the existing
  17493. * value instead, use {@link materialSpecularColor}.
  17494. *
  17495. * @type {?Node<vec3>}
  17496. * @default null
  17497. */
  17498. this.specularColorNode = null;
  17499. /**
  17500. * The ior of physical materials is by default inferred from the `ior`
  17501. * property. This node property allows to overwrite the default
  17502. * and define the ior with a node instead.
  17503. *
  17504. * If you don't want to overwrite the ior but modify the existing
  17505. * value instead, use {@link materialIOR}.
  17506. *
  17507. * @type {?Node<float>}
  17508. * @default null
  17509. */
  17510. this.iorNode = null;
  17511. /**
  17512. * The transmission of physical materials is by default inferred from the `transmission` and
  17513. * `transmissionMap` properties. This node property allows to overwrite the default
  17514. * and define the transmission with a node instead.
  17515. *
  17516. * If you don't want to overwrite the transmission but modify the existing
  17517. * value instead, use {@link materialTransmission}.
  17518. *
  17519. * @type {?Node<float>}
  17520. * @default null
  17521. */
  17522. this.transmissionNode = null;
  17523. /**
  17524. * The thickness of physical materials is by default inferred from the `thickness` and
  17525. * `thicknessMap` properties. This node property allows to overwrite the default
  17526. * and define the thickness with a node instead.
  17527. *
  17528. * If you don't want to overwrite the thickness but modify the existing
  17529. * value instead, use {@link materialThickness}.
  17530. *
  17531. * @type {?Node<float>}
  17532. * @default null
  17533. */
  17534. this.thicknessNode = null;
  17535. /**
  17536. * The attenuation distance of physical materials is by default inferred from the
  17537. * `attenuationDistance` property. This node property allows to overwrite the default
  17538. * and define the attenuation distance with a node instead.
  17539. *
  17540. * If you don't want to overwrite the attenuation distance but modify the existing
  17541. * value instead, use {@link materialAttenuationDistance}.
  17542. *
  17543. * @type {?Node<float>}
  17544. * @default null
  17545. */
  17546. this.attenuationDistanceNode = null;
  17547. /**
  17548. * The attenuation color of physical materials is by default inferred from the
  17549. * `attenuationColor` property. This node property allows to overwrite the default
  17550. * and define the attenuation color with a node instead.
  17551. *
  17552. * If you don't want to overwrite the attenuation color but modify the existing
  17553. * value instead, use {@link materialAttenuationColor}.
  17554. *
  17555. * @type {?Node<vec3>}
  17556. * @default null
  17557. */
  17558. this.attenuationColorNode = null;
  17559. /**
  17560. * The dispersion of physical materials is by default inferred from the
  17561. * `dispersion` property. This node property allows to overwrite the default
  17562. * and define the dispersion with a node instead.
  17563. *
  17564. * If you don't want to overwrite the dispersion but modify the existing
  17565. * value instead, use {@link materialDispersion}.
  17566. *
  17567. * @type {?Node<float>}
  17568. * @default null
  17569. */
  17570. this.dispersionNode = null;
  17571. /**
  17572. * The anisotropy of physical materials is by default inferred from the
  17573. * `anisotropy` property. This node property allows to overwrite the default
  17574. * and define the anisotropy with a node instead.
  17575. *
  17576. * If you don't want to overwrite the anisotropy but modify the existing
  17577. * value instead, use {@link materialAnisotropy}.
  17578. *
  17579. * @type {?Node<float>}
  17580. * @default null
  17581. */
  17582. this.anisotropyNode = null;
  17583. this.setDefaultValues( _defaultValues$5 );
  17584. this.setValues( parameters );
  17585. }
  17586. /**
  17587. * Whether the lighting model should use clearcoat or not.
  17588. *
  17589. * @type {boolean}
  17590. * @default true
  17591. */
  17592. get useClearcoat() {
  17593. return this.clearcoat > 0 || this.clearcoatNode !== null;
  17594. }
  17595. /**
  17596. * Whether the lighting model should use iridescence or not.
  17597. *
  17598. * @type {boolean}
  17599. * @default true
  17600. */
  17601. get useIridescence() {
  17602. return this.iridescence > 0 || this.iridescenceNode !== null;
  17603. }
  17604. /**
  17605. * Whether the lighting model should use sheen or not.
  17606. *
  17607. * @type {boolean}
  17608. * @default true
  17609. */
  17610. get useSheen() {
  17611. return this.sheen > 0 || this.sheenNode !== null;
  17612. }
  17613. /**
  17614. * Whether the lighting model should use anisotropy or not.
  17615. *
  17616. * @type {boolean}
  17617. * @default true
  17618. */
  17619. get useAnisotropy() {
  17620. return this.anisotropy > 0 || this.anisotropyNode !== null;
  17621. }
  17622. /**
  17623. * Whether the lighting model should use transmission or not.
  17624. *
  17625. * @type {boolean}
  17626. * @default true
  17627. */
  17628. get useTransmission() {
  17629. return this.transmission > 0 || this.transmissionNode !== null;
  17630. }
  17631. /**
  17632. * Whether the lighting model should use dispersion or not.
  17633. *
  17634. * @type {boolean}
  17635. * @default true
  17636. */
  17637. get useDispersion() {
  17638. return this.dispersion > 0 || this.dispersionNode !== null;
  17639. }
  17640. /**
  17641. * Setups the specular related node variables.
  17642. */
  17643. setupSpecular() {
  17644. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  17645. ior.assign( iorNode );
  17646. 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 ) );
  17647. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  17648. }
  17649. /**
  17650. * Setups the lighting model.
  17651. *
  17652. * @return {PhysicalLightingModel} The lighting model.
  17653. */
  17654. setupLightingModel( /*builder*/ ) {
  17655. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion );
  17656. }
  17657. /**
  17658. * Setups the physical specific node variables.
  17659. *
  17660. * @param {NodeBuilder} builder - The current node builder.
  17661. */
  17662. setupVariants( builder ) {
  17663. super.setupVariants( builder );
  17664. // CLEARCOAT
  17665. if ( this.useClearcoat ) {
  17666. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  17667. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  17668. clearcoat.assign( clearcoatNode );
  17669. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  17670. }
  17671. // SHEEN
  17672. if ( this.useSheen ) {
  17673. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  17674. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  17675. sheen.assign( sheenNode );
  17676. sheenRoughness.assign( sheenRoughnessNode );
  17677. }
  17678. // IRIDESCENCE
  17679. if ( this.useIridescence ) {
  17680. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  17681. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  17682. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  17683. iridescence.assign( iridescenceNode );
  17684. iridescenceIOR.assign( iridescenceIORNode );
  17685. iridescenceThickness.assign( iridescenceThicknessNode );
  17686. }
  17687. // ANISOTROPY
  17688. if ( this.useAnisotropy ) {
  17689. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  17690. anisotropy.assign( anisotropyV.length() );
  17691. If( anisotropy.equal( 0.0 ), () => {
  17692. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  17693. } ).Else( () => {
  17694. anisotropyV.divAssign( vec2( anisotropy ) );
  17695. anisotropy.assign( anisotropy.saturate() );
  17696. } );
  17697. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  17698. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  17699. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  17700. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  17701. }
  17702. // TRANSMISSION
  17703. if ( this.useTransmission ) {
  17704. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  17705. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  17706. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  17707. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  17708. transmission.assign( transmissionNode );
  17709. thickness.assign( thicknessNode );
  17710. attenuationDistance.assign( attenuationDistanceNode );
  17711. attenuationColor.assign( attenuationColorNode );
  17712. if ( this.useDispersion ) {
  17713. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  17714. dispersion.assign( dispersionNode );
  17715. }
  17716. }
  17717. }
  17718. /**
  17719. * Setups the clearcoat normal node.
  17720. *
  17721. * @return {Node<vec3>} The clearcoat normal.
  17722. */
  17723. setupClearcoatNormal() {
  17724. return this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  17725. }
  17726. setup( builder ) {
  17727. builder.context.setupClearcoatNormal = () => subBuild( this.setupClearcoatNormal( builder ), 'NORMAL', 'vec3' );
  17728. super.setup( builder );
  17729. }
  17730. copy( source ) {
  17731. this.clearcoatNode = source.clearcoatNode;
  17732. this.clearcoatRoughnessNode = source.clearcoatRoughnessNode;
  17733. this.clearcoatNormalNode = source.clearcoatNormalNode;
  17734. this.sheenNode = source.sheenNode;
  17735. this.sheenRoughnessNode = source.sheenRoughnessNode;
  17736. this.iridescenceNode = source.iridescenceNode;
  17737. this.iridescenceIORNode = source.iridescenceIORNode;
  17738. this.iridescenceThicknessNode = source.iridescenceThicknessNode;
  17739. this.specularIntensityNode = source.specularIntensityNode;
  17740. this.specularColorNode = source.specularColorNode;
  17741. this.transmissionNode = source.transmissionNode;
  17742. this.thicknessNode = source.thicknessNode;
  17743. this.attenuationDistanceNode = source.attenuationDistanceNode;
  17744. this.attenuationColorNode = source.attenuationColorNode;
  17745. this.dispersionNode = source.dispersionNode;
  17746. this.anisotropyNode = source.anisotropyNode;
  17747. return super.copy( source );
  17748. }
  17749. }
  17750. /**
  17751. * Represents the lighting model for {@link MeshSSSNodeMaterial}.
  17752. *
  17753. * @augments PhysicalLightingModel
  17754. */
  17755. class SSSLightingModel extends PhysicalLightingModel {
  17756. /**
  17757. * Constructs a new physical lighting model.
  17758. *
  17759. * @param {boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  17760. * @param {boolean} [sheen=false] - Whether sheen is supported or not.
  17761. * @param {boolean} [iridescence=false] - Whether iridescence is supported or not.
  17762. * @param {boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  17763. * @param {boolean} [transmission=false] - Whether transmission is supported or not.
  17764. * @param {boolean} [dispersion=false] - Whether dispersion is supported or not.
  17765. * @param {boolean} [sss=false] - Whether SSS is supported or not.
  17766. */
  17767. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false, sss = false ) {
  17768. super( clearcoat, sheen, iridescence, anisotropy, transmission, dispersion );
  17769. /**
  17770. * Whether the lighting model should use SSS or not.
  17771. *
  17772. * @type {boolean}
  17773. * @default false
  17774. */
  17775. this.useSSS = sss;
  17776. }
  17777. /**
  17778. * Extends the default implementation with a SSS term.
  17779. *
  17780. * 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/}
  17781. *
  17782. * @param {Object} input - The input data.
  17783. * @param {NodeBuilder} builder - The current node builder.
  17784. */
  17785. direct( { lightDirection, lightColor, reflectedLight }, builder ) {
  17786. if ( this.useSSS === true ) {
  17787. const material = builder.material;
  17788. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  17789. const scatteringHalf = lightDirection.add( normalView.mul( thicknessDistortionNode ) ).normalize();
  17790. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  17791. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  17792. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  17793. }
  17794. super.direct( { lightDirection, lightColor, reflectedLight }, builder );
  17795. }
  17796. }
  17797. /**
  17798. * This node material is an experimental extension of {@link MeshPhysicalNodeMaterial}
  17799. * that implements a Subsurface scattering (SSS) term.
  17800. *
  17801. * @augments MeshPhysicalNodeMaterial
  17802. */
  17803. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  17804. static get type() {
  17805. return 'MeshSSSNodeMaterial';
  17806. }
  17807. /**
  17808. * Constructs a new mesh SSS node material.
  17809. *
  17810. * @param {Object} [parameters] - The configuration parameter.
  17811. */
  17812. constructor( parameters ) {
  17813. super( parameters );
  17814. /**
  17815. * Represents the thickness color.
  17816. *
  17817. * @type {?Node<vec3>}
  17818. * @default null
  17819. */
  17820. this.thicknessColorNode = null;
  17821. /**
  17822. * Represents the distortion factor.
  17823. *
  17824. * @type {?Node<float>}
  17825. */
  17826. this.thicknessDistortionNode = float( 0.1 );
  17827. /**
  17828. * Represents the thickness ambient factor.
  17829. *
  17830. * @type {?Node<float>}
  17831. */
  17832. this.thicknessAmbientNode = float( 0.0 );
  17833. /**
  17834. * Represents the thickness attenuation.
  17835. *
  17836. * @type {?Node<float>}
  17837. */
  17838. this.thicknessAttenuationNode = float( .1 );
  17839. /**
  17840. * Represents the thickness power.
  17841. *
  17842. * @type {?Node<float>}
  17843. */
  17844. this.thicknessPowerNode = float( 2.0 );
  17845. /**
  17846. * Represents the thickness scale.
  17847. *
  17848. * @type {?Node<float>}
  17849. */
  17850. this.thicknessScaleNode = float( 10.0 );
  17851. }
  17852. /**
  17853. * Whether the lighting model should use SSS or not.
  17854. *
  17855. * @type {boolean}
  17856. * @default true
  17857. */
  17858. get useSSS() {
  17859. return this.thicknessColorNode !== null;
  17860. }
  17861. /**
  17862. * Setups the lighting model.
  17863. *
  17864. * @return {SSSLightingModel} The lighting model.
  17865. */
  17866. setupLightingModel( /*builder*/ ) {
  17867. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion, this.useSSS );
  17868. }
  17869. copy( source ) {
  17870. this.thicknessColorNode = source.thicknessColorNode;
  17871. this.thicknessDistortionNode = source.thicknessDistortionNode;
  17872. this.thicknessAmbientNode = source.thicknessAmbientNode;
  17873. this.thicknessAttenuationNode = source.thicknessAttenuationNode;
  17874. this.thicknessPowerNode = source.thicknessPowerNode;
  17875. this.thicknessScaleNode = source.thicknessScaleNode;
  17876. return super.copy( source );
  17877. }
  17878. }
  17879. const getGradientIrradiance = /*@__PURE__*/ Fn( ( { normal, lightDirection, builder } ) => {
  17880. // dotNL will be from -1.0 to 1.0
  17881. const dotNL = normal.dot( lightDirection );
  17882. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  17883. if ( builder.material.gradientMap ) {
  17884. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  17885. return vec3( gradientMap.r );
  17886. } else {
  17887. const fw = coord.fwidth().mul( 0.5 );
  17888. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  17889. }
  17890. } );
  17891. /**
  17892. * Represents the lighting model for a toon material. Used in {@link MeshToonNodeMaterial}.
  17893. *
  17894. * @augments LightingModel
  17895. */
  17896. class ToonLightingModel extends LightingModel {
  17897. /**
  17898. * Implements the direct lighting. Instead of using a conventional smooth irradiance, the irradiance is
  17899. * reduced to a small number of discrete shades to create a comic-like, flat look.
  17900. *
  17901. * @param {Object} lightData - The light data.
  17902. * @param {NodeBuilder} builder - The current node builder.
  17903. */
  17904. direct( { lightDirection, lightColor, reflectedLight }, builder ) {
  17905. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  17906. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  17907. }
  17908. /**
  17909. * Implements the indirect lighting.
  17910. *
  17911. * @param {NodeBuilder} builder - The current node builder.
  17912. */
  17913. indirect( builder ) {
  17914. const { ambientOcclusion, irradiance, reflectedLight } = builder.context;
  17915. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  17916. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  17917. }
  17918. }
  17919. const _defaultValues$4 = /*@__PURE__*/ new MeshToonMaterial();
  17920. /**
  17921. * Node material version of {@link MeshToonMaterial}.
  17922. *
  17923. * @augments NodeMaterial
  17924. */
  17925. class MeshToonNodeMaterial extends NodeMaterial {
  17926. static get type() {
  17927. return 'MeshToonNodeMaterial';
  17928. }
  17929. /**
  17930. * Constructs a new mesh toon node material.
  17931. *
  17932. * @param {Object} [parameters] - The configuration parameter.
  17933. */
  17934. constructor( parameters ) {
  17935. super();
  17936. /**
  17937. * This flag can be used for type testing.
  17938. *
  17939. * @type {boolean}
  17940. * @readonly
  17941. * @default true
  17942. */
  17943. this.isMeshToonNodeMaterial = true;
  17944. /**
  17945. * Set to `true` because toon materials react on lights.
  17946. *
  17947. * @type {boolean}
  17948. * @default true
  17949. */
  17950. this.lights = true;
  17951. this.setDefaultValues( _defaultValues$4 );
  17952. this.setValues( parameters );
  17953. }
  17954. /**
  17955. * Setups the lighting model.
  17956. *
  17957. * @return {ToonLightingModel} The lighting model.
  17958. */
  17959. setupLightingModel( /*builder*/ ) {
  17960. return new ToonLightingModel();
  17961. }
  17962. }
  17963. /**
  17964. * TSL function for creating a matcap uv node.
  17965. *
  17966. * Can be used to compute texture coordinates for projecting a
  17967. * matcap onto a mesh. Used by {@link MeshMatcapNodeMaterial}.
  17968. *
  17969. * @tsl
  17970. * @function
  17971. * @returns {Node<vec2>} The matcap UV coordinates.
  17972. */
  17973. const matcapUV = /*@__PURE__*/ Fn( () => {
  17974. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  17975. const y = positionViewDirection.cross( x );
  17976. return vec2( x.dot( normalView ), y.dot( normalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  17977. } ).once( [ 'NORMAL', 'VERTEX' ] )().toVar( 'matcapUV' );
  17978. const _defaultValues$3 = /*@__PURE__*/ new MeshMatcapMaterial();
  17979. /**
  17980. * Node material version of {@link MeshMatcapMaterial}.
  17981. *
  17982. * @augments NodeMaterial
  17983. */
  17984. class MeshMatcapNodeMaterial extends NodeMaterial {
  17985. static get type() {
  17986. return 'MeshMatcapNodeMaterial';
  17987. }
  17988. /**
  17989. * Constructs a new mesh normal node material.
  17990. *
  17991. * @param {Object} [parameters] - The configuration parameter.
  17992. */
  17993. constructor( parameters ) {
  17994. super();
  17995. /**
  17996. * This flag can be used for type testing.
  17997. *
  17998. * @type {boolean}
  17999. * @readonly
  18000. * @default true
  18001. */
  18002. this.isMeshMatcapNodeMaterial = true;
  18003. this.setDefaultValues( _defaultValues$3 );
  18004. this.setValues( parameters );
  18005. }
  18006. /**
  18007. * Setups the matcap specific node variables.
  18008. *
  18009. * @param {NodeBuilder} builder - The current node builder.
  18010. */
  18011. setupVariants( builder ) {
  18012. const uv = matcapUV;
  18013. let matcapColor;
  18014. if ( builder.material.matcap ) {
  18015. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  18016. } else {
  18017. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  18018. }
  18019. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  18020. }
  18021. }
  18022. /**
  18023. * Applies a rotation to the given position node.
  18024. *
  18025. * @augments TempNode
  18026. */
  18027. class RotateNode extends TempNode {
  18028. static get type() {
  18029. return 'RotateNode';
  18030. }
  18031. /**
  18032. * Constructs a new rotate node.
  18033. *
  18034. * @param {Node} positionNode - The position node.
  18035. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  18036. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  18037. */
  18038. constructor( positionNode, rotationNode ) {
  18039. super();
  18040. /**
  18041. * The position node.
  18042. *
  18043. * @type {Node}
  18044. */
  18045. this.positionNode = positionNode;
  18046. /**
  18047. * Represents the rotation that is applied to the position node.
  18048. * Depending on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  18049. *
  18050. * @type {Node}
  18051. */
  18052. this.rotationNode = rotationNode;
  18053. }
  18054. /**
  18055. * The type of the {@link RotateNode#positionNode} defines the node's type.
  18056. *
  18057. * @param {NodeBuilder} builder - The current node builder.
  18058. * @return {string} The node's type.
  18059. */
  18060. getNodeType( builder ) {
  18061. return this.positionNode.getNodeType( builder );
  18062. }
  18063. setup( builder ) {
  18064. const { rotationNode, positionNode } = this;
  18065. const nodeType = this.getNodeType( builder );
  18066. if ( nodeType === 'vec2' ) {
  18067. const cosAngle = rotationNode.cos();
  18068. const sinAngle = rotationNode.sin();
  18069. const rotationMatrix = mat2(
  18070. cosAngle, sinAngle,
  18071. sinAngle.negate(), cosAngle
  18072. );
  18073. return rotationMatrix.mul( positionNode );
  18074. } else {
  18075. const rotation = rotationNode;
  18076. 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 ) );
  18077. 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 ) );
  18078. 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 ) );
  18079. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  18080. }
  18081. }
  18082. }
  18083. /**
  18084. * TSL function for creating a rotate node.
  18085. *
  18086. * @tsl
  18087. * @function
  18088. * @param {Node} positionNode - The position node.
  18089. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  18090. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  18091. * @returns {RotateNode}
  18092. */
  18093. const rotate = /*@__PURE__*/ nodeProxy( RotateNode ).setParameterLength( 2 );
  18094. const _defaultValues$2 = /*@__PURE__*/ new SpriteMaterial();
  18095. /**
  18096. * Node material version of {@link SpriteMaterial}.
  18097. *
  18098. * @augments NodeMaterial
  18099. */
  18100. class SpriteNodeMaterial extends NodeMaterial {
  18101. static get type() {
  18102. return 'SpriteNodeMaterial';
  18103. }
  18104. /**
  18105. * Constructs a new sprite node material.
  18106. *
  18107. * @param {Object} [parameters] - The configuration parameter.
  18108. */
  18109. constructor( parameters ) {
  18110. super();
  18111. /**
  18112. * This flag can be used for type testing.
  18113. *
  18114. * @type {boolean}
  18115. * @readonly
  18116. * @default true
  18117. */
  18118. this.isSpriteNodeMaterial = true;
  18119. this._useSizeAttenuation = true;
  18120. /**
  18121. * This property makes it possible to define the position of the sprite with a
  18122. * node. That can be useful when the material is used with instanced rendering
  18123. * and node data are defined with an instanced attribute node:
  18124. * ```js
  18125. * const positionAttribute = new InstancedBufferAttribute( new Float32Array( positions ), 3 );
  18126. * material.positionNode = instancedBufferAttribute( positionAttribute );
  18127. * ```
  18128. * Another possibility is to compute the instanced data with a compute shader:
  18129. * ```js
  18130. * const positionBuffer = instancedArray( particleCount, 'vec3' );
  18131. * particleMaterial.positionNode = positionBuffer.toAttribute();
  18132. * ```
  18133. *
  18134. * @type {?Node<vec2>}
  18135. * @default null
  18136. */
  18137. this.positionNode = null;
  18138. /**
  18139. * The rotation of sprite materials is by default inferred from the `rotation`,
  18140. * property. This node property allows to overwrite the default and define
  18141. * the rotation with a node instead.
  18142. *
  18143. * If you don't want to overwrite the rotation but modify the existing
  18144. * value instead, use {@link materialRotation}.
  18145. *
  18146. * @type {?Node<float>}
  18147. * @default null
  18148. */
  18149. this.rotationNode = null;
  18150. /**
  18151. * This node property provides an additional way to scale sprites next to
  18152. * `Object3D.scale`. The scale transformation based in `Object3D.scale`
  18153. * is multiplied with the scale value of this node in the vertex shader.
  18154. *
  18155. * @type {?Node<vec2>}
  18156. * @default null
  18157. */
  18158. this.scaleNode = null;
  18159. /**
  18160. * In Sprites, the transparent property is enabled by default.
  18161. *
  18162. * @type {boolean}
  18163. * @default true
  18164. */
  18165. this.transparent = true;
  18166. this.setDefaultValues( _defaultValues$2 );
  18167. this.setValues( parameters );
  18168. }
  18169. /**
  18170. * Setups the position node in view space. This method implements
  18171. * the sprite specific vertex shader.
  18172. *
  18173. * @param {NodeBuilder} builder - The current node builder.
  18174. * @return {Node<vec3>} The position in view space.
  18175. */
  18176. setupPositionView( builder ) {
  18177. const { object, camera } = builder;
  18178. const sizeAttenuation = this.sizeAttenuation;
  18179. const { positionNode, rotationNode, scaleNode } = this;
  18180. const mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  18181. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  18182. if ( scaleNode !== null ) {
  18183. scale = scale.mul( vec2( scaleNode ) );
  18184. }
  18185. if ( sizeAttenuation === false ) {
  18186. if ( camera.isPerspectiveCamera ) {
  18187. scale = scale.mul( mvPosition.z.negate() );
  18188. } else {
  18189. const orthoScale = float( 2.0 ).div( cameraProjectionMatrix.element( 1 ).element( 1 ) );
  18190. scale = scale.mul( orthoScale.mul( 2 ) );
  18191. }
  18192. }
  18193. let alignedPosition = positionGeometry.xy;
  18194. if ( object.center && object.center.isVector2 === true ) {
  18195. const center = reference$1( 'center', 'vec2', object );
  18196. alignedPosition = alignedPosition.sub( center.sub( 0.5 ) );
  18197. }
  18198. alignedPosition = alignedPosition.mul( scale );
  18199. const rotation = float( rotationNode || materialRotation );
  18200. const rotatedPosition = rotate( alignedPosition, rotation );
  18201. return vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  18202. }
  18203. copy( source ) {
  18204. this.positionNode = source.positionNode;
  18205. this.rotationNode = source.rotationNode;
  18206. this.scaleNode = source.scaleNode;
  18207. return super.copy( source );
  18208. }
  18209. /**
  18210. * Whether to use size attenuation or not.
  18211. *
  18212. * @type {boolean}
  18213. * @default true
  18214. */
  18215. get sizeAttenuation() {
  18216. return this._useSizeAttenuation;
  18217. }
  18218. set sizeAttenuation( value ) {
  18219. if ( this._useSizeAttenuation !== value ) {
  18220. this._useSizeAttenuation = value;
  18221. this.needsUpdate = true;
  18222. }
  18223. }
  18224. }
  18225. const _defaultValues$1 = /*@__PURE__*/ new PointsMaterial();
  18226. /**
  18227. * Node material version of {@link PointsMaterial}.
  18228. *
  18229. * @augments SpriteNodeMaterial
  18230. */
  18231. class PointsNodeMaterial extends SpriteNodeMaterial {
  18232. static get type() {
  18233. return 'PointsNodeMaterial';
  18234. }
  18235. /**
  18236. * Constructs a new points node material.
  18237. *
  18238. * @param {Object} [parameters] - The configuration parameter.
  18239. */
  18240. constructor( parameters ) {
  18241. super();
  18242. /**
  18243. * This node property provides an additional way to set the point size.
  18244. *
  18245. * @type {?Node<vec2>}
  18246. * @default null
  18247. */
  18248. this.sizeNode = null;
  18249. /**
  18250. * This flag can be used for type testing.
  18251. *
  18252. * @type {boolean}
  18253. * @readonly
  18254. * @default true
  18255. */
  18256. this.isPointsNodeMaterial = true;
  18257. this.setDefaultValues( _defaultValues$1 );
  18258. this.setValues( parameters );
  18259. }
  18260. setupPositionView() {
  18261. const { positionNode } = this;
  18262. return modelViewMatrix.mul( vec3( positionNode || positionLocal ) ).xyz;
  18263. }
  18264. setupVertex( builder ) {
  18265. const mvp = super.setupVertex( builder );
  18266. // skip further processing if the material is not a node material
  18267. if ( builder.material.isNodeMaterial !== true ) {
  18268. return mvp;
  18269. }
  18270. // ndc space
  18271. const { rotationNode, scaleNode, sizeNode } = this;
  18272. const alignedPosition = positionGeometry.xy.toVar();
  18273. const aspect = viewport.z.div( viewport.w );
  18274. // rotation
  18275. if ( rotationNode && rotationNode.isNode ) {
  18276. const rotation = float( rotationNode );
  18277. alignedPosition.assign( rotate( alignedPosition, rotation ) );
  18278. }
  18279. // point size
  18280. let pointSize = sizeNode !== null ? vec2( sizeNode ) : materialPointSize;
  18281. if ( this.sizeAttenuation === true ) {
  18282. pointSize = pointSize.mul( pointSize.div( positionView.z.negate() ) );
  18283. }
  18284. // scale
  18285. if ( scaleNode && scaleNode.isNode ) {
  18286. pointSize = pointSize.mul( vec2( scaleNode ) );
  18287. }
  18288. alignedPosition.mulAssign( pointSize.mul( 2 ) );
  18289. alignedPosition.assign( alignedPosition.div( viewport.z ) );
  18290. alignedPosition.y.assign( alignedPosition.y.mul( aspect ) );
  18291. // back to clip space
  18292. alignedPosition.assign( alignedPosition.mul( mvp.w ) );
  18293. //clipPos.xy += offset;
  18294. mvp.addAssign( vec4( alignedPosition, 0, 0 ) );
  18295. return mvp;
  18296. }
  18297. /**
  18298. * Whether alpha to coverage should be used or not.
  18299. *
  18300. * @type {boolean}
  18301. * @default true
  18302. */
  18303. get alphaToCoverage() {
  18304. return this._useAlphaToCoverage;
  18305. }
  18306. set alphaToCoverage( value ) {
  18307. if ( this._useAlphaToCoverage !== value ) {
  18308. this._useAlphaToCoverage = value;
  18309. this.needsUpdate = true;
  18310. }
  18311. }
  18312. }
  18313. /**
  18314. * Represents lighting model for a shadow material. Used in {@link ShadowNodeMaterial}.
  18315. *
  18316. * @augments LightingModel
  18317. */
  18318. class ShadowMaskModel extends LightingModel {
  18319. /**
  18320. * Constructs a new shadow mask model.
  18321. */
  18322. constructor() {
  18323. super();
  18324. /**
  18325. * The shadow mask node.
  18326. *
  18327. * @type {Node}
  18328. */
  18329. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  18330. }
  18331. /**
  18332. * Only used to save the shadow mask.
  18333. *
  18334. * @param {Object} input - The input data.
  18335. */
  18336. direct( { lightNode } ) {
  18337. if ( lightNode.shadowNode !== null ) {
  18338. this.shadowNode.mulAssign( lightNode.shadowNode );
  18339. }
  18340. }
  18341. /**
  18342. * Uses the shadow mask to produce the final color.
  18343. *
  18344. * @param {NodeBuilder} builder - The current node builder.
  18345. */
  18346. finish( { context } ) {
  18347. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  18348. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  18349. }
  18350. }
  18351. const _defaultValues = /*@__PURE__*/ new ShadowMaterial();
  18352. /**
  18353. * Node material version of {@link ShadowMaterial}.
  18354. *
  18355. * @augments NodeMaterial
  18356. */
  18357. class ShadowNodeMaterial extends NodeMaterial {
  18358. static get type() {
  18359. return 'ShadowNodeMaterial';
  18360. }
  18361. /**
  18362. * Constructs a new shadow node material.
  18363. *
  18364. * @param {Object} [parameters] - The configuration parameter.
  18365. */
  18366. constructor( parameters ) {
  18367. super();
  18368. /**
  18369. * This flag can be used for type testing.
  18370. *
  18371. * @type {boolean}
  18372. * @readonly
  18373. * @default true
  18374. */
  18375. this.isShadowNodeMaterial = true;
  18376. /**
  18377. * Set to `true` because so it's possible to implement
  18378. * the shadow mask effect.
  18379. *
  18380. * @type {boolean}
  18381. * @default true
  18382. */
  18383. this.lights = true;
  18384. /**
  18385. * Overwritten since shadow materials are transparent
  18386. * by default.
  18387. *
  18388. * @type {boolean}
  18389. * @default true
  18390. */
  18391. this.transparent = true;
  18392. this.setDefaultValues( _defaultValues );
  18393. this.setValues( parameters );
  18394. }
  18395. /**
  18396. * Setups the lighting model.
  18397. *
  18398. * @return {ShadowMaskModel} The lighting model.
  18399. */
  18400. setupLightingModel( /*builder*/ ) {
  18401. return new ShadowMaskModel();
  18402. }
  18403. }
  18404. const scatteringDensity = property( 'vec3' );
  18405. const linearDepthRay = property( 'vec3' );
  18406. const outgoingRayLight = property( 'vec3' );
  18407. /**
  18408. * VolumetricLightingModel class extends the LightingModel to implement volumetric lighting effects.
  18409. * This model calculates the scattering and transmittance of light through a volumetric medium.
  18410. * It dynamically adjusts the direction of the ray based on the camera and object positions.
  18411. * The model supports custom scattering and depth nodes to enhance the lighting effects.
  18412. *
  18413. * @augments LightingModel
  18414. */
  18415. class VolumetricLightingModel extends LightingModel {
  18416. constructor() {
  18417. super();
  18418. }
  18419. start( builder ) {
  18420. const { material, context } = builder;
  18421. const startPos = property( 'vec3' );
  18422. const endPos = property( 'vec3' );
  18423. // This approach dynamically changes the direction of the ray,
  18424. // 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.
  18425. If( cameraPosition.sub( positionWorld ).length().greaterThan( modelRadius.mul( 2 ) ), () => {
  18426. startPos.assign( cameraPosition );
  18427. endPos.assign( positionWorld );
  18428. } ).Else( () => {
  18429. startPos.assign( positionWorld );
  18430. endPos.assign( cameraPosition );
  18431. } );
  18432. //
  18433. const viewVector = endPos.sub( startPos );
  18434. const steps = uniform( 'int' ).onRenderUpdate( ( { material } ) => material.steps );
  18435. const stepSize = viewVector.length().div( steps ).toVar();
  18436. const rayDir = viewVector.normalize().toVar(); // TODO: toVar() should be automatic here ( in loop )
  18437. const distTravelled = float( 0.0 ).toVar();
  18438. const transmittance = vec3( 1 ).toVar();
  18439. if ( material.offsetNode ) {
  18440. // reduce banding
  18441. distTravelled.addAssign( material.offsetNode.mul( stepSize ) );
  18442. }
  18443. Loop( steps, () => {
  18444. const positionRay = startPos.add( rayDir.mul( distTravelled ) );
  18445. const positionViewRay = cameraViewMatrix.mul( vec4( positionRay, 1 ) ).xyz;
  18446. if ( material.depthNode !== null ) {
  18447. linearDepthRay.assign( linearDepth( viewZToPerspectiveDepth( positionViewRay.z, cameraNear, cameraFar ) ) );
  18448. context.sceneDepthNode = linearDepth( material.depthNode ).toVar();
  18449. }
  18450. context.positionWorld = positionRay;
  18451. context.shadowPositionWorld = positionRay;
  18452. context.positionView = positionViewRay;
  18453. scatteringDensity.assign( 0 );
  18454. let scatteringNode;
  18455. if ( material.scatteringNode ) {
  18456. scatteringNode = material.scatteringNode( {
  18457. positionRay
  18458. } );
  18459. }
  18460. super.start( builder );
  18461. if ( scatteringNode ) {
  18462. scatteringDensity.mulAssign( scatteringNode );
  18463. }
  18464. // beer's law
  18465. const falloff = scatteringDensity.mul( .01 ).negate().mul( stepSize ).exp();
  18466. transmittance.mulAssign( falloff );
  18467. // move along the ray
  18468. distTravelled.addAssign( stepSize );
  18469. } );
  18470. outgoingRayLight.addAssign( transmittance.saturate().oneMinus() );
  18471. }
  18472. scatteringLight( lightColor, builder ) {
  18473. const sceneDepthNode = builder.context.sceneDepthNode;
  18474. if ( sceneDepthNode ) {
  18475. If( sceneDepthNode.greaterThanEqual( linearDepthRay ), () => {
  18476. scatteringDensity.addAssign( lightColor );
  18477. } );
  18478. } else {
  18479. scatteringDensity.addAssign( lightColor );
  18480. }
  18481. }
  18482. direct( { lightNode, lightColor }, builder ) {
  18483. // Ignore lights with infinite distance
  18484. if ( lightNode.light.distance === undefined ) return;
  18485. // TODO: We need a viewportOpaque*() ( output, depth ) to fit with modern rendering approaches
  18486. const directLight = lightColor.xyz.toVar();
  18487. directLight.mulAssign( lightNode.shadowNode ); // it no should be necessary if used in the same render pass
  18488. this.scatteringLight( directLight, builder );
  18489. }
  18490. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight }, builder ) {
  18491. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  18492. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  18493. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  18494. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  18495. const P = builder.context.positionView;
  18496. const directLight = lightColor.xyz.mul( LTC_Evaluate_Volume( { P, p0, p1, p2, p3 } ) ).pow( 1.5 );
  18497. this.scatteringLight( directLight, builder );
  18498. }
  18499. finish( builder ) {
  18500. builder.context.outgoingLight.assign( outgoingRayLight );
  18501. }
  18502. }
  18503. /**
  18504. * Volume node material.
  18505. *
  18506. * @augments NodeMaterial
  18507. */
  18508. class VolumeNodeMaterial extends NodeMaterial {
  18509. static get type() {
  18510. return 'VolumeNodeMaterial';
  18511. }
  18512. /**
  18513. * Constructs a new volume node material.
  18514. *
  18515. * @param {Object} [parameters] - The configuration parameter.
  18516. */
  18517. constructor( parameters ) {
  18518. super();
  18519. /**
  18520. * This flag can be used for type testing.
  18521. *
  18522. * @type {boolean}
  18523. * @readonly
  18524. * @default true
  18525. */
  18526. this.isVolumeNodeMaterial = true;
  18527. /**
  18528. * Number of steps used for raymarching.
  18529. *
  18530. * @type {number}
  18531. * @default 25
  18532. */
  18533. this.steps = 25;
  18534. /**
  18535. * Offsets the distance a ray has been traveled through a volume.
  18536. * Can be used to implement dithering to reduce banding.
  18537. *
  18538. * @type {Node<float>}
  18539. * @default null
  18540. */
  18541. this.offsetNode = null;
  18542. /**
  18543. * Node used for scattering calculations.
  18544. *
  18545. * @type {Function|FunctionNode<vec4>}
  18546. * @default null
  18547. */
  18548. this.scatteringNode = null;
  18549. this.lights = true;
  18550. this.transparent = true;
  18551. this.side = BackSide;
  18552. this.depthTest = false;
  18553. this.depthWrite = false;
  18554. this.setValues( parameters );
  18555. }
  18556. setupLightingModel() {
  18557. return new VolumetricLightingModel();
  18558. }
  18559. }
  18560. /**
  18561. * This module manages the internal animation loop of the renderer.
  18562. *
  18563. * @private
  18564. */
  18565. class Animation {
  18566. /**
  18567. * Constructs a new animation loop management component.
  18568. *
  18569. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  18570. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  18571. */
  18572. constructor( nodes, info ) {
  18573. /**
  18574. * Renderer component for managing nodes related logic.
  18575. *
  18576. * @type {Nodes}
  18577. */
  18578. this.nodes = nodes;
  18579. /**
  18580. * Renderer component for managing metrics and monitoring data.
  18581. *
  18582. * @type {Info}
  18583. */
  18584. this.info = info;
  18585. /**
  18586. * A reference to the context from `requestAnimationFrame()` can
  18587. * be called (usually `window`).
  18588. *
  18589. * @type {?(Window|XRSession)}
  18590. */
  18591. this._context = typeof self !== 'undefined' ? self : null;
  18592. /**
  18593. * The user-defined animation loop.
  18594. *
  18595. * @type {?Function}
  18596. * @default null
  18597. */
  18598. this._animationLoop = null;
  18599. /**
  18600. * The requestId which is returned from the `requestAnimationFrame()` call.
  18601. * Can be used to cancel the stop the animation loop.
  18602. *
  18603. * @type {?number}
  18604. * @default null
  18605. */
  18606. this._requestId = null;
  18607. }
  18608. /**
  18609. * Starts the internal animation loop.
  18610. */
  18611. start() {
  18612. const update = ( time, xrFrame ) => {
  18613. this._requestId = this._context.requestAnimationFrame( update );
  18614. if ( this.info.autoReset === true ) this.info.reset();
  18615. this.nodes.nodeFrame.update();
  18616. this.info.frame = this.nodes.nodeFrame.frameId;
  18617. if ( this._animationLoop !== null ) this._animationLoop( time, xrFrame );
  18618. };
  18619. update();
  18620. }
  18621. /**
  18622. * Stops the internal animation loop.
  18623. */
  18624. stop() {
  18625. this._context.cancelAnimationFrame( this._requestId );
  18626. this._requestId = null;
  18627. }
  18628. /**
  18629. * Returns the user-level animation loop.
  18630. *
  18631. * @return {?Function} The animation loop.
  18632. */
  18633. getAnimationLoop() {
  18634. return this._animationLoop;
  18635. }
  18636. /**
  18637. * Defines the user-level animation loop.
  18638. *
  18639. * @param {?Function} callback - The animation loop.
  18640. */
  18641. setAnimationLoop( callback ) {
  18642. this._animationLoop = callback;
  18643. }
  18644. /**
  18645. * Returns the animation context.
  18646. *
  18647. * @return {Window|XRSession} The animation context.
  18648. */
  18649. getContext() {
  18650. return this._context;
  18651. }
  18652. /**
  18653. * Defines the context in which `requestAnimationFrame()` is executed.
  18654. *
  18655. * @param {Window|XRSession} context - The context to set.
  18656. */
  18657. setContext( context ) {
  18658. this._context = context;
  18659. }
  18660. /**
  18661. * Frees all internal resources and stops the animation loop.
  18662. */
  18663. dispose() {
  18664. this.stop();
  18665. }
  18666. }
  18667. /**
  18668. * Data structure for the renderer. It allows defining values
  18669. * with chained, hierarchical keys. Keys are meant to be
  18670. * objects since the module internally works with Weak Maps
  18671. * for performance reasons.
  18672. *
  18673. * @private
  18674. */
  18675. class ChainMap {
  18676. /**
  18677. * Constructs a new Chain Map.
  18678. */
  18679. constructor() {
  18680. /**
  18681. * The root Weak Map.
  18682. *
  18683. * @type {WeakMap}
  18684. */
  18685. this.weakMap = new WeakMap();
  18686. }
  18687. /**
  18688. * Returns the value for the given array of keys.
  18689. *
  18690. * @param {Array<Object>} keys - List of keys.
  18691. * @return {any} The value. Returns `undefined` if no value was found.
  18692. */
  18693. get( keys ) {
  18694. let map = this.weakMap;
  18695. for ( let i = 0; i < keys.length - 1; i ++ ) {
  18696. map = map.get( keys[ i ] );
  18697. if ( map === undefined ) return undefined;
  18698. }
  18699. return map.get( keys[ keys.length - 1 ] );
  18700. }
  18701. /**
  18702. * Sets the value for the given keys.
  18703. *
  18704. * @param {Array<Object>} keys - List of keys.
  18705. * @param {any} value - The value to set.
  18706. * @return {ChainMap} A reference to this Chain Map.
  18707. */
  18708. set( keys, value ) {
  18709. let map = this.weakMap;
  18710. for ( let i = 0; i < keys.length - 1; i ++ ) {
  18711. const key = keys[ i ];
  18712. if ( map.has( key ) === false ) map.set( key, new WeakMap() );
  18713. map = map.get( key );
  18714. }
  18715. map.set( keys[ keys.length - 1 ], value );
  18716. return this;
  18717. }
  18718. /**
  18719. * Deletes a value for the given keys.
  18720. *
  18721. * @param {Array<Object>} keys - The keys.
  18722. * @return {boolean} Returns `true` if the value has been removed successfully and `false` if the value has not be found.
  18723. */
  18724. delete( keys ) {
  18725. let map = this.weakMap;
  18726. for ( let i = 0; i < keys.length - 1; i ++ ) {
  18727. map = map.get( keys[ i ] );
  18728. if ( map === undefined ) return false;
  18729. }
  18730. return map.delete( keys[ keys.length - 1 ] );
  18731. }
  18732. }
  18733. let _id$9 = 0;
  18734. function getKeys( obj ) {
  18735. const keys = Object.keys( obj );
  18736. let proto = Object.getPrototypeOf( obj );
  18737. while ( proto ) {
  18738. const descriptors = Object.getOwnPropertyDescriptors( proto );
  18739. for ( const key in descriptors ) {
  18740. if ( descriptors[ key ] !== undefined ) {
  18741. const descriptor = descriptors[ key ];
  18742. if ( descriptor && typeof descriptor.get === 'function' ) {
  18743. keys.push( key );
  18744. }
  18745. }
  18746. }
  18747. proto = Object.getPrototypeOf( proto );
  18748. }
  18749. return keys;
  18750. }
  18751. /**
  18752. * A render object is the renderer's representation of single entity that gets drawn
  18753. * with a draw command. There is no unique mapping of render objects to 3D objects in the
  18754. * scene since render objects also depend from the used material, the current render context
  18755. * and the current scene's lighting.
  18756. *
  18757. * In general, the basic process of the renderer is:
  18758. *
  18759. * - Analyze the 3D objects in the scene and generate render lists containing render items.
  18760. * - Process the render lists by calling one or more render commands for each render item.
  18761. * - For each render command, request a render object and perform the draw.
  18762. *
  18763. * The module provides an interface to get data required for the draw command like the actual
  18764. * draw parameters or vertex buffers. It also holds a series of caching related methods since
  18765. * creating render objects should only be done when necessary.
  18766. *
  18767. * @private
  18768. */
  18769. class RenderObject {
  18770. /**
  18771. * Constructs a new render object.
  18772. *
  18773. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  18774. * @param {Geometries} geometries - Renderer component for managing geometries.
  18775. * @param {Renderer} renderer - The renderer.
  18776. * @param {Object3D} object - The 3D object.
  18777. * @param {Material} material - The 3D object's material.
  18778. * @param {Scene} scene - The scene the 3D object belongs to.
  18779. * @param {Camera} camera - The camera the object should be rendered with.
  18780. * @param {LightsNode} lightsNode - The lights node.
  18781. * @param {RenderContext} renderContext - The render context.
  18782. * @param {ClippingContext} clippingContext - The clipping context.
  18783. */
  18784. constructor( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext ) {
  18785. this.id = _id$9 ++;
  18786. /**
  18787. * Renderer component for managing nodes related logic.
  18788. *
  18789. * @type {Nodes}
  18790. * @private
  18791. */
  18792. this._nodes = nodes;
  18793. /**
  18794. * Renderer component for managing geometries.
  18795. *
  18796. * @type {Geometries}
  18797. * @private
  18798. */
  18799. this._geometries = geometries;
  18800. /**
  18801. * The renderer.
  18802. *
  18803. * @type {Renderer}
  18804. */
  18805. this.renderer = renderer;
  18806. /**
  18807. * The 3D object.
  18808. *
  18809. * @type {Object3D}
  18810. */
  18811. this.object = object;
  18812. /**
  18813. * The 3D object's material.
  18814. *
  18815. * @type {Material}
  18816. */
  18817. this.material = material;
  18818. /**
  18819. * The scene the 3D object belongs to.
  18820. *
  18821. * @type {Scene}
  18822. */
  18823. this.scene = scene;
  18824. /**
  18825. * The camera the 3D object should be rendered with.
  18826. *
  18827. * @type {Camera}
  18828. */
  18829. this.camera = camera;
  18830. /**
  18831. * The lights node.
  18832. *
  18833. * @type {LightsNode}
  18834. */
  18835. this.lightsNode = lightsNode;
  18836. /**
  18837. * The render context.
  18838. *
  18839. * @type {RenderContext}
  18840. */
  18841. this.context = renderContext;
  18842. /**
  18843. * The 3D object's geometry.
  18844. *
  18845. * @type {BufferGeometry}
  18846. */
  18847. this.geometry = object.geometry;
  18848. /**
  18849. * The render object's version.
  18850. *
  18851. * @type {number}
  18852. */
  18853. this.version = material.version;
  18854. /**
  18855. * The draw range of the geometry.
  18856. *
  18857. * @type {?Object}
  18858. * @default null
  18859. */
  18860. this.drawRange = null;
  18861. /**
  18862. * An array holding the buffer attributes
  18863. * of the render object. This entails attribute
  18864. * definitions on geometry and node level.
  18865. *
  18866. * @type {?Array<BufferAttribute>}
  18867. * @default null
  18868. */
  18869. this.attributes = null;
  18870. /**
  18871. * An object holding the version of the
  18872. * attributes. The keys are the attribute names
  18873. * and the values are the attribute versions.
  18874. *
  18875. * @type {?Object<string, number>}
  18876. * @default null
  18877. */
  18878. this.attributesId = null;
  18879. /**
  18880. * A reference to a render pipeline the render
  18881. * object is processed with.
  18882. *
  18883. * @type {RenderPipeline}
  18884. * @default null
  18885. */
  18886. this.pipeline = null;
  18887. /**
  18888. * Only relevant for objects using
  18889. * multiple materials. This represents a group entry
  18890. * from the respective `BufferGeometry`.
  18891. *
  18892. * @type {?{start: number, count: number}}
  18893. * @default null
  18894. */
  18895. this.group = null;
  18896. /**
  18897. * An array holding the vertex buffers which can
  18898. * be buffer attributes but also interleaved buffers.
  18899. *
  18900. * @type {?Array<BufferAttribute|InterleavedBuffer>}
  18901. * @default null
  18902. */
  18903. this.vertexBuffers = null;
  18904. /**
  18905. * The parameters for the draw command.
  18906. *
  18907. * @type {?Object}
  18908. * @default null
  18909. */
  18910. this.drawParams = null;
  18911. /**
  18912. * If this render object is used inside a render bundle,
  18913. * this property points to the respective bundle group.
  18914. *
  18915. * @type {?BundleGroup}
  18916. * @default null
  18917. */
  18918. this.bundle = null;
  18919. /**
  18920. * The clipping context.
  18921. *
  18922. * @type {ClippingContext}
  18923. */
  18924. this.clippingContext = clippingContext;
  18925. /**
  18926. * The clipping context's cache key.
  18927. *
  18928. * @type {string}
  18929. */
  18930. this.clippingContextCacheKey = clippingContext !== null ? clippingContext.cacheKey : '';
  18931. /**
  18932. * The initial node cache key.
  18933. *
  18934. * @type {number}
  18935. */
  18936. this.initialNodesCacheKey = this.getDynamicCacheKey();
  18937. /**
  18938. * The initial cache key.
  18939. *
  18940. * @type {number}
  18941. */
  18942. this.initialCacheKey = this.getCacheKey();
  18943. /**
  18944. * The node builder state.
  18945. *
  18946. * @type {?NodeBuilderState}
  18947. * @private
  18948. * @default null
  18949. */
  18950. this._nodeBuilderState = null;
  18951. /**
  18952. * An array of bindings.
  18953. *
  18954. * @type {?Array<BindGroup>}
  18955. * @private
  18956. * @default null
  18957. */
  18958. this._bindings = null;
  18959. /**
  18960. * Reference to the node material observer.
  18961. *
  18962. * @type {?NodeMaterialObserver}
  18963. * @private
  18964. * @default null
  18965. */
  18966. this._monitor = null;
  18967. /**
  18968. * An event listener which is defined by `RenderObjects`. It performs
  18969. * clean up tasks when `dispose()` on this render object.
  18970. *
  18971. * @method
  18972. */
  18973. this.onDispose = null;
  18974. /**
  18975. * This flag can be used for type testing.
  18976. *
  18977. * @type {boolean}
  18978. * @readonly
  18979. * @default true
  18980. */
  18981. this.isRenderObject = true;
  18982. /**
  18983. * An event listener which is executed when `dispose()` is called on
  18984. * the material of this render object.
  18985. *
  18986. * @method
  18987. */
  18988. this.onMaterialDispose = () => {
  18989. this.dispose();
  18990. };
  18991. /**
  18992. * An event listener which is executed when `dispose()` is called on
  18993. * the geometry of this render object.
  18994. *
  18995. * @method
  18996. */
  18997. this.onGeometryDispose = () => {
  18998. // clear geometry cache attributes
  18999. this.attributes = null;
  19000. this.attributesId = null;
  19001. };
  19002. this.material.addEventListener( 'dispose', this.onMaterialDispose );
  19003. this.geometry.addEventListener( 'dispose', this.onGeometryDispose );
  19004. }
  19005. /**
  19006. * Updates the clipping context.
  19007. *
  19008. * @param {ClippingContext} context - The clipping context to set.
  19009. */
  19010. updateClipping( context ) {
  19011. this.clippingContext = context;
  19012. }
  19013. /**
  19014. * Whether the clipping requires an update or not.
  19015. *
  19016. * @type {boolean}
  19017. * @readonly
  19018. */
  19019. get clippingNeedsUpdate() {
  19020. if ( this.clippingContext === null || this.clippingContext.cacheKey === this.clippingContextCacheKey ) return false;
  19021. this.clippingContextCacheKey = this.clippingContext.cacheKey;
  19022. return true;
  19023. }
  19024. /**
  19025. * The number of clipping planes defined in context of hardware clipping.
  19026. *
  19027. * @type {number}
  19028. * @readonly
  19029. */
  19030. get hardwareClippingPlanes() {
  19031. return this.material.hardwareClipping === true ? this.clippingContext.unionClippingCount : 0;
  19032. }
  19033. /**
  19034. * Returns the node builder state of this render object.
  19035. *
  19036. * @return {NodeBuilderState} The node builder state.
  19037. */
  19038. getNodeBuilderState() {
  19039. return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) );
  19040. }
  19041. /**
  19042. * Returns the node material observer of this render object.
  19043. *
  19044. * @return {NodeMaterialObserver} The node material observer.
  19045. */
  19046. getMonitor() {
  19047. return this._monitor || ( this._monitor = this.getNodeBuilderState().observer );
  19048. }
  19049. /**
  19050. * Returns an array of bind groups of this render object.
  19051. *
  19052. * @return {Array<BindGroup>} The bindings.
  19053. */
  19054. getBindings() {
  19055. return this._bindings || ( this._bindings = this.getNodeBuilderState().createBindings() );
  19056. }
  19057. /**
  19058. * Returns a binding group by group name of this render object.
  19059. *
  19060. * @param {string} name - The name of the binding group.
  19061. * @return {?BindGroup} The bindings.
  19062. */
  19063. getBindingGroup( name ) {
  19064. for ( const bindingGroup of this.getBindings() ) {
  19065. if ( bindingGroup.name === name ) {
  19066. return bindingGroup;
  19067. }
  19068. }
  19069. }
  19070. /**
  19071. * Returns the index of the render object's geometry.
  19072. *
  19073. * @return {?BufferAttribute} The index. Returns `null` for non-indexed geometries.
  19074. */
  19075. getIndex() {
  19076. return this._geometries.getIndex( this );
  19077. }
  19078. /**
  19079. * Returns the indirect buffer attribute.
  19080. *
  19081. * @return {?BufferAttribute} The indirect attribute. `null` if no indirect drawing is used.
  19082. */
  19083. getIndirect() {
  19084. return this._geometries.getIndirect( this );
  19085. }
  19086. /**
  19087. * Returns an array that acts as a key for identifying the render object in a chain map.
  19088. *
  19089. * @return {Array<Object>} An array with object references.
  19090. */
  19091. getChainArray() {
  19092. return [ this.object, this.material, this.context, this.lightsNode ];
  19093. }
  19094. /**
  19095. * This method is used when the geometry of a 3D object has been exchanged and the
  19096. * respective render object now requires an update.
  19097. *
  19098. * @param {BufferGeometry} geometry - The geometry to set.
  19099. */
  19100. setGeometry( geometry ) {
  19101. this.geometry = geometry;
  19102. this.attributes = null;
  19103. this.attributesId = null;
  19104. }
  19105. /**
  19106. * Returns the buffer attributes of the render object. The returned array holds
  19107. * attribute definitions on geometry and node level.
  19108. *
  19109. * @return {Array<BufferAttribute>} An array with buffer attributes.
  19110. */
  19111. getAttributes() {
  19112. if ( this.attributes !== null ) return this.attributes;
  19113. const nodeAttributes = this.getNodeBuilderState().nodeAttributes;
  19114. const geometry = this.geometry;
  19115. const attributes = [];
  19116. const vertexBuffers = new Set();
  19117. const attributesId = {};
  19118. for ( const nodeAttribute of nodeAttributes ) {
  19119. let attribute;
  19120. if ( nodeAttribute.node && nodeAttribute.node.attribute ) {
  19121. // node attribute
  19122. attribute = nodeAttribute.node.attribute;
  19123. } else {
  19124. // geometry attribute
  19125. attribute = geometry.getAttribute( nodeAttribute.name );
  19126. attributesId[ nodeAttribute.name ] = attribute.version;
  19127. }
  19128. if ( attribute === undefined ) continue;
  19129. attributes.push( attribute );
  19130. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  19131. vertexBuffers.add( bufferAttribute );
  19132. }
  19133. this.attributes = attributes;
  19134. this.attributesId = attributesId;
  19135. this.vertexBuffers = Array.from( vertexBuffers.values() );
  19136. return attributes;
  19137. }
  19138. /**
  19139. * Returns the vertex buffers of the render object.
  19140. *
  19141. * @return {Array<BufferAttribute|InterleavedBuffer>} An array with buffer attribute or interleaved buffers.
  19142. */
  19143. getVertexBuffers() {
  19144. if ( this.vertexBuffers === null ) this.getAttributes();
  19145. return this.vertexBuffers;
  19146. }
  19147. /**
  19148. * Returns the draw parameters for the render object.
  19149. *
  19150. * @return {?{vertexCount: number, firstVertex: number, instanceCount: number, firstInstance: number}} The draw parameters.
  19151. */
  19152. getDrawParameters() {
  19153. const { object, material, geometry, group, drawRange } = this;
  19154. const drawParams = this.drawParams || ( this.drawParams = {
  19155. vertexCount: 0,
  19156. firstVertex: 0,
  19157. instanceCount: 0,
  19158. firstInstance: 0
  19159. } );
  19160. const index = this.getIndex();
  19161. const hasIndex = ( index !== null );
  19162. let instanceCount = 1;
  19163. if ( geometry.isInstancedBufferGeometry === true ) {
  19164. instanceCount = geometry.instanceCount;
  19165. } else if ( object.count !== undefined ) {
  19166. instanceCount = Math.max( 0, object.count );
  19167. }
  19168. if ( instanceCount === 0 ) return null;
  19169. drawParams.instanceCount = instanceCount;
  19170. if ( object.isBatchedMesh === true ) return drawParams;
  19171. let rangeFactor = 1;
  19172. if ( material.wireframe === true && ! object.isPoints && ! object.isLineSegments && ! object.isLine && ! object.isLineLoop ) {
  19173. rangeFactor = 2;
  19174. }
  19175. let firstVertex = drawRange.start * rangeFactor;
  19176. let lastVertex = ( drawRange.start + drawRange.count ) * rangeFactor;
  19177. if ( group !== null ) {
  19178. firstVertex = Math.max( firstVertex, group.start * rangeFactor );
  19179. lastVertex = Math.min( lastVertex, ( group.start + group.count ) * rangeFactor );
  19180. }
  19181. const position = geometry.attributes.position;
  19182. let itemCount = Infinity;
  19183. if ( hasIndex ) {
  19184. itemCount = index.count;
  19185. } else if ( position !== undefined && position !== null ) {
  19186. itemCount = position.count;
  19187. }
  19188. firstVertex = Math.max( firstVertex, 0 );
  19189. lastVertex = Math.min( lastVertex, itemCount );
  19190. const count = lastVertex - firstVertex;
  19191. if ( count < 0 || count === Infinity ) return null;
  19192. drawParams.vertexCount = count;
  19193. drawParams.firstVertex = firstVertex;
  19194. return drawParams;
  19195. }
  19196. /**
  19197. * Returns the render object's geometry cache key.
  19198. *
  19199. * The geometry cache key is part of the material cache key.
  19200. *
  19201. * @return {string} The geometry cache key.
  19202. */
  19203. getGeometryCacheKey() {
  19204. const { geometry } = this;
  19205. let cacheKey = '';
  19206. for ( const name of Object.keys( geometry.attributes ).sort() ) {
  19207. const attribute = geometry.attributes[ name ];
  19208. cacheKey += name + ',';
  19209. if ( attribute.data ) cacheKey += attribute.data.stride + ',';
  19210. if ( attribute.offset ) cacheKey += attribute.offset + ',';
  19211. if ( attribute.itemSize ) cacheKey += attribute.itemSize + ',';
  19212. if ( attribute.normalized ) cacheKey += 'n,';
  19213. }
  19214. // structural equality isn't sufficient for morph targets since the
  19215. // data are maintained in textures. only if the targets are all equal
  19216. // the texture and thus the instance of `MorphNode` can be shared.
  19217. for ( const name of Object.keys( geometry.morphAttributes ).sort() ) {
  19218. const targets = geometry.morphAttributes[ name ];
  19219. cacheKey += 'morph-' + name + ',';
  19220. for ( let i = 0, l = targets.length; i < l; i ++ ) {
  19221. const attribute = targets[ i ];
  19222. cacheKey += attribute.id + ',';
  19223. }
  19224. }
  19225. if ( geometry.index ) {
  19226. cacheKey += 'index,';
  19227. }
  19228. return cacheKey;
  19229. }
  19230. /**
  19231. * Returns the render object's material cache key.
  19232. *
  19233. * The material cache key is part of the render object cache key.
  19234. *
  19235. * @return {number} The material cache key.
  19236. */
  19237. getMaterialCacheKey() {
  19238. const { object, material } = this;
  19239. let cacheKey = material.customProgramCacheKey();
  19240. for ( const property of getKeys( material ) ) {
  19241. if ( /^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test( property ) ) continue;
  19242. const value = material[ property ];
  19243. let valueKey;
  19244. if ( value !== null ) {
  19245. // some material values require a formatting
  19246. const type = typeof value;
  19247. if ( type === 'number' ) {
  19248. valueKey = value !== 0 ? '1' : '0'; // Convert to on/off, important for clearcoat, transmission, etc
  19249. } else if ( type === 'object' ) {
  19250. valueKey = '{';
  19251. if ( value.isTexture ) {
  19252. valueKey += value.mapping;
  19253. }
  19254. valueKey += '}';
  19255. } else {
  19256. valueKey = String( value );
  19257. }
  19258. } else {
  19259. valueKey = String( value );
  19260. }
  19261. cacheKey += /*property + ':' +*/ valueKey + ',';
  19262. }
  19263. cacheKey += this.clippingContextCacheKey + ',';
  19264. if ( object.geometry ) {
  19265. cacheKey += this.getGeometryCacheKey();
  19266. }
  19267. if ( object.skeleton ) {
  19268. cacheKey += object.skeleton.bones.length + ',';
  19269. }
  19270. if ( object.isBatchedMesh ) {
  19271. cacheKey += object._matricesTexture.uuid + ',';
  19272. if ( object._colorsTexture !== null ) {
  19273. cacheKey += object._colorsTexture.uuid + ',';
  19274. }
  19275. }
  19276. if ( object.count > 1 ) {
  19277. // TODO: https://github.com/mrdoob/three.js/pull/29066#issuecomment-2269400850
  19278. cacheKey += object.uuid + ',';
  19279. }
  19280. cacheKey += object.receiveShadow + ',';
  19281. return hashString( cacheKey );
  19282. }
  19283. /**
  19284. * Whether the geometry requires an update or not.
  19285. *
  19286. * @type {boolean}
  19287. * @readonly
  19288. */
  19289. get needsGeometryUpdate() {
  19290. if ( this.geometry.id !== this.object.geometry.id ) return true;
  19291. if ( this.attributes !== null ) {
  19292. const attributesId = this.attributesId;
  19293. for ( const name in attributesId ) {
  19294. const attribute = this.geometry.getAttribute( name );
  19295. if ( attribute === undefined || attributesId[ name ] !== attribute.id ) {
  19296. return true;
  19297. }
  19298. }
  19299. }
  19300. return false;
  19301. }
  19302. /**
  19303. * Whether the render object requires an update or not.
  19304. *
  19305. * Note: There are two distinct places where render objects are checked for an update.
  19306. *
  19307. * 1. In `RenderObjects.get()` which is executed when the render object is request. This
  19308. * method checks the `needsUpdate` flag and recreates the render object if necessary.
  19309. * 2. In `Renderer._renderObjectDirect()` right after getting the render object via
  19310. * `RenderObjects.get()`. The render object's NodeMaterialObserver is then used to detect
  19311. * a need for a refresh due to material, geometry or object related value changes.
  19312. *
  19313. * TODO: Investigate if it's possible to merge both steps so there is only a single place
  19314. * that performs the 'needsUpdate' check.
  19315. *
  19316. * @type {boolean}
  19317. * @readonly
  19318. */
  19319. get needsUpdate() {
  19320. return /*this.object.static !== true &&*/ ( this.initialNodesCacheKey !== this.getDynamicCacheKey() || this.clippingNeedsUpdate );
  19321. }
  19322. /**
  19323. * Returns the dynamic cache key which represents a key that is computed per draw command.
  19324. *
  19325. * @return {number} The cache key.
  19326. */
  19327. getDynamicCacheKey() {
  19328. let cacheKey = 0;
  19329. // `Nodes.getCacheKey()` returns an environment cache key which is not relevant when
  19330. // the renderer is inside a shadow pass.
  19331. if ( this.material.isShadowPassMaterial !== true ) {
  19332. cacheKey = this._nodes.getCacheKey( this.scene, this.lightsNode );
  19333. }
  19334. if ( this.camera.isArrayCamera ) {
  19335. cacheKey = hash$1( cacheKey, this.camera.cameras.length );
  19336. }
  19337. if ( this.object.receiveShadow ) {
  19338. cacheKey = hash$1( cacheKey, 1 );
  19339. }
  19340. return cacheKey;
  19341. }
  19342. /**
  19343. * Returns the render object's cache key.
  19344. *
  19345. * @return {number} The cache key.
  19346. */
  19347. getCacheKey() {
  19348. return this.getMaterialCacheKey() + this.getDynamicCacheKey();
  19349. }
  19350. /**
  19351. * Frees internal resources.
  19352. */
  19353. dispose() {
  19354. this.material.removeEventListener( 'dispose', this.onMaterialDispose );
  19355. this.geometry.removeEventListener( 'dispose', this.onGeometryDispose );
  19356. this.onDispose();
  19357. }
  19358. }
  19359. const _chainKeys$5 = [];
  19360. /**
  19361. * This module manages the render objects of the renderer.
  19362. *
  19363. * @private
  19364. */
  19365. class RenderObjects {
  19366. /**
  19367. * Constructs a new render object management component.
  19368. *
  19369. * @param {Renderer} renderer - The renderer.
  19370. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  19371. * @param {Geometries} geometries - Renderer component for managing geometries.
  19372. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  19373. * @param {Bindings} bindings - Renderer component for managing bindings.
  19374. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  19375. */
  19376. constructor( renderer, nodes, geometries, pipelines, bindings, info ) {
  19377. /**
  19378. * The renderer.
  19379. *
  19380. * @type {Renderer}
  19381. */
  19382. this.renderer = renderer;
  19383. /**
  19384. * Renderer component for managing nodes related logic.
  19385. *
  19386. * @type {Nodes}
  19387. */
  19388. this.nodes = nodes;
  19389. /**
  19390. * Renderer component for managing geometries.
  19391. *
  19392. * @type {Geometries}
  19393. */
  19394. this.geometries = geometries;
  19395. /**
  19396. * Renderer component for managing pipelines.
  19397. *
  19398. * @type {Pipelines}
  19399. */
  19400. this.pipelines = pipelines;
  19401. /**
  19402. * Renderer component for managing bindings.
  19403. *
  19404. * @type {Bindings}
  19405. */
  19406. this.bindings = bindings;
  19407. /**
  19408. * Renderer component for managing metrics and monitoring data.
  19409. *
  19410. * @type {Info}
  19411. */
  19412. this.info = info;
  19413. /**
  19414. * A dictionary that manages render contexts in chain maps
  19415. * for each pass ID.
  19416. *
  19417. * @type {Object<string,ChainMap>}
  19418. */
  19419. this.chainMaps = {};
  19420. }
  19421. /**
  19422. * Returns a render object for the given object and state data.
  19423. *
  19424. * @param {Object3D} object - The 3D object.
  19425. * @param {Material} material - The 3D object's material.
  19426. * @param {Scene} scene - The scene the 3D object belongs to.
  19427. * @param {Camera} camera - The camera the 3D object should be rendered with.
  19428. * @param {LightsNode} lightsNode - The lights node.
  19429. * @param {RenderContext} renderContext - The render context.
  19430. * @param {ClippingContext} clippingContext - The clipping context.
  19431. * @param {string} [passId] - An optional ID for identifying the pass.
  19432. * @return {RenderObject} The render object.
  19433. */
  19434. get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  19435. const chainMap = this.getChainMap( passId );
  19436. // reuse chainArray
  19437. _chainKeys$5[ 0 ] = object;
  19438. _chainKeys$5[ 1 ] = material;
  19439. _chainKeys$5[ 2 ] = renderContext;
  19440. _chainKeys$5[ 3 ] = lightsNode;
  19441. let renderObject = chainMap.get( _chainKeys$5 );
  19442. if ( renderObject === undefined ) {
  19443. renderObject = this.createRenderObject( this.nodes, this.geometries, this.renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  19444. chainMap.set( _chainKeys$5, renderObject );
  19445. } else {
  19446. renderObject.updateClipping( clippingContext );
  19447. if ( renderObject.needsGeometryUpdate ) {
  19448. renderObject.setGeometry( object.geometry );
  19449. }
  19450. if ( renderObject.version !== material.version || renderObject.needsUpdate ) {
  19451. if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) {
  19452. renderObject.dispose();
  19453. renderObject = this.get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  19454. } else {
  19455. renderObject.version = material.version;
  19456. }
  19457. }
  19458. }
  19459. _chainKeys$5.length = 0;
  19460. return renderObject;
  19461. }
  19462. /**
  19463. * Returns a chain map for the given pass ID.
  19464. *
  19465. * @param {string} [passId='default'] - The pass ID.
  19466. * @return {ChainMap} The chain map.
  19467. */
  19468. getChainMap( passId = 'default' ) {
  19469. return this.chainMaps[ passId ] || ( this.chainMaps[ passId ] = new ChainMap() );
  19470. }
  19471. /**
  19472. * Frees internal resources.
  19473. */
  19474. dispose() {
  19475. this.chainMaps = {};
  19476. }
  19477. /**
  19478. * Factory method for creating render objects with the given list of parameters.
  19479. *
  19480. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  19481. * @param {Geometries} geometries - Renderer component for managing geometries.
  19482. * @param {Renderer} renderer - The renderer.
  19483. * @param {Object3D} object - The 3D object.
  19484. * @param {Material} material - The object's material.
  19485. * @param {Scene} scene - The scene the 3D object belongs to.
  19486. * @param {Camera} camera - The camera the object should be rendered with.
  19487. * @param {LightsNode} lightsNode - The lights node.
  19488. * @param {RenderContext} renderContext - The render context.
  19489. * @param {ClippingContext} clippingContext - The clipping context.
  19490. * @param {string} [passId] - An optional ID for identifying the pass.
  19491. * @return {RenderObject} The render object.
  19492. */
  19493. createRenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  19494. const chainMap = this.getChainMap( passId );
  19495. const renderObject = new RenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext );
  19496. renderObject.onDispose = () => {
  19497. this.pipelines.delete( renderObject );
  19498. this.bindings.delete( renderObject );
  19499. this.nodes.delete( renderObject );
  19500. chainMap.delete( renderObject.getChainArray() );
  19501. };
  19502. return renderObject;
  19503. }
  19504. }
  19505. /**
  19506. * Data structure for the renderer. It is intended to manage
  19507. * data of objects in dictionaries.
  19508. *
  19509. * @private
  19510. */
  19511. class DataMap {
  19512. /**
  19513. * Constructs a new data map.
  19514. */
  19515. constructor() {
  19516. /**
  19517. * `DataMap` internally uses a weak map
  19518. * to manage its data.
  19519. *
  19520. * @type {WeakMap}
  19521. */
  19522. this.data = new WeakMap();
  19523. }
  19524. /**
  19525. * Returns the dictionary for the given object.
  19526. *
  19527. * @param {Object} object - The object.
  19528. * @return {Object} The dictionary.
  19529. */
  19530. get( object ) {
  19531. let map = this.data.get( object );
  19532. if ( map === undefined ) {
  19533. map = {};
  19534. this.data.set( object, map );
  19535. }
  19536. return map;
  19537. }
  19538. /**
  19539. * Deletes the dictionary for the given object.
  19540. *
  19541. * @param {Object} object - The object.
  19542. * @return {?Object} The deleted dictionary.
  19543. */
  19544. delete( object ) {
  19545. let map = null;
  19546. if ( this.data.has( object ) ) {
  19547. map = this.data.get( object );
  19548. this.data.delete( object );
  19549. }
  19550. return map;
  19551. }
  19552. /**
  19553. * Returns `true` if the given object has a dictionary defined.
  19554. *
  19555. * @param {Object} object - The object to test.
  19556. * @return {boolean} Whether a dictionary is defined or not.
  19557. */
  19558. has( object ) {
  19559. return this.data.has( object );
  19560. }
  19561. /**
  19562. * Frees internal resources.
  19563. */
  19564. dispose() {
  19565. this.data = new WeakMap();
  19566. }
  19567. }
  19568. const AttributeType = {
  19569. VERTEX: 1,
  19570. INDEX: 2,
  19571. STORAGE: 3,
  19572. INDIRECT: 4
  19573. };
  19574. // size of a chunk in bytes (STD140 layout)
  19575. const GPU_CHUNK_BYTES = 16;
  19576. // @TODO: Move to src/constants.js
  19577. const BlendColorFactor = 211;
  19578. const OneMinusBlendColorFactor = 212;
  19579. /**
  19580. * This renderer module manages geometry attributes.
  19581. *
  19582. * @private
  19583. * @augments DataMap
  19584. */
  19585. class Attributes extends DataMap {
  19586. /**
  19587. * Constructs a new attribute management component.
  19588. *
  19589. * @param {Backend} backend - The renderer's backend.
  19590. */
  19591. constructor( backend ) {
  19592. super();
  19593. /**
  19594. * The renderer's backend.
  19595. *
  19596. * @type {Backend}
  19597. */
  19598. this.backend = backend;
  19599. }
  19600. /**
  19601. * Deletes the data for the given attribute.
  19602. *
  19603. * @param {BufferAttribute} attribute - The attribute.
  19604. * @return {Object|null} The deleted attribute data.
  19605. */
  19606. delete( attribute ) {
  19607. const attributeData = super.delete( attribute );
  19608. if ( attributeData !== null ) {
  19609. this.backend.destroyAttribute( attribute );
  19610. }
  19611. return attributeData;
  19612. }
  19613. /**
  19614. * Updates the given attribute. This method creates attribute buffers
  19615. * for new attributes and updates data for existing ones.
  19616. *
  19617. * @param {BufferAttribute} attribute - The attribute to update.
  19618. * @param {number} type - The attribute type.
  19619. */
  19620. update( attribute, type ) {
  19621. const data = this.get( attribute );
  19622. if ( data.version === undefined ) {
  19623. if ( type === AttributeType.VERTEX ) {
  19624. this.backend.createAttribute( attribute );
  19625. } else if ( type === AttributeType.INDEX ) {
  19626. this.backend.createIndexAttribute( attribute );
  19627. } else if ( type === AttributeType.STORAGE ) {
  19628. this.backend.createStorageAttribute( attribute );
  19629. } else if ( type === AttributeType.INDIRECT ) {
  19630. this.backend.createIndirectStorageAttribute( attribute );
  19631. }
  19632. data.version = this._getBufferAttribute( attribute ).version;
  19633. } else {
  19634. const bufferAttribute = this._getBufferAttribute( attribute );
  19635. if ( data.version < bufferAttribute.version || bufferAttribute.usage === DynamicDrawUsage ) {
  19636. this.backend.updateAttribute( attribute );
  19637. data.version = bufferAttribute.version;
  19638. }
  19639. }
  19640. }
  19641. /**
  19642. * Utility method for handling interleaved buffer attributes correctly.
  19643. * To process them, their `InterleavedBuffer` is returned.
  19644. *
  19645. * @param {BufferAttribute} attribute - The attribute.
  19646. * @return {BufferAttribute|InterleavedBuffer}
  19647. */
  19648. _getBufferAttribute( attribute ) {
  19649. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  19650. return attribute;
  19651. }
  19652. }
  19653. /**
  19654. * Returns the wireframe version for the given geometry.
  19655. *
  19656. * @private
  19657. * @function
  19658. * @param {BufferGeometry} geometry - The geometry.
  19659. * @return {number} The version.
  19660. */
  19661. function getWireframeVersion( geometry ) {
  19662. return ( geometry.index !== null ) ? geometry.index.version : geometry.attributes.position.version;
  19663. }
  19664. /**
  19665. * Returns a wireframe index attribute for the given geometry.
  19666. *
  19667. * @private
  19668. * @function
  19669. * @param {BufferGeometry} geometry - The geometry.
  19670. * @return {BufferAttribute} The wireframe index attribute.
  19671. */
  19672. function getWireframeIndex( geometry ) {
  19673. const indices = [];
  19674. const geometryIndex = geometry.index;
  19675. const geometryPosition = geometry.attributes.position;
  19676. if ( geometryIndex !== null ) {
  19677. const array = geometryIndex.array;
  19678. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  19679. const a = array[ i + 0 ];
  19680. const b = array[ i + 1 ];
  19681. const c = array[ i + 2 ];
  19682. indices.push( a, b, b, c, c, a );
  19683. }
  19684. } else {
  19685. const array = geometryPosition.array;
  19686. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  19687. const a = i + 0;
  19688. const b = i + 1;
  19689. const c = i + 2;
  19690. indices.push( a, b, b, c, c, a );
  19691. }
  19692. }
  19693. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  19694. attribute.version = getWireframeVersion( geometry );
  19695. return attribute;
  19696. }
  19697. /**
  19698. * This renderer module manages geometries.
  19699. *
  19700. * @private
  19701. * @augments DataMap
  19702. */
  19703. class Geometries extends DataMap {
  19704. /**
  19705. * Constructs a new geometry management component.
  19706. *
  19707. * @param {Attributes} attributes - Renderer component for managing attributes.
  19708. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  19709. */
  19710. constructor( attributes, info ) {
  19711. super();
  19712. /**
  19713. * Renderer component for managing attributes.
  19714. *
  19715. * @type {Attributes}
  19716. */
  19717. this.attributes = attributes;
  19718. /**
  19719. * Renderer component for managing metrics and monitoring data.
  19720. *
  19721. * @type {Info}
  19722. */
  19723. this.info = info;
  19724. /**
  19725. * Weak Map for managing attributes for wireframe rendering.
  19726. *
  19727. * @type {WeakMap<BufferGeometry,BufferAttribute>}
  19728. */
  19729. this.wireframes = new WeakMap();
  19730. /**
  19731. * This Weak Map is used to make sure buffer attributes are
  19732. * updated only once per render call.
  19733. *
  19734. * @type {WeakMap<BufferAttribute,number>}
  19735. */
  19736. this.attributeCall = new WeakMap();
  19737. }
  19738. /**
  19739. * Returns `true` if the given render object has an initialized geometry.
  19740. *
  19741. * @param {RenderObject} renderObject - The render object.
  19742. * @return {boolean} Whether if the given render object has an initialized geometry or not.
  19743. */
  19744. has( renderObject ) {
  19745. const geometry = renderObject.geometry;
  19746. return super.has( geometry ) && this.get( geometry ).initialized === true;
  19747. }
  19748. /**
  19749. * Prepares the geometry of the given render object for rendering.
  19750. *
  19751. * @param {RenderObject} renderObject - The render object.
  19752. */
  19753. updateForRender( renderObject ) {
  19754. if ( this.has( renderObject ) === false ) this.initGeometry( renderObject );
  19755. this.updateAttributes( renderObject );
  19756. }
  19757. /**
  19758. * Initializes the geometry of the given render object.
  19759. *
  19760. * @param {RenderObject} renderObject - The render object.
  19761. */
  19762. initGeometry( renderObject ) {
  19763. const geometry = renderObject.geometry;
  19764. const geometryData = this.get( geometry );
  19765. geometryData.initialized = true;
  19766. this.info.memory.geometries ++;
  19767. const onDispose = () => {
  19768. this.info.memory.geometries --;
  19769. const index = geometry.index;
  19770. const geometryAttributes = renderObject.getAttributes();
  19771. if ( index !== null ) {
  19772. this.attributes.delete( index );
  19773. }
  19774. for ( const geometryAttribute of geometryAttributes ) {
  19775. this.attributes.delete( geometryAttribute );
  19776. }
  19777. const wireframeAttribute = this.wireframes.get( geometry );
  19778. if ( wireframeAttribute !== undefined ) {
  19779. this.attributes.delete( wireframeAttribute );
  19780. }
  19781. geometry.removeEventListener( 'dispose', onDispose );
  19782. };
  19783. geometry.addEventListener( 'dispose', onDispose );
  19784. }
  19785. /**
  19786. * Updates the geometry attributes of the given render object.
  19787. *
  19788. * @param {RenderObject} renderObject - The render object.
  19789. */
  19790. updateAttributes( renderObject ) {
  19791. // attributes
  19792. const attributes = renderObject.getAttributes();
  19793. for ( const attribute of attributes ) {
  19794. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  19795. this.updateAttribute( attribute, AttributeType.STORAGE );
  19796. } else {
  19797. this.updateAttribute( attribute, AttributeType.VERTEX );
  19798. }
  19799. }
  19800. // indexes
  19801. const index = this.getIndex( renderObject );
  19802. if ( index !== null ) {
  19803. this.updateAttribute( index, AttributeType.INDEX );
  19804. }
  19805. // indirect
  19806. const indirect = renderObject.geometry.indirect;
  19807. if ( indirect !== null ) {
  19808. this.updateAttribute( indirect, AttributeType.INDIRECT );
  19809. }
  19810. }
  19811. /**
  19812. * Updates the given attribute.
  19813. *
  19814. * @param {BufferAttribute} attribute - The attribute to update.
  19815. * @param {number} type - The attribute type.
  19816. */
  19817. updateAttribute( attribute, type ) {
  19818. const callId = this.info.render.calls;
  19819. if ( ! attribute.isInterleavedBufferAttribute ) {
  19820. if ( this.attributeCall.get( attribute ) !== callId ) {
  19821. this.attributes.update( attribute, type );
  19822. this.attributeCall.set( attribute, callId );
  19823. }
  19824. } else {
  19825. if ( this.attributeCall.get( attribute ) === undefined ) {
  19826. this.attributes.update( attribute, type );
  19827. this.attributeCall.set( attribute, callId );
  19828. } else if ( this.attributeCall.get( attribute.data ) !== callId ) {
  19829. this.attributes.update( attribute, type );
  19830. this.attributeCall.set( attribute.data, callId );
  19831. this.attributeCall.set( attribute, callId );
  19832. }
  19833. }
  19834. }
  19835. /**
  19836. * Returns the indirect buffer attribute of the given render object.
  19837. *
  19838. * @param {RenderObject} renderObject - The render object.
  19839. * @return {?BufferAttribute} The indirect attribute. `null` if no indirect drawing is used.
  19840. */
  19841. getIndirect( renderObject ) {
  19842. return renderObject.geometry.indirect;
  19843. }
  19844. /**
  19845. * Returns the index of the given render object's geometry. This is implemented
  19846. * in a method to return a wireframe index if necessary.
  19847. *
  19848. * @param {RenderObject} renderObject - The render object.
  19849. * @return {?BufferAttribute} The index. Returns `null` for non-indexed geometries.
  19850. */
  19851. getIndex( renderObject ) {
  19852. const { geometry, material } = renderObject;
  19853. let index = geometry.index;
  19854. if ( material.wireframe === true ) {
  19855. const wireframes = this.wireframes;
  19856. let wireframeAttribute = wireframes.get( geometry );
  19857. if ( wireframeAttribute === undefined ) {
  19858. wireframeAttribute = getWireframeIndex( geometry );
  19859. wireframes.set( geometry, wireframeAttribute );
  19860. } else if ( wireframeAttribute.version !== getWireframeVersion( geometry ) ) {
  19861. this.attributes.delete( wireframeAttribute );
  19862. wireframeAttribute = getWireframeIndex( geometry );
  19863. wireframes.set( geometry, wireframeAttribute );
  19864. }
  19865. index = wireframeAttribute;
  19866. }
  19867. return index;
  19868. }
  19869. }
  19870. /**
  19871. * This renderer module provides a series of statistical information
  19872. * about the GPU memory and the rendering process. Useful for debugging
  19873. * and monitoring.
  19874. */
  19875. class Info {
  19876. /**
  19877. * Constructs a new info component.
  19878. */
  19879. constructor() {
  19880. /**
  19881. * Whether frame related metrics should automatically
  19882. * be resetted or not. This property should be set to `false`
  19883. * by apps which manage their own animation loop. They must
  19884. * then call `renderer.info.reset()` once per frame manually.
  19885. *
  19886. * @type {boolean}
  19887. * @default true
  19888. */
  19889. this.autoReset = true;
  19890. /**
  19891. * The current frame ID. This ID is managed
  19892. * by `NodeFrame`.
  19893. *
  19894. * @type {number}
  19895. * @readonly
  19896. * @default 0
  19897. */
  19898. this.frame = 0;
  19899. /**
  19900. * The number of render calls since the
  19901. * app has been started.
  19902. *
  19903. * @type {number}
  19904. * @readonly
  19905. * @default 0
  19906. */
  19907. this.calls = 0;
  19908. /**
  19909. * Render related metrics.
  19910. *
  19911. * @type {Object}
  19912. * @readonly
  19913. * @property {number} calls - The number of render calls since the app has been started.
  19914. * @property {number} frameCalls - The number of render calls of the current frame.
  19915. * @property {number} drawCalls - The number of draw calls of the current frame.
  19916. * @property {number} triangles - The number of rendered triangle primitives of the current frame.
  19917. * @property {number} points - The number of rendered point primitives of the current frame.
  19918. * @property {number} lines - The number of rendered line primitives of the current frame.
  19919. * @property {number} timestamp - The timestamp of the frame when using `renderer.renderAsync()`.
  19920. */
  19921. this.render = {
  19922. calls: 0,
  19923. frameCalls: 0,
  19924. drawCalls: 0,
  19925. triangles: 0,
  19926. points: 0,
  19927. lines: 0,
  19928. timestamp: 0,
  19929. };
  19930. /**
  19931. * Compute related metrics.
  19932. *
  19933. * @type {Object}
  19934. * @readonly
  19935. * @property {number} calls - The number of compute calls since the app has been started.
  19936. * @property {number} frameCalls - The number of compute calls of the current frame.
  19937. * @property {number} timestamp - The timestamp of the frame when using `renderer.computeAsync()`.
  19938. */
  19939. this.compute = {
  19940. calls: 0,
  19941. frameCalls: 0,
  19942. timestamp: 0
  19943. };
  19944. /**
  19945. * Memory related metrics.
  19946. *
  19947. * @type {Object}
  19948. * @readonly
  19949. * @property {number} geometries - The number of active geometries.
  19950. * @property {number} frameCalls - The number of active textures.
  19951. */
  19952. this.memory = {
  19953. geometries: 0,
  19954. textures: 0
  19955. };
  19956. }
  19957. /**
  19958. * This method should be executed per draw call and updates the corresponding metrics.
  19959. *
  19960. * @param {Object3D} object - The 3D object that is going to be rendered.
  19961. * @param {number} count - The vertex or index count.
  19962. * @param {number} instanceCount - The instance count.
  19963. */
  19964. update( object, count, instanceCount ) {
  19965. this.render.drawCalls ++;
  19966. if ( object.isMesh || object.isSprite ) {
  19967. this.render.triangles += instanceCount * ( count / 3 );
  19968. } else if ( object.isPoints ) {
  19969. this.render.points += instanceCount * count;
  19970. } else if ( object.isLineSegments ) {
  19971. this.render.lines += instanceCount * ( count / 2 );
  19972. } else if ( object.isLine ) {
  19973. this.render.lines += instanceCount * ( count - 1 );
  19974. } else {
  19975. console.error( 'THREE.WebGPUInfo: Unknown object type.' );
  19976. }
  19977. }
  19978. /**
  19979. * Resets frame related metrics.
  19980. */
  19981. reset() {
  19982. this.render.drawCalls = 0;
  19983. this.render.frameCalls = 0;
  19984. this.compute.frameCalls = 0;
  19985. this.render.triangles = 0;
  19986. this.render.points = 0;
  19987. this.render.lines = 0;
  19988. }
  19989. /**
  19990. * Performs a complete reset of the object.
  19991. */
  19992. dispose() {
  19993. this.reset();
  19994. this.calls = 0;
  19995. this.render.calls = 0;
  19996. this.compute.calls = 0;
  19997. this.render.timestamp = 0;
  19998. this.compute.timestamp = 0;
  19999. this.memory.geometries = 0;
  20000. this.memory.textures = 0;
  20001. }
  20002. }
  20003. /**
  20004. * Abstract class for representing pipelines.
  20005. *
  20006. * @private
  20007. * @abstract
  20008. */
  20009. class Pipeline {
  20010. /**
  20011. * Constructs a new pipeline.
  20012. *
  20013. * @param {string} cacheKey - The pipeline's cache key.
  20014. */
  20015. constructor( cacheKey ) {
  20016. /**
  20017. * The pipeline's cache key.
  20018. *
  20019. * @type {string}
  20020. */
  20021. this.cacheKey = cacheKey;
  20022. /**
  20023. * How often the pipeline is currently in use.
  20024. *
  20025. * @type {number}
  20026. * @default 0
  20027. */
  20028. this.usedTimes = 0;
  20029. }
  20030. }
  20031. /**
  20032. * Class for representing render pipelines.
  20033. *
  20034. * @private
  20035. * @augments Pipeline
  20036. */
  20037. class RenderPipeline extends Pipeline {
  20038. /**
  20039. * Constructs a new render pipeline.
  20040. *
  20041. * @param {string} cacheKey - The pipeline's cache key.
  20042. * @param {ProgrammableStage} vertexProgram - The pipeline's vertex shader.
  20043. * @param {ProgrammableStage} fragmentProgram - The pipeline's fragment shader.
  20044. */
  20045. constructor( cacheKey, vertexProgram, fragmentProgram ) {
  20046. super( cacheKey );
  20047. /**
  20048. * The pipeline's vertex shader.
  20049. *
  20050. * @type {ProgrammableStage}
  20051. */
  20052. this.vertexProgram = vertexProgram;
  20053. /**
  20054. * The pipeline's fragment shader.
  20055. *
  20056. * @type {ProgrammableStage}
  20057. */
  20058. this.fragmentProgram = fragmentProgram;
  20059. }
  20060. }
  20061. /**
  20062. * Class for representing compute pipelines.
  20063. *
  20064. * @private
  20065. * @augments Pipeline
  20066. */
  20067. class ComputePipeline extends Pipeline {
  20068. /**
  20069. * Constructs a new render pipeline.
  20070. *
  20071. * @param {string} cacheKey - The pipeline's cache key.
  20072. * @param {ProgrammableStage} computeProgram - The pipeline's compute shader.
  20073. */
  20074. constructor( cacheKey, computeProgram ) {
  20075. super( cacheKey );
  20076. /**
  20077. * The pipeline's compute shader.
  20078. *
  20079. * @type {ProgrammableStage}
  20080. */
  20081. this.computeProgram = computeProgram;
  20082. /**
  20083. * This flag can be used for type testing.
  20084. *
  20085. * @type {boolean}
  20086. * @readonly
  20087. * @default true
  20088. */
  20089. this.isComputePipeline = true;
  20090. }
  20091. }
  20092. let _id$8 = 0;
  20093. /**
  20094. * Class for representing programmable stages which are vertex,
  20095. * fragment or compute shaders. Unlike fixed-function states (like blending),
  20096. * they represent the programmable part of a pipeline.
  20097. *
  20098. * @private
  20099. */
  20100. class ProgrammableStage {
  20101. /**
  20102. * Constructs a new programmable stage.
  20103. *
  20104. * @param {string} code - The shader code.
  20105. * @param {('vertex'|'fragment'|'compute')} stage - The type of stage.
  20106. * @param {string} name - The name of the shader.
  20107. * @param {?Array<Object>} [transforms=null] - The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  20108. * @param {?Array<Object>} [attributes=null] - The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  20109. */
  20110. constructor( code, stage, name, transforms = null, attributes = null ) {
  20111. /**
  20112. * The id of the programmable stage.
  20113. *
  20114. * @type {number}
  20115. */
  20116. this.id = _id$8 ++;
  20117. /**
  20118. * The shader code.
  20119. *
  20120. * @type {string}
  20121. */
  20122. this.code = code;
  20123. /**
  20124. * The type of stage.
  20125. *
  20126. * @type {string}
  20127. */
  20128. this.stage = stage;
  20129. /**
  20130. * The name of the stage.
  20131. * This is used for debugging purposes.
  20132. *
  20133. * @type {string}
  20134. */
  20135. this.name = name;
  20136. /**
  20137. * The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  20138. *
  20139. * @type {?Array<Object>}
  20140. */
  20141. this.transforms = transforms;
  20142. /**
  20143. * The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  20144. *
  20145. * @type {?Array<Object>}
  20146. */
  20147. this.attributes = attributes;
  20148. /**
  20149. * How often the programmable stage is currently in use.
  20150. *
  20151. * @type {number}
  20152. * @default 0
  20153. */
  20154. this.usedTimes = 0;
  20155. }
  20156. }
  20157. /**
  20158. * This renderer module manages the pipelines of the renderer.
  20159. *
  20160. * @private
  20161. * @augments DataMap
  20162. */
  20163. class Pipelines extends DataMap {
  20164. /**
  20165. * Constructs a new pipeline management component.
  20166. *
  20167. * @param {Backend} backend - The renderer's backend.
  20168. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  20169. */
  20170. constructor( backend, nodes ) {
  20171. super();
  20172. /**
  20173. * The renderer's backend.
  20174. *
  20175. * @type {Backend}
  20176. */
  20177. this.backend = backend;
  20178. /**
  20179. * Renderer component for managing nodes related logic.
  20180. *
  20181. * @type {Nodes}
  20182. */
  20183. this.nodes = nodes;
  20184. /**
  20185. * A references to the bindings management component.
  20186. * This reference will be set inside the `Bindings`
  20187. * constructor.
  20188. *
  20189. * @type {?Bindings}
  20190. * @default null
  20191. */
  20192. this.bindings = null;
  20193. /**
  20194. * Internal cache for maintaining pipelines.
  20195. * The key of the map is a cache key, the value the pipeline.
  20196. *
  20197. * @type {Map<string,Pipeline>}
  20198. */
  20199. this.caches = new Map();
  20200. /**
  20201. * This dictionary maintains for each shader stage type (vertex,
  20202. * fragment and compute) the programmable stage objects which
  20203. * represent the actual shader code.
  20204. *
  20205. * @type {Object<string,Map>}
  20206. */
  20207. this.programs = {
  20208. vertex: new Map(),
  20209. fragment: new Map(),
  20210. compute: new Map()
  20211. };
  20212. }
  20213. /**
  20214. * Returns a compute pipeline for the given compute node.
  20215. *
  20216. * @param {Node} computeNode - The compute node.
  20217. * @param {Array<BindGroup>} bindings - The bindings.
  20218. * @return {ComputePipeline} The compute pipeline.
  20219. */
  20220. getForCompute( computeNode, bindings ) {
  20221. const { backend } = this;
  20222. const data = this.get( computeNode );
  20223. if ( this._needsComputeUpdate( computeNode ) ) {
  20224. const previousPipeline = data.pipeline;
  20225. if ( previousPipeline ) {
  20226. previousPipeline.usedTimes --;
  20227. previousPipeline.computeProgram.usedTimes --;
  20228. }
  20229. // get shader
  20230. const nodeBuilderState = this.nodes.getForCompute( computeNode );
  20231. // programmable stage
  20232. let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader );
  20233. if ( stageCompute === undefined ) {
  20234. if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram );
  20235. stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', computeNode.name, nodeBuilderState.transforms, nodeBuilderState.nodeAttributes );
  20236. this.programs.compute.set( nodeBuilderState.computeShader, stageCompute );
  20237. backend.createProgram( stageCompute );
  20238. }
  20239. // determine compute pipeline
  20240. const cacheKey = this._getComputeCacheKey( computeNode, stageCompute );
  20241. let pipeline = this.caches.get( cacheKey );
  20242. if ( pipeline === undefined ) {
  20243. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  20244. pipeline = this._getComputePipeline( computeNode, stageCompute, cacheKey, bindings );
  20245. }
  20246. // keep track of all used times
  20247. pipeline.usedTimes ++;
  20248. stageCompute.usedTimes ++;
  20249. //
  20250. data.version = computeNode.version;
  20251. data.pipeline = pipeline;
  20252. }
  20253. return data.pipeline;
  20254. }
  20255. /**
  20256. * Returns a render pipeline for the given render object.
  20257. *
  20258. * @param {RenderObject} renderObject - The render object.
  20259. * @param {?Array<Promise>} [promises=null] - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  20260. * @return {RenderPipeline} The render pipeline.
  20261. */
  20262. getForRender( renderObject, promises = null ) {
  20263. const { backend } = this;
  20264. const data = this.get( renderObject );
  20265. if ( this._needsRenderUpdate( renderObject ) ) {
  20266. const previousPipeline = data.pipeline;
  20267. if ( previousPipeline ) {
  20268. previousPipeline.usedTimes --;
  20269. previousPipeline.vertexProgram.usedTimes --;
  20270. previousPipeline.fragmentProgram.usedTimes --;
  20271. }
  20272. // get shader
  20273. const nodeBuilderState = renderObject.getNodeBuilderState();
  20274. const name = renderObject.material ? renderObject.material.name : '';
  20275. // programmable stages
  20276. let stageVertex = this.programs.vertex.get( nodeBuilderState.vertexShader );
  20277. if ( stageVertex === undefined ) {
  20278. if ( previousPipeline && previousPipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.vertexProgram );
  20279. stageVertex = new ProgrammableStage( nodeBuilderState.vertexShader, 'vertex', name );
  20280. this.programs.vertex.set( nodeBuilderState.vertexShader, stageVertex );
  20281. backend.createProgram( stageVertex );
  20282. }
  20283. let stageFragment = this.programs.fragment.get( nodeBuilderState.fragmentShader );
  20284. if ( stageFragment === undefined ) {
  20285. if ( previousPipeline && previousPipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.fragmentProgram );
  20286. stageFragment = new ProgrammableStage( nodeBuilderState.fragmentShader, 'fragment', name );
  20287. this.programs.fragment.set( nodeBuilderState.fragmentShader, stageFragment );
  20288. backend.createProgram( stageFragment );
  20289. }
  20290. // determine render pipeline
  20291. const cacheKey = this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  20292. let pipeline = this.caches.get( cacheKey );
  20293. if ( pipeline === undefined ) {
  20294. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  20295. pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises );
  20296. } else {
  20297. renderObject.pipeline = pipeline;
  20298. }
  20299. // keep track of all used times
  20300. pipeline.usedTimes ++;
  20301. stageVertex.usedTimes ++;
  20302. stageFragment.usedTimes ++;
  20303. //
  20304. data.pipeline = pipeline;
  20305. }
  20306. return data.pipeline;
  20307. }
  20308. /**
  20309. * Deletes the pipeline for the given render object.
  20310. *
  20311. * @param {RenderObject} object - The render object.
  20312. * @return {?Object} The deleted dictionary.
  20313. */
  20314. delete( object ) {
  20315. const pipeline = this.get( object ).pipeline;
  20316. if ( pipeline ) {
  20317. // pipeline
  20318. pipeline.usedTimes --;
  20319. if ( pipeline.usedTimes === 0 ) this._releasePipeline( pipeline );
  20320. // programs
  20321. if ( pipeline.isComputePipeline ) {
  20322. pipeline.computeProgram.usedTimes --;
  20323. if ( pipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( pipeline.computeProgram );
  20324. } else {
  20325. pipeline.fragmentProgram.usedTimes --;
  20326. pipeline.vertexProgram.usedTimes --;
  20327. if ( pipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( pipeline.vertexProgram );
  20328. if ( pipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( pipeline.fragmentProgram );
  20329. }
  20330. }
  20331. return super.delete( object );
  20332. }
  20333. /**
  20334. * Frees internal resources.
  20335. */
  20336. dispose() {
  20337. super.dispose();
  20338. this.caches = new Map();
  20339. this.programs = {
  20340. vertex: new Map(),
  20341. fragment: new Map(),
  20342. compute: new Map()
  20343. };
  20344. }
  20345. /**
  20346. * Updates the pipeline for the given render object.
  20347. *
  20348. * @param {RenderObject} renderObject - The render object.
  20349. */
  20350. updateForRender( renderObject ) {
  20351. this.getForRender( renderObject );
  20352. }
  20353. /**
  20354. * Returns a compute pipeline for the given parameters.
  20355. *
  20356. * @private
  20357. * @param {Node} computeNode - The compute node.
  20358. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  20359. * @param {string} cacheKey - The cache key.
  20360. * @param {Array<BindGroup>} bindings - The bindings.
  20361. * @return {ComputePipeline} The compute pipeline.
  20362. */
  20363. _getComputePipeline( computeNode, stageCompute, cacheKey, bindings ) {
  20364. // check for existing pipeline
  20365. cacheKey = cacheKey || this._getComputeCacheKey( computeNode, stageCompute );
  20366. let pipeline = this.caches.get( cacheKey );
  20367. if ( pipeline === undefined ) {
  20368. pipeline = new ComputePipeline( cacheKey, stageCompute );
  20369. this.caches.set( cacheKey, pipeline );
  20370. this.backend.createComputePipeline( pipeline, bindings );
  20371. }
  20372. return pipeline;
  20373. }
  20374. /**
  20375. * Returns a render pipeline for the given parameters.
  20376. *
  20377. * @private
  20378. * @param {RenderObject} renderObject - The render object.
  20379. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  20380. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  20381. * @param {string} cacheKey - The cache key.
  20382. * @param {?Array<Promise>} promises - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  20383. * @return {ComputePipeline} The compute pipeline.
  20384. */
  20385. _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) {
  20386. // check for existing pipeline
  20387. cacheKey = cacheKey || this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  20388. let pipeline = this.caches.get( cacheKey );
  20389. if ( pipeline === undefined ) {
  20390. pipeline = new RenderPipeline( cacheKey, stageVertex, stageFragment );
  20391. this.caches.set( cacheKey, pipeline );
  20392. renderObject.pipeline = pipeline;
  20393. // The `promises` array is `null` by default and only set to an empty array when
  20394. // `Renderer.compileAsync()` is used. The next call actually fills the array with
  20395. // pending promises that resolve when the render pipelines are ready for rendering.
  20396. this.backend.createRenderPipeline( renderObject, promises );
  20397. }
  20398. return pipeline;
  20399. }
  20400. /**
  20401. * Computes a cache key representing a compute pipeline.
  20402. *
  20403. * @private
  20404. * @param {Node} computeNode - The compute node.
  20405. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  20406. * @return {string} The cache key.
  20407. */
  20408. _getComputeCacheKey( computeNode, stageCompute ) {
  20409. return computeNode.id + ',' + stageCompute.id;
  20410. }
  20411. /**
  20412. * Computes a cache key representing a render pipeline.
  20413. *
  20414. * @private
  20415. * @param {RenderObject} renderObject - The render object.
  20416. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  20417. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  20418. * @return {string} The cache key.
  20419. */
  20420. _getRenderCacheKey( renderObject, stageVertex, stageFragment ) {
  20421. return stageVertex.id + ',' + stageFragment.id + ',' + this.backend.getRenderCacheKey( renderObject );
  20422. }
  20423. /**
  20424. * Releases the given pipeline.
  20425. *
  20426. * @private
  20427. * @param {Pipeline} pipeline - The pipeline to release.
  20428. */
  20429. _releasePipeline( pipeline ) {
  20430. this.caches.delete( pipeline.cacheKey );
  20431. }
  20432. /**
  20433. * Releases the shader program.
  20434. *
  20435. * @private
  20436. * @param {Object} program - The shader program to release.
  20437. */
  20438. _releaseProgram( program ) {
  20439. const code = program.code;
  20440. const stage = program.stage;
  20441. this.programs[ stage ].delete( code );
  20442. }
  20443. /**
  20444. * Returns `true` if the compute pipeline for the given compute node requires an update.
  20445. *
  20446. * @private
  20447. * @param {Node} computeNode - The compute node.
  20448. * @return {boolean} Whether the compute pipeline for the given compute node requires an update or not.
  20449. */
  20450. _needsComputeUpdate( computeNode ) {
  20451. const data = this.get( computeNode );
  20452. return data.pipeline === undefined || data.version !== computeNode.version;
  20453. }
  20454. /**
  20455. * Returns `true` if the render pipeline for the given render object requires an update.
  20456. *
  20457. * @private
  20458. * @param {RenderObject} renderObject - The render object.
  20459. * @return {boolean} Whether the render object for the given render object requires an update or not.
  20460. */
  20461. _needsRenderUpdate( renderObject ) {
  20462. const data = this.get( renderObject );
  20463. return data.pipeline === undefined || this.backend.needsRenderUpdate( renderObject );
  20464. }
  20465. }
  20466. /**
  20467. * This renderer module manages the bindings of the renderer.
  20468. *
  20469. * @private
  20470. * @augments DataMap
  20471. */
  20472. class Bindings extends DataMap {
  20473. /**
  20474. * Constructs a new bindings management component.
  20475. *
  20476. * @param {Backend} backend - The renderer's backend.
  20477. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  20478. * @param {Textures} textures - Renderer component for managing textures.
  20479. * @param {Attributes} attributes - Renderer component for managing attributes.
  20480. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  20481. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  20482. */
  20483. constructor( backend, nodes, textures, attributes, pipelines, info ) {
  20484. super();
  20485. /**
  20486. * The renderer's backend.
  20487. *
  20488. * @type {Backend}
  20489. */
  20490. this.backend = backend;
  20491. /**
  20492. * Renderer component for managing textures.
  20493. *
  20494. * @type {Textures}
  20495. */
  20496. this.textures = textures;
  20497. /**
  20498. * Renderer component for managing pipelines.
  20499. *
  20500. * @type {Pipelines}
  20501. */
  20502. this.pipelines = pipelines;
  20503. /**
  20504. * Renderer component for managing attributes.
  20505. *
  20506. * @type {Attributes}
  20507. */
  20508. this.attributes = attributes;
  20509. /**
  20510. * Renderer component for managing nodes related logic.
  20511. *
  20512. * @type {Nodes}
  20513. */
  20514. this.nodes = nodes;
  20515. /**
  20516. * Renderer component for managing metrics and monitoring data.
  20517. *
  20518. * @type {Info}
  20519. */
  20520. this.info = info;
  20521. this.pipelines.bindings = this; // assign bindings to pipelines
  20522. }
  20523. /**
  20524. * Returns the bind groups for the given render object.
  20525. *
  20526. * @param {RenderObject} renderObject - The render object.
  20527. * @return {Array<BindGroup>} The bind groups.
  20528. */
  20529. getForRender( renderObject ) {
  20530. const bindings = renderObject.getBindings();
  20531. for ( const bindGroup of bindings ) {
  20532. const groupData = this.get( bindGroup );
  20533. if ( groupData.bindGroup === undefined ) {
  20534. // each object defines an array of bindings (ubos, textures, samplers etc.)
  20535. this._init( bindGroup );
  20536. this.backend.createBindings( bindGroup, bindings, 0 );
  20537. groupData.bindGroup = bindGroup;
  20538. }
  20539. }
  20540. return bindings;
  20541. }
  20542. /**
  20543. * Returns the bind groups for the given compute node.
  20544. *
  20545. * @param {Node} computeNode - The compute node.
  20546. * @return {Array<BindGroup>} The bind groups.
  20547. */
  20548. getForCompute( computeNode ) {
  20549. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  20550. for ( const bindGroup of bindings ) {
  20551. const groupData = this.get( bindGroup );
  20552. if ( groupData.bindGroup === undefined ) {
  20553. this._init( bindGroup );
  20554. this.backend.createBindings( bindGroup, bindings, 0 );
  20555. groupData.bindGroup = bindGroup;
  20556. }
  20557. }
  20558. return bindings;
  20559. }
  20560. /**
  20561. * Updates the bindings for the given compute node.
  20562. *
  20563. * @param {Node} computeNode - The compute node.
  20564. */
  20565. updateForCompute( computeNode ) {
  20566. this._updateBindings( this.getForCompute( computeNode ) );
  20567. }
  20568. /**
  20569. * Updates the bindings for the given render object.
  20570. *
  20571. * @param {RenderObject} renderObject - The render object.
  20572. */
  20573. updateForRender( renderObject ) {
  20574. this._updateBindings( this.getForRender( renderObject ) );
  20575. }
  20576. /**
  20577. * Updates the given array of bindings.
  20578. *
  20579. * @param {Array<BindGroup>} bindings - The bind groups.
  20580. */
  20581. _updateBindings( bindings ) {
  20582. for ( const bindGroup of bindings ) {
  20583. this._update( bindGroup, bindings );
  20584. }
  20585. }
  20586. /**
  20587. * Initializes the given bind group.
  20588. *
  20589. * @param {BindGroup} bindGroup - The bind group to initialize.
  20590. */
  20591. _init( bindGroup ) {
  20592. for ( const binding of bindGroup.bindings ) {
  20593. if ( binding.isSampledTexture ) {
  20594. this.textures.updateTexture( binding.texture );
  20595. } else if ( binding.isStorageBuffer ) {
  20596. const attribute = binding.attribute;
  20597. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  20598. this.attributes.update( attribute, attributeType );
  20599. }
  20600. }
  20601. }
  20602. /**
  20603. * Updates the given bind group.
  20604. *
  20605. * @param {BindGroup} bindGroup - The bind group to update.
  20606. * @param {Array<BindGroup>} bindings - The bind groups.
  20607. */
  20608. _update( bindGroup, bindings ) {
  20609. const { backend } = this;
  20610. let needsBindingsUpdate = false;
  20611. let cacheBindings = true;
  20612. let cacheIndex = 0;
  20613. let version = 0;
  20614. // iterate over all bindings and check if buffer updates or a new binding group is required
  20615. for ( const binding of bindGroup.bindings ) {
  20616. if ( binding.isNodeUniformsGroup ) {
  20617. const updated = this.nodes.updateGroup( binding );
  20618. // every uniforms group is a uniform buffer. So if no update is required,
  20619. // we move one with the next binding. Otherwise the next if block will update the group.
  20620. if ( updated === false ) continue;
  20621. }
  20622. if ( binding.isStorageBuffer ) {
  20623. const attribute = binding.attribute;
  20624. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  20625. this.attributes.update( attribute, attributeType );
  20626. }
  20627. if ( binding.isUniformBuffer ) {
  20628. const updated = binding.update();
  20629. if ( updated ) {
  20630. backend.updateBinding( binding );
  20631. }
  20632. } else if ( binding.isSampler ) {
  20633. binding.update();
  20634. } else if ( binding.isSampledTexture ) {
  20635. const texturesTextureData = this.textures.get( binding.texture );
  20636. if ( binding.needsBindingsUpdate( texturesTextureData.generation ) ) needsBindingsUpdate = true;
  20637. const updated = binding.update();
  20638. const texture = binding.texture;
  20639. if ( updated ) {
  20640. this.textures.updateTexture( texture );
  20641. }
  20642. const textureData = backend.get( texture );
  20643. if ( textureData.externalTexture !== undefined || texturesTextureData.isDefaultTexture ) {
  20644. cacheBindings = false;
  20645. } else {
  20646. cacheIndex = cacheIndex * 10 + texture.id;
  20647. version += texture.version;
  20648. }
  20649. if ( backend.isWebGPUBackend === true && textureData.texture === undefined && textureData.externalTexture === undefined ) {
  20650. // TODO: Remove this once we found why updated === false isn't bound to a texture in the WebGPU backend
  20651. console.error( 'Bindings._update: binding should be available:', binding, updated, texture, binding.textureNode.value, needsBindingsUpdate );
  20652. this.textures.updateTexture( texture );
  20653. needsBindingsUpdate = true;
  20654. }
  20655. if ( texture.isStorageTexture === true ) {
  20656. const textureData = this.get( texture );
  20657. if ( binding.store === true ) {
  20658. textureData.needsMipmap = true;
  20659. } else if ( this.textures.needsMipmaps( texture ) && textureData.needsMipmap === true ) {
  20660. this.backend.generateMipmaps( texture );
  20661. textureData.needsMipmap = false;
  20662. }
  20663. }
  20664. }
  20665. }
  20666. if ( needsBindingsUpdate === true ) {
  20667. this.backend.updateBindings( bindGroup, bindings, cacheBindings ? cacheIndex : 0, version );
  20668. }
  20669. }
  20670. }
  20671. /**
  20672. * Default sorting function for opaque render items.
  20673. *
  20674. * @private
  20675. * @function
  20676. * @param {Object} a - The first render item.
  20677. * @param {Object} b - The second render item.
  20678. * @return {number} A numeric value which defines the sort order.
  20679. */
  20680. function painterSortStable( a, b ) {
  20681. if ( a.groupOrder !== b.groupOrder ) {
  20682. return a.groupOrder - b.groupOrder;
  20683. } else if ( a.renderOrder !== b.renderOrder ) {
  20684. return a.renderOrder - b.renderOrder;
  20685. } else if ( a.z !== b.z ) {
  20686. return a.z - b.z;
  20687. } else {
  20688. return a.id - b.id;
  20689. }
  20690. }
  20691. /**
  20692. * Default sorting function for transparent render items.
  20693. *
  20694. * @private
  20695. * @function
  20696. * @param {Object} a - The first render item.
  20697. * @param {Object} b - The second render item.
  20698. * @return {number} A numeric value which defines the sort order.
  20699. */
  20700. function reversePainterSortStable( a, b ) {
  20701. if ( a.groupOrder !== b.groupOrder ) {
  20702. return a.groupOrder - b.groupOrder;
  20703. } else if ( a.renderOrder !== b.renderOrder ) {
  20704. return a.renderOrder - b.renderOrder;
  20705. } else if ( a.z !== b.z ) {
  20706. return b.z - a.z;
  20707. } else {
  20708. return a.id - b.id;
  20709. }
  20710. }
  20711. /**
  20712. * Returns `true` if the given transparent material requires a double pass.
  20713. *
  20714. * @private
  20715. * @function
  20716. * @param {Material} material - The transparent material.
  20717. * @return {boolean} Whether the given material requires a double pass or not.
  20718. */
  20719. function needsDoublePass( material ) {
  20720. const hasTransmission = material.transmission > 0 || material.transmissionNode;
  20721. return hasTransmission && material.side === DoubleSide && material.forceSinglePass === false;
  20722. }
  20723. /**
  20724. * When the renderer analyzes the scene at the beginning of a render call,
  20725. * it stores 3D object for further processing in render lists. Depending on the
  20726. * properties of a 3D objects (like their transformation or material state), the
  20727. * objects are maintained in ordered lists for the actual rendering.
  20728. *
  20729. * Render lists are unique per scene and camera combination.
  20730. *
  20731. * @private
  20732. * @augments Pipeline
  20733. */
  20734. class RenderList {
  20735. /**
  20736. * Constructs a render list.
  20737. *
  20738. * @param {Lighting} lighting - The lighting management component.
  20739. * @param {Scene} scene - The scene.
  20740. * @param {Camera} camera - The camera the scene is rendered with.
  20741. */
  20742. constructor( lighting, scene, camera ) {
  20743. /**
  20744. * 3D objects are transformed into render items and stored in this array.
  20745. *
  20746. * @type {Array<Object>}
  20747. */
  20748. this.renderItems = [];
  20749. /**
  20750. * The current render items index.
  20751. *
  20752. * @type {number}
  20753. * @default 0
  20754. */
  20755. this.renderItemsIndex = 0;
  20756. /**
  20757. * A list with opaque render items.
  20758. *
  20759. * @type {Array<Object>}
  20760. */
  20761. this.opaque = [];
  20762. /**
  20763. * A list with transparent render items which require
  20764. * double pass rendering (e.g. transmissive objects).
  20765. *
  20766. * @type {Array<Object>}
  20767. */
  20768. this.transparentDoublePass = [];
  20769. /**
  20770. * A list with transparent render items.
  20771. *
  20772. * @type {Array<Object>}
  20773. */
  20774. this.transparent = [];
  20775. /**
  20776. * A list with transparent render bundle data.
  20777. *
  20778. * @type {Array<Object>}
  20779. */
  20780. this.bundles = [];
  20781. /**
  20782. * The render list's lights node. This node is later
  20783. * relevant for the actual analytical light nodes which
  20784. * compute the scene's lighting in the shader.
  20785. *
  20786. * @type {LightsNode}
  20787. */
  20788. this.lightsNode = lighting.getNode( scene, camera );
  20789. /**
  20790. * The scene's lights stored in an array. This array
  20791. * is used to setup the lights node.
  20792. *
  20793. * @type {Array<Light>}
  20794. */
  20795. this.lightsArray = [];
  20796. /**
  20797. * The scene.
  20798. *
  20799. * @type {Scene}
  20800. */
  20801. this.scene = scene;
  20802. /**
  20803. * The camera the scene is rendered with.
  20804. *
  20805. * @type {Camera}
  20806. */
  20807. this.camera = camera;
  20808. /**
  20809. * How many objects perform occlusion query tests.
  20810. *
  20811. * @type {number}
  20812. * @default 0
  20813. */
  20814. this.occlusionQueryCount = 0;
  20815. }
  20816. /**
  20817. * This method is called right at the beginning of a render call
  20818. * before the scene is analyzed. It prepares the internal data
  20819. * structures for the upcoming render lists generation.
  20820. *
  20821. * @return {RenderList} A reference to this render list.
  20822. */
  20823. begin() {
  20824. this.renderItemsIndex = 0;
  20825. this.opaque.length = 0;
  20826. this.transparentDoublePass.length = 0;
  20827. this.transparent.length = 0;
  20828. this.bundles.length = 0;
  20829. this.lightsArray.length = 0;
  20830. this.occlusionQueryCount = 0;
  20831. return this;
  20832. }
  20833. /**
  20834. * Returns a render item for the giving render item state. The state is defined
  20835. * by a series of object-related parameters.
  20836. *
  20837. * The method avoids object creation by holding render items and reusing them in
  20838. * subsequent render calls (just with different property values).
  20839. *
  20840. * @param {Object3D} object - The 3D object.
  20841. * @param {BufferGeometry} geometry - The 3D object's geometry.
  20842. * @param {Material} material - The 3D object's material.
  20843. * @param {number} groupOrder - The current group order.
  20844. * @param {number} z - Th 3D object's depth value (z value in clip space).
  20845. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  20846. * @param {ClippingContext} clippingContext - The current clipping context.
  20847. * @return {Object} The render item.
  20848. */
  20849. getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext ) {
  20850. let renderItem = this.renderItems[ this.renderItemsIndex ];
  20851. if ( renderItem === undefined ) {
  20852. renderItem = {
  20853. id: object.id,
  20854. object: object,
  20855. geometry: geometry,
  20856. material: material,
  20857. groupOrder: groupOrder,
  20858. renderOrder: object.renderOrder,
  20859. z: z,
  20860. group: group,
  20861. clippingContext: clippingContext
  20862. };
  20863. this.renderItems[ this.renderItemsIndex ] = renderItem;
  20864. } else {
  20865. renderItem.id = object.id;
  20866. renderItem.object = object;
  20867. renderItem.geometry = geometry;
  20868. renderItem.material = material;
  20869. renderItem.groupOrder = groupOrder;
  20870. renderItem.renderOrder = object.renderOrder;
  20871. renderItem.z = z;
  20872. renderItem.group = group;
  20873. renderItem.clippingContext = clippingContext;
  20874. }
  20875. this.renderItemsIndex ++;
  20876. return renderItem;
  20877. }
  20878. /**
  20879. * Pushes the given object as a render item to the internal render lists.
  20880. * The selected lists depend on the object properties.
  20881. *
  20882. * @param {Object3D} object - The 3D object.
  20883. * @param {BufferGeometry} geometry - The 3D object's geometry.
  20884. * @param {Material} material - The 3D object's material.
  20885. * @param {number} groupOrder - The current group order.
  20886. * @param {number} z - Th 3D object's depth value (z value in clip space).
  20887. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  20888. * @param {ClippingContext} clippingContext - The current clipping context.
  20889. */
  20890. push( object, geometry, material, groupOrder, z, group, clippingContext ) {
  20891. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  20892. if ( object.occlusionTest === true ) this.occlusionQueryCount ++;
  20893. if ( material.transparent === true || material.transmission > 0 ) {
  20894. if ( needsDoublePass( material ) ) this.transparentDoublePass.push( renderItem );
  20895. this.transparent.push( renderItem );
  20896. } else {
  20897. this.opaque.push( renderItem );
  20898. }
  20899. }
  20900. /**
  20901. * Inserts the given object as a render item at the start of the internal render lists.
  20902. * The selected lists depend on the object properties.
  20903. *
  20904. * @param {Object3D} object - The 3D object.
  20905. * @param {BufferGeometry} geometry - The 3D object's geometry.
  20906. * @param {Material} material - The 3D object's material.
  20907. * @param {number} groupOrder - The current group order.
  20908. * @param {number} z - Th 3D object's depth value (z value in clip space).
  20909. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  20910. * @param {ClippingContext} clippingContext - The current clipping context.
  20911. */
  20912. unshift( object, geometry, material, groupOrder, z, group, clippingContext ) {
  20913. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  20914. if ( material.transparent === true || material.transmission > 0 ) {
  20915. if ( needsDoublePass( material ) ) this.transparentDoublePass.unshift( renderItem );
  20916. this.transparent.unshift( renderItem );
  20917. } else {
  20918. this.opaque.unshift( renderItem );
  20919. }
  20920. }
  20921. /**
  20922. * Pushes render bundle group data into the render list.
  20923. *
  20924. * @param {Object} group - Bundle group data.
  20925. */
  20926. pushBundle( group ) {
  20927. this.bundles.push( group );
  20928. }
  20929. /**
  20930. * Pushes a light into the render list.
  20931. *
  20932. * @param {Light} light - The light.
  20933. */
  20934. pushLight( light ) {
  20935. this.lightsArray.push( light );
  20936. }
  20937. /**
  20938. * Sorts the internal render lists.
  20939. *
  20940. * @param {?function(any, any): number} customOpaqueSort - A custom sort function for opaque objects.
  20941. * @param {?function(any, any): number} customTransparentSort - A custom sort function for transparent objects.
  20942. */
  20943. sort( customOpaqueSort, customTransparentSort ) {
  20944. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  20945. if ( this.transparentDoublePass.length > 1 ) this.transparentDoublePass.sort( customTransparentSort || reversePainterSortStable );
  20946. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  20947. }
  20948. /**
  20949. * This method performs finalizing tasks right after the render lists
  20950. * have been generated.
  20951. */
  20952. finish() {
  20953. // update lights
  20954. this.lightsNode.setLights( this.lightsArray );
  20955. // Clear references from inactive renderItems in the list
  20956. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  20957. const renderItem = this.renderItems[ i ];
  20958. if ( renderItem.id === null ) break;
  20959. renderItem.id = null;
  20960. renderItem.object = null;
  20961. renderItem.geometry = null;
  20962. renderItem.material = null;
  20963. renderItem.groupOrder = null;
  20964. renderItem.renderOrder = null;
  20965. renderItem.z = null;
  20966. renderItem.group = null;
  20967. renderItem.clippingContext = null;
  20968. }
  20969. }
  20970. }
  20971. const _chainKeys$4 = [];
  20972. /**
  20973. * This renderer module manages the render lists which are unique
  20974. * per scene and camera combination.
  20975. *
  20976. * @private
  20977. */
  20978. class RenderLists {
  20979. /**
  20980. * Constructs a render lists management component.
  20981. *
  20982. * @param {Lighting} lighting - The lighting management component.
  20983. */
  20984. constructor( lighting ) {
  20985. /**
  20986. * The lighting management component.
  20987. *
  20988. * @type {Lighting}
  20989. */
  20990. this.lighting = lighting;
  20991. /**
  20992. * The internal chain map which holds the render lists.
  20993. *
  20994. * @type {ChainMap}
  20995. */
  20996. this.lists = new ChainMap();
  20997. }
  20998. /**
  20999. * Returns a render list for the given scene and camera.
  21000. *
  21001. * @param {Scene} scene - The scene.
  21002. * @param {Camera} camera - The camera.
  21003. * @return {RenderList} The render list.
  21004. */
  21005. get( scene, camera ) {
  21006. const lists = this.lists;
  21007. _chainKeys$4[ 0 ] = scene;
  21008. _chainKeys$4[ 1 ] = camera;
  21009. let list = lists.get( _chainKeys$4 );
  21010. if ( list === undefined ) {
  21011. list = new RenderList( this.lighting, scene, camera );
  21012. lists.set( _chainKeys$4, list );
  21013. }
  21014. _chainKeys$4.length = 0;
  21015. return list;
  21016. }
  21017. /**
  21018. * Frees all internal resources.
  21019. */
  21020. dispose() {
  21021. this.lists = new ChainMap();
  21022. }
  21023. }
  21024. let _id$7 = 0;
  21025. /**
  21026. * Any render or compute command is executed in a specific context that defines
  21027. * the state of the renderer and its backend. Typical examples for such context
  21028. * data are the current clear values or data from the active framebuffer. This
  21029. * module is used to represent these contexts as objects.
  21030. *
  21031. * @private
  21032. */
  21033. class RenderContext {
  21034. /**
  21035. * Constructs a new render context.
  21036. */
  21037. constructor() {
  21038. /**
  21039. * The context's ID.
  21040. *
  21041. * @type {number}
  21042. */
  21043. this.id = _id$7 ++;
  21044. /**
  21045. * Whether the current active framebuffer has a color attachment.
  21046. *
  21047. * @type {boolean}
  21048. * @default true
  21049. */
  21050. this.color = true;
  21051. /**
  21052. * Whether the color attachment should be cleared or not.
  21053. *
  21054. * @type {boolean}
  21055. * @default true
  21056. */
  21057. this.clearColor = true;
  21058. /**
  21059. * The clear color value.
  21060. *
  21061. * @type {Object}
  21062. * @default true
  21063. */
  21064. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  21065. /**
  21066. * Whether the current active framebuffer has a depth attachment.
  21067. *
  21068. * @type {boolean}
  21069. * @default true
  21070. */
  21071. this.depth = true;
  21072. /**
  21073. * Whether the depth attachment should be cleared or not.
  21074. *
  21075. * @type {boolean}
  21076. * @default true
  21077. */
  21078. this.clearDepth = true;
  21079. /**
  21080. * The clear depth value.
  21081. *
  21082. * @type {number}
  21083. * @default 1
  21084. */
  21085. this.clearDepthValue = 1;
  21086. /**
  21087. * Whether the current active framebuffer has a stencil attachment.
  21088. *
  21089. * @type {boolean}
  21090. * @default false
  21091. */
  21092. this.stencil = false;
  21093. /**
  21094. * Whether the stencil attachment should be cleared or not.
  21095. *
  21096. * @type {boolean}
  21097. * @default true
  21098. */
  21099. this.clearStencil = true;
  21100. /**
  21101. * The clear stencil value.
  21102. *
  21103. * @type {number}
  21104. * @default 1
  21105. */
  21106. this.clearStencilValue = 1;
  21107. /**
  21108. * By default the viewport encloses the entire framebuffer If a smaller
  21109. * viewport is manually defined, this property is to `true` by the renderer.
  21110. *
  21111. * @type {boolean}
  21112. * @default false
  21113. */
  21114. this.viewport = false;
  21115. /**
  21116. * The viewport value. This value is in physical pixels meaning it incorporates
  21117. * the renderer's pixel ratio. The viewport property of render targets or
  21118. * the renderer is in logical pixels.
  21119. *
  21120. * @type {Vector4}
  21121. */
  21122. this.viewportValue = new Vector4();
  21123. /**
  21124. * When the scissor test is active and scissor rectangle smaller than the
  21125. * framebuffers dimensions, this property is to `true` by the renderer.
  21126. *
  21127. * @type {boolean}
  21128. * @default false
  21129. */
  21130. this.scissor = false;
  21131. /**
  21132. * The scissor rectangle.
  21133. *
  21134. * @type {Vector4}
  21135. */
  21136. this.scissorValue = new Vector4();
  21137. /**
  21138. * The active render target.
  21139. *
  21140. * @type {?RenderTarget}
  21141. * @default null
  21142. */
  21143. this.renderTarget = null;
  21144. /**
  21145. * The textures of the active render target.
  21146. * `null` when no render target is set.
  21147. *
  21148. * @type {?Array<Texture>}
  21149. * @default null
  21150. */
  21151. this.textures = null;
  21152. /**
  21153. * The depth texture of the active render target.
  21154. * `null` when no render target is set.
  21155. *
  21156. * @type {?DepthTexture}
  21157. * @default null
  21158. */
  21159. this.depthTexture = null;
  21160. /**
  21161. * The active cube face.
  21162. *
  21163. * @type {number}
  21164. * @default 0
  21165. */
  21166. this.activeCubeFace = 0;
  21167. /**
  21168. * The active mipmap level.
  21169. *
  21170. * @type {number}
  21171. * @default 0
  21172. */
  21173. this.activeMipmapLevel = 0;
  21174. /**
  21175. * The number of MSAA samples. This value is always `1` when
  21176. * MSAA isn't used.
  21177. *
  21178. * @type {number}
  21179. * @default 1
  21180. */
  21181. this.sampleCount = 1;
  21182. /**
  21183. * The active render target's width in physical pixels.
  21184. *
  21185. * @type {number}
  21186. * @default 0
  21187. */
  21188. this.width = 0;
  21189. /**
  21190. * The active render target's height in physical pixels.
  21191. *
  21192. * @type {number}
  21193. * @default 0
  21194. */
  21195. this.height = 0;
  21196. /**
  21197. * The occlusion query count.
  21198. *
  21199. * @type {number}
  21200. * @default 0
  21201. */
  21202. this.occlusionQueryCount = 0;
  21203. /**
  21204. * The current clipping context.
  21205. *
  21206. * @type {?ClippingContext}
  21207. * @default null
  21208. */
  21209. this.clippingContext = null;
  21210. /**
  21211. * This flag can be used for type testing.
  21212. *
  21213. * @type {boolean}
  21214. * @readonly
  21215. * @default true
  21216. */
  21217. this.isRenderContext = true;
  21218. }
  21219. /**
  21220. * Returns the cache key of this render context.
  21221. *
  21222. * @return {number} The cache key.
  21223. */
  21224. getCacheKey() {
  21225. return getCacheKey( this );
  21226. }
  21227. }
  21228. /**
  21229. * Computes a cache key for the given render context. This key
  21230. * should identify the render target state so it is possible to
  21231. * configure the correct attachments in the respective backend.
  21232. *
  21233. * @param {RenderContext} renderContext - The render context.
  21234. * @return {number} The cache key.
  21235. */
  21236. function getCacheKey( renderContext ) {
  21237. const { textures, activeCubeFace } = renderContext;
  21238. const values = [ activeCubeFace ];
  21239. for ( const texture of textures ) {
  21240. values.push( texture.id );
  21241. }
  21242. return hashArray( values );
  21243. }
  21244. const _chainKeys$3 = [];
  21245. const _defaultScene = /*@__PURE__*/ new Scene();
  21246. const _defaultCamera = /*@__PURE__*/ new Camera();
  21247. /**
  21248. * This module manages the render contexts of the renderer.
  21249. *
  21250. * @private
  21251. */
  21252. class RenderContexts {
  21253. /**
  21254. * Constructs a new render context management component.
  21255. */
  21256. constructor() {
  21257. /**
  21258. * A dictionary that manages render contexts in chain maps
  21259. * for each attachment state.
  21260. *
  21261. * @type {Object<string,ChainMap>}
  21262. */
  21263. this.chainMaps = {};
  21264. }
  21265. /**
  21266. * Returns a render context for the given scene, camera and render target.
  21267. *
  21268. * @param {Scene} scene - The scene.
  21269. * @param {Camera} camera - The camera that is used to render the scene.
  21270. * @param {?RenderTarget} [renderTarget=null] - The active render target.
  21271. * @return {RenderContext} The render context.
  21272. */
  21273. get( scene, camera, renderTarget = null ) {
  21274. _chainKeys$3[ 0 ] = scene;
  21275. _chainKeys$3[ 1 ] = camera;
  21276. let attachmentState;
  21277. if ( renderTarget === null ) {
  21278. attachmentState = 'default';
  21279. } else {
  21280. const format = renderTarget.texture.format;
  21281. const count = renderTarget.textures.length;
  21282. attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  21283. }
  21284. const chainMap = this._getChainMap( attachmentState );
  21285. let renderState = chainMap.get( _chainKeys$3 );
  21286. if ( renderState === undefined ) {
  21287. renderState = new RenderContext();
  21288. chainMap.set( _chainKeys$3, renderState );
  21289. }
  21290. _chainKeys$3.length = 0;
  21291. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  21292. return renderState;
  21293. }
  21294. /**
  21295. * Returns a render context intended for clear operations.
  21296. *
  21297. * @param {?RenderTarget} [renderTarget=null] - The active render target.
  21298. * @return {RenderContext} The render context.
  21299. */
  21300. getForClear( renderTarget = null ) {
  21301. return this.get( _defaultScene, _defaultCamera, renderTarget );
  21302. }
  21303. /**
  21304. * Returns a chain map for the given attachment state.
  21305. *
  21306. * @private
  21307. * @param {string} attachmentState - The attachment state.
  21308. * @return {ChainMap} The chain map.
  21309. */
  21310. _getChainMap( attachmentState ) {
  21311. return this.chainMaps[ attachmentState ] || ( this.chainMaps[ attachmentState ] = new ChainMap() );
  21312. }
  21313. /**
  21314. * Frees internal resources.
  21315. */
  21316. dispose() {
  21317. this.chainMaps = {};
  21318. }
  21319. }
  21320. const _size$3 = /*@__PURE__*/ new Vector3();
  21321. /**
  21322. * This module manages the textures of the renderer.
  21323. *
  21324. * @private
  21325. * @augments DataMap
  21326. */
  21327. class Textures extends DataMap {
  21328. /**
  21329. * Constructs a new texture management component.
  21330. *
  21331. * @param {Renderer} renderer - The renderer.
  21332. * @param {Backend} backend - The renderer's backend.
  21333. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  21334. */
  21335. constructor( renderer, backend, info ) {
  21336. super();
  21337. /**
  21338. * The renderer.
  21339. *
  21340. * @type {Renderer}
  21341. */
  21342. this.renderer = renderer;
  21343. /**
  21344. * The backend.
  21345. *
  21346. * @type {Backend}
  21347. */
  21348. this.backend = backend;
  21349. /**
  21350. * Renderer component for managing metrics and monitoring data.
  21351. *
  21352. * @type {Info}
  21353. */
  21354. this.info = info;
  21355. }
  21356. /**
  21357. * Updates the given render target. Based on the given render target configuration,
  21358. * it updates the texture states representing the attachments of the framebuffer.
  21359. *
  21360. * @param {RenderTarget} renderTarget - The render target to update.
  21361. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  21362. */
  21363. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  21364. const renderTargetData = this.get( renderTarget );
  21365. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  21366. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  21367. const textures = renderTarget.textures;
  21368. const size = this.getSize( textures[ 0 ] );
  21369. const mipWidth = size.width >> activeMipmapLevel;
  21370. const mipHeight = size.height >> activeMipmapLevel;
  21371. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  21372. const useDepthTexture = renderTarget.depthBuffer === true || renderTarget.stencilBuffer === true;
  21373. let textureNeedsUpdate = false;
  21374. if ( depthTexture === undefined && useDepthTexture ) {
  21375. depthTexture = new DepthTexture();
  21376. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  21377. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  21378. depthTexture.image.width = mipWidth;
  21379. depthTexture.image.height = mipHeight;
  21380. depthTexture.image.depth = size.depth;
  21381. depthTexture.isArrayTexture = renderTarget.multiview === true && size.depth > 1;
  21382. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  21383. }
  21384. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  21385. textureNeedsUpdate = true;
  21386. if ( depthTexture ) {
  21387. depthTexture.needsUpdate = true;
  21388. depthTexture.image.width = mipWidth;
  21389. depthTexture.image.height = mipHeight;
  21390. depthTexture.image.depth = depthTexture.isArrayTexture ? depthTexture.image.depth : 1;
  21391. }
  21392. }
  21393. renderTargetData.width = size.width;
  21394. renderTargetData.height = size.height;
  21395. renderTargetData.textures = textures;
  21396. renderTargetData.depthTexture = depthTexture || null;
  21397. renderTargetData.depth = renderTarget.depthBuffer;
  21398. renderTargetData.stencil = renderTarget.stencilBuffer;
  21399. renderTargetData.renderTarget = renderTarget;
  21400. if ( renderTargetData.sampleCount !== sampleCount ) {
  21401. textureNeedsUpdate = true;
  21402. if ( depthTexture ) {
  21403. depthTexture.needsUpdate = true;
  21404. }
  21405. renderTargetData.sampleCount = sampleCount;
  21406. }
  21407. //
  21408. const options = { sampleCount };
  21409. // XR render targets require no texture updates
  21410. if ( renderTarget.isXRRenderTarget !== true ) {
  21411. for ( let i = 0; i < textures.length; i ++ ) {
  21412. const texture = textures[ i ];
  21413. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  21414. this.updateTexture( texture, options );
  21415. }
  21416. if ( depthTexture ) {
  21417. this.updateTexture( depthTexture, options );
  21418. }
  21419. }
  21420. // dispose handler
  21421. if ( renderTargetData.initialized !== true ) {
  21422. renderTargetData.initialized = true;
  21423. // dispose
  21424. const onDispose = () => {
  21425. renderTarget.removeEventListener( 'dispose', onDispose );
  21426. for ( let i = 0; i < textures.length; i ++ ) {
  21427. this._destroyTexture( textures[ i ] );
  21428. }
  21429. if ( depthTexture ) {
  21430. this._destroyTexture( depthTexture );
  21431. }
  21432. this.delete( renderTarget );
  21433. };
  21434. renderTarget.addEventListener( 'dispose', onDispose );
  21435. }
  21436. }
  21437. /**
  21438. * Updates the given texture. Depending on the texture state, this method
  21439. * triggers the upload of texture data to the GPU memory. If the texture data are
  21440. * not yet ready for the upload, it uses default texture data for as a placeholder.
  21441. *
  21442. * @param {Texture} texture - The texture to update.
  21443. * @param {Object} [options={}] - The options.
  21444. */
  21445. updateTexture( texture, options = {} ) {
  21446. const textureData = this.get( texture );
  21447. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  21448. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  21449. const backend = this.backend;
  21450. if ( isRenderTarget && textureData.initialized === true ) {
  21451. // it's an update
  21452. backend.destroySampler( texture );
  21453. backend.destroyTexture( texture );
  21454. }
  21455. //
  21456. if ( texture.isFramebufferTexture ) {
  21457. const renderTarget = this.renderer.getRenderTarget();
  21458. if ( renderTarget ) {
  21459. texture.type = renderTarget.texture.type;
  21460. } else {
  21461. texture.type = UnsignedByteType;
  21462. }
  21463. }
  21464. //
  21465. const { width, height, depth } = this.getSize( texture );
  21466. options.width = width;
  21467. options.height = height;
  21468. options.depth = depth;
  21469. options.needsMipmaps = this.needsMipmaps( texture );
  21470. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  21471. //
  21472. if ( isRenderTarget || texture.isStorageTexture === true ) {
  21473. backend.createSampler( texture );
  21474. backend.createTexture( texture, options );
  21475. textureData.generation = texture.version;
  21476. } else {
  21477. const needsCreate = textureData.initialized !== true;
  21478. if ( needsCreate ) backend.createSampler( texture );
  21479. if ( texture.version > 0 ) {
  21480. const image = texture.image;
  21481. if ( image === undefined ) {
  21482. console.warn( 'THREE.Renderer: Texture marked for update but image is undefined.' );
  21483. } else if ( image.complete === false ) {
  21484. console.warn( 'THREE.Renderer: Texture marked for update but image is incomplete.' );
  21485. } else {
  21486. if ( texture.images ) {
  21487. const images = [];
  21488. for ( const image of texture.images ) {
  21489. images.push( image );
  21490. }
  21491. options.images = images;
  21492. } else {
  21493. options.image = image;
  21494. }
  21495. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  21496. backend.createTexture( texture, options );
  21497. textureData.isDefaultTexture = false;
  21498. textureData.generation = texture.version;
  21499. }
  21500. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  21501. if ( options.needsMipmaps && texture.mipmaps.length === 0 ) backend.generateMipmaps( texture );
  21502. }
  21503. } else {
  21504. // async update
  21505. backend.createDefaultTexture( texture );
  21506. textureData.isDefaultTexture = true;
  21507. textureData.generation = texture.version;
  21508. }
  21509. }
  21510. // dispose handler
  21511. if ( textureData.initialized !== true ) {
  21512. textureData.initialized = true;
  21513. textureData.generation = texture.version;
  21514. //
  21515. this.info.memory.textures ++;
  21516. // dispose
  21517. const onDispose = () => {
  21518. texture.removeEventListener( 'dispose', onDispose );
  21519. this._destroyTexture( texture );
  21520. };
  21521. texture.addEventListener( 'dispose', onDispose );
  21522. }
  21523. //
  21524. textureData.version = texture.version;
  21525. }
  21526. /**
  21527. * Computes the size of the given texture and writes the result
  21528. * into the target vector. This vector is also returned by the
  21529. * method.
  21530. *
  21531. * If no texture data are available for the compute yet, the method
  21532. * returns default size values.
  21533. *
  21534. * @param {Texture} texture - The texture to compute the size for.
  21535. * @param {Vector3} target - The target vector.
  21536. * @return {Vector3} The target vector.
  21537. */
  21538. getSize( texture, target = _size$3 ) {
  21539. let image = texture.images ? texture.images[ 0 ] : texture.image;
  21540. if ( image ) {
  21541. if ( image.image !== undefined ) image = image.image;
  21542. if ( image instanceof HTMLVideoElement ) {
  21543. target.width = image.videoWidth || 1;
  21544. target.height = image.videoHeight || 1;
  21545. target.depth = 1;
  21546. } else if ( image instanceof VideoFrame ) {
  21547. target.width = image.displayWidth || 1;
  21548. target.height = image.displayHeight || 1;
  21549. target.depth = 1;
  21550. } else {
  21551. target.width = image.width || 1;
  21552. target.height = image.height || 1;
  21553. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  21554. }
  21555. } else {
  21556. target.width = target.height = target.depth = 1;
  21557. }
  21558. return target;
  21559. }
  21560. /**
  21561. * Computes the number of mipmap levels for the given texture.
  21562. *
  21563. * @param {Texture} texture - The texture.
  21564. * @param {number} width - The texture's width.
  21565. * @param {number} height - The texture's height.
  21566. * @return {number} The number of mipmap levels.
  21567. */
  21568. getMipLevels( texture, width, height ) {
  21569. let mipLevelCount;
  21570. if ( texture.isCompressedTexture ) {
  21571. if ( texture.mipmaps ) {
  21572. mipLevelCount = texture.mipmaps.length;
  21573. } else {
  21574. mipLevelCount = 1;
  21575. }
  21576. } else {
  21577. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  21578. }
  21579. return mipLevelCount;
  21580. }
  21581. /**
  21582. * Returns `true` if the given texture requires mipmaps.
  21583. *
  21584. * @param {Texture} texture - The texture.
  21585. * @return {boolean} Whether mipmaps are required or not.
  21586. */
  21587. needsMipmaps( texture ) {
  21588. return texture.isCompressedTexture === true || texture.generateMipmaps;
  21589. }
  21590. /**
  21591. * Frees internal resource when the given texture isn't
  21592. * required anymore.
  21593. *
  21594. * @param {Texture} texture - The texture to destroy.
  21595. */
  21596. _destroyTexture( texture ) {
  21597. if ( this.has( texture ) === true ) {
  21598. this.backend.destroySampler( texture );
  21599. this.backend.destroyTexture( texture );
  21600. this.delete( texture );
  21601. this.info.memory.textures --;
  21602. }
  21603. }
  21604. }
  21605. /**
  21606. * A four-component version of {@link Color} which is internally
  21607. * used by the renderer to represents clear color with alpha as
  21608. * one object.
  21609. *
  21610. * @private
  21611. * @augments Color
  21612. */
  21613. class Color4 extends Color {
  21614. /**
  21615. * Constructs a new four-component color.
  21616. * You can also pass a single THREE.Color, hex or
  21617. * string argument to this constructor.
  21618. *
  21619. * @param {number|string} [r=1] - The red value.
  21620. * @param {number} [g=1] - The green value.
  21621. * @param {number} [b=1] - The blue value.
  21622. * @param {number} [a=1] - The alpha value.
  21623. */
  21624. constructor( r, g, b, a = 1 ) {
  21625. super( r, g, b );
  21626. this.a = a;
  21627. }
  21628. /**
  21629. * Overwrites the default to honor alpha.
  21630. * You can also pass a single THREE.Color, hex or
  21631. * string argument to this method.
  21632. *
  21633. * @param {number|string|Color} r - The red value.
  21634. * @param {number} [g] - The green value.
  21635. * @param {number} [b] - The blue value.
  21636. * @param {number} [a=1] - The alpha value.
  21637. * @return {Color4} A reference to this object.
  21638. */
  21639. set( r, g, b, a = 1 ) {
  21640. this.a = a;
  21641. return super.set( r, g, b );
  21642. }
  21643. /**
  21644. * Overwrites the default to honor alpha.
  21645. *
  21646. * @param {Color4} color - The color to copy.
  21647. * @return {Color4} A reference to this object.
  21648. */
  21649. copy( color ) {
  21650. if ( color.a !== undefined ) this.a = color.a;
  21651. return super.copy( color );
  21652. }
  21653. /**
  21654. * Overwrites the default to honor alpha.
  21655. *
  21656. * @return {Color4} The cloned color.
  21657. */
  21658. clone() {
  21659. return new this.constructor( this.r, this.g, this.b, this.a );
  21660. }
  21661. }
  21662. /**
  21663. * Special version of {@link PropertyNode} which is used for parameters.
  21664. *
  21665. * @augments PropertyNode
  21666. */
  21667. class ParameterNode extends PropertyNode {
  21668. static get type() {
  21669. return 'ParameterNode';
  21670. }
  21671. /**
  21672. * Constructs a new parameter node.
  21673. *
  21674. * @param {string} nodeType - The type of the node.
  21675. * @param {?string} [name=null] - The name of the parameter in the shader.
  21676. */
  21677. constructor( nodeType, name = null ) {
  21678. super( nodeType, name );
  21679. /**
  21680. * This flag can be used for type testing.
  21681. *
  21682. * @type {boolean}
  21683. * @readonly
  21684. * @default true
  21685. */
  21686. this.isParameterNode = true;
  21687. }
  21688. getHash() {
  21689. return this.uuid;
  21690. }
  21691. generate() {
  21692. return this.name;
  21693. }
  21694. }
  21695. /**
  21696. * TSL function for creating a parameter node.
  21697. *
  21698. * @tsl
  21699. * @function
  21700. * @param {string} type - The type of the node.
  21701. * @param {?string} name - The name of the parameter in the shader.
  21702. * @returns {ParameterNode}
  21703. */
  21704. const parameter = ( type, name ) => nodeObject( new ParameterNode( type, name ) );
  21705. /**
  21706. * Stack is a helper for Nodes that need to produce stack-based code instead of continuous flow.
  21707. * They are usually needed in cases like `If`, `Else`.
  21708. *
  21709. * @augments Node
  21710. */
  21711. class StackNode extends Node {
  21712. static get type() {
  21713. return 'StackNode';
  21714. }
  21715. /**
  21716. * Constructs a new stack node.
  21717. *
  21718. * @param {?StackNode} [parent=null] - The parent stack node.
  21719. */
  21720. constructor( parent = null ) {
  21721. super();
  21722. /**
  21723. * List of nodes.
  21724. *
  21725. * @type {Array<Node>}
  21726. */
  21727. this.nodes = [];
  21728. /**
  21729. * The output node.
  21730. *
  21731. * @type {?Node}
  21732. * @default null
  21733. */
  21734. this.outputNode = null;
  21735. /**
  21736. * The parent stack node.
  21737. *
  21738. * @type {?StackNode}
  21739. * @default null
  21740. */
  21741. this.parent = parent;
  21742. /**
  21743. * The current conditional node.
  21744. *
  21745. * @private
  21746. * @type {ConditionalNode}
  21747. * @default null
  21748. */
  21749. this._currentCond = null;
  21750. /**
  21751. * The expression node. Only
  21752. * relevant for Switch/Case.
  21753. *
  21754. * @private
  21755. * @type {Node}
  21756. * @default null
  21757. */
  21758. this._expressionNode = null;
  21759. /**
  21760. * This flag can be used for type testing.
  21761. *
  21762. * @type {boolean}
  21763. * @readonly
  21764. * @default true
  21765. */
  21766. this.isStackNode = true;
  21767. }
  21768. getNodeType( builder ) {
  21769. return this.outputNode ? this.outputNode.getNodeType( builder ) : 'void';
  21770. }
  21771. getMemberType( builder, name ) {
  21772. return this.outputNode ? this.outputNode.getMemberType( builder, name ) : 'void';
  21773. }
  21774. /**
  21775. * Adds a node to this stack.
  21776. *
  21777. * @param {Node} node - The node to add.
  21778. * @return {StackNode} A reference to this stack node.
  21779. */
  21780. add( node ) {
  21781. this.nodes.push( node );
  21782. return this;
  21783. }
  21784. /**
  21785. * Represent an `if` statement in TSL.
  21786. *
  21787. * @param {Node} boolNode - Represents the condition.
  21788. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  21789. * @return {StackNode} A reference to this stack node.
  21790. */
  21791. If( boolNode, method ) {
  21792. const methodNode = new ShaderNode( method );
  21793. this._currentCond = select( boolNode, methodNode );
  21794. return this.add( this._currentCond );
  21795. }
  21796. /**
  21797. * Represent an `elseif` statement in TSL.
  21798. *
  21799. * @param {Node} boolNode - Represents the condition.
  21800. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  21801. * @return {StackNode} A reference to this stack node.
  21802. */
  21803. ElseIf( boolNode, method ) {
  21804. const methodNode = new ShaderNode( method );
  21805. const ifNode = select( boolNode, methodNode );
  21806. this._currentCond.elseNode = ifNode;
  21807. this._currentCond = ifNode;
  21808. return this;
  21809. }
  21810. /**
  21811. * Represent an `else` statement in TSL.
  21812. *
  21813. * @param {Function} method - TSL code which is executed in the `else` case.
  21814. * @return {StackNode} A reference to this stack node.
  21815. */
  21816. Else( method ) {
  21817. this._currentCond.elseNode = new ShaderNode( method );
  21818. return this;
  21819. }
  21820. /**
  21821. * Represents a `switch` statement in TSL.
  21822. *
  21823. * @param {any} expression - Represents the expression.
  21824. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  21825. * @return {StackNode} A reference to this stack node.
  21826. */
  21827. Switch( expression ) {
  21828. this._expressionNode = nodeObject( expression );
  21829. return this;
  21830. }
  21831. /**
  21832. * Represents a `case` statement in TSL. The TSL version accepts an arbitrary numbers of values.
  21833. * The last parameter must be the callback method that should be executed in the `true` case.
  21834. *
  21835. * @param {...any} params - The values of the `Case()` statement as well as the callback method.
  21836. * @return {StackNode} A reference to this stack node.
  21837. */
  21838. Case( ...params ) {
  21839. const caseNodes = [];
  21840. // extract case nodes from the parameter list
  21841. if ( params.length >= 2 ) {
  21842. for ( let i = 0; i < params.length - 1; i ++ ) {
  21843. caseNodes.push( this._expressionNode.equal( nodeObject( params[ i ] ) ) );
  21844. }
  21845. } else {
  21846. throw new Error( 'TSL: Invalid parameter length. Case() requires at least two parameters.' );
  21847. }
  21848. // extract method
  21849. const method = params[ params.length - 1 ];
  21850. const methodNode = new ShaderNode( method );
  21851. // chain multiple cases when using Case( 1, 2, 3, () => {} )
  21852. let caseNode = caseNodes[ 0 ];
  21853. for ( let i = 1; i < caseNodes.length; i ++ ) {
  21854. caseNode = caseNode.or( caseNodes[ i ] );
  21855. }
  21856. // build condition
  21857. const condNode = select( caseNode, methodNode );
  21858. if ( this._currentCond === null ) {
  21859. this._currentCond = condNode;
  21860. return this.add( this._currentCond );
  21861. } else {
  21862. this._currentCond.elseNode = condNode;
  21863. this._currentCond = condNode;
  21864. return this;
  21865. }
  21866. }
  21867. /**
  21868. * Represents the default code block of a Switch/Case statement.
  21869. *
  21870. * @param {Function} method - TSL code which is executed in the `else` case.
  21871. * @return {StackNode} A reference to this stack node.
  21872. */
  21873. Default( method ) {
  21874. this.Else( method );
  21875. return this;
  21876. }
  21877. build( builder, ...params ) {
  21878. const previousBuildStack = builder.currentStack;
  21879. const previousStack = getCurrentStack();
  21880. setCurrentStack( this );
  21881. builder.currentStack = this;
  21882. const buildStage = builder.buildStage;
  21883. for ( const node of this.nodes ) {
  21884. if ( buildStage === 'setup' ) {
  21885. node.build( builder );
  21886. } else if ( buildStage === 'analyze' ) {
  21887. node.build( builder, this );
  21888. } else if ( buildStage === 'generate' ) {
  21889. const stages = builder.getDataFromNode( node, 'any' ).stages;
  21890. const parents = stages && stages[ builder.shaderStage ];
  21891. if ( node.isVarNode && parents && parents.length === 1 && parents[ 0 ] && parents[ 0 ].isStackNode ) {
  21892. continue; // skip var nodes that are only used in .toVarying()
  21893. }
  21894. node.build( builder, 'void' );
  21895. }
  21896. }
  21897. const result = this.outputNode ? this.outputNode.build( builder, ...params ) : super.build( builder, ...params );
  21898. setCurrentStack( previousStack );
  21899. builder.currentStack = previousBuildStack;
  21900. return result;
  21901. }
  21902. }
  21903. /**
  21904. * TSL function for creating a stack node.
  21905. *
  21906. * @tsl
  21907. * @function
  21908. * @param {?StackNode} [parent=null] - The parent stack node.
  21909. * @returns {StackNode}
  21910. */
  21911. const stack = /*@__PURE__*/ nodeProxy( StackNode ).setParameterLength( 0, 1 );
  21912. /**
  21913. * Generates a layout for struct members.
  21914. * This function takes an object representing struct members and returns an array of member layouts.
  21915. * Each member layout includes the member's name, type, and whether it is atomic.
  21916. *
  21917. * @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.
  21918. * @returns {Array.<{name: string, type: string, atomic: boolean}>} An array of member layouts.
  21919. */
  21920. function getMembersLayout( members ) {
  21921. return Object.entries( members ).map( ( [ name, value ] ) => {
  21922. if ( typeof value === 'string' ) {
  21923. return { name, type: value, atomic: false };
  21924. }
  21925. return { name, type: value.type, atomic: value.atomic || false };
  21926. } );
  21927. }
  21928. /**
  21929. * Represents a struct type node in the node-based system.
  21930. * This class is used to define and manage the layout and types of struct members.
  21931. * It extends the base Node class and provides methods to get the length of the struct,
  21932. * retrieve member types, and generate the struct type for a builder.
  21933. *
  21934. * @augments Node
  21935. */
  21936. class StructTypeNode extends Node {
  21937. static get type() {
  21938. return 'StructTypeNode';
  21939. }
  21940. /**
  21941. * Creates an instance of StructTypeNode.
  21942. *
  21943. * @param {Object} membersLayout - The layout of the members for the struct.
  21944. * @param {?string} [name=null] - The optional name of the struct.
  21945. */
  21946. constructor( membersLayout, name = null ) {
  21947. super( 'struct' );
  21948. /**
  21949. * The layout of the members for the struct
  21950. *
  21951. * @type {Array.<{name: string, type: string, atomic: boolean}>}
  21952. */
  21953. this.membersLayout = getMembersLayout( membersLayout );
  21954. /**
  21955. * The name of the struct.
  21956. *
  21957. * @type {?string}
  21958. * @default null
  21959. */
  21960. this.name = name;
  21961. /**
  21962. * This flag can be used for type testing.
  21963. *
  21964. * @type {boolean}
  21965. * @readonly
  21966. * @default true
  21967. */
  21968. this.isStructLayoutNode = true;
  21969. }
  21970. /**
  21971. * Returns the length of the struct.
  21972. * The length is calculated by summing the lengths of the struct's members.
  21973. *
  21974. * @returns {number} The length of the struct.
  21975. */
  21976. getLength() {
  21977. const GPU_CHUNK_BYTES = 8;
  21978. const BYTES_PER_ELEMENT = Float32Array.BYTES_PER_ELEMENT;
  21979. let offset = 0; // global buffer offset in bytes
  21980. for ( const member of this.membersLayout ) {
  21981. const type = member.type;
  21982. const itemSize = getMemoryLengthFromType( type ) * BYTES_PER_ELEMENT;
  21983. const boundary = getByteBoundaryFromType( type );
  21984. const chunkOffset = offset % GPU_CHUNK_BYTES; // offset in the current chunk
  21985. const chunkPadding = chunkOffset % boundary; // required padding to match boundary
  21986. const chunkStart = chunkOffset + chunkPadding; // start position in the current chunk for the data
  21987. offset += chunkPadding;
  21988. // Check for chunk overflow
  21989. if ( chunkStart !== 0 && ( GPU_CHUNK_BYTES - chunkStart ) < itemSize ) {
  21990. // Add padding to the end of the chunk
  21991. offset += ( GPU_CHUNK_BYTES - chunkStart );
  21992. }
  21993. offset += itemSize;
  21994. }
  21995. return ( Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES ) / BYTES_PER_ELEMENT;
  21996. }
  21997. getMemberType( builder, name ) {
  21998. const member = this.membersLayout.find( m => m.name === name );
  21999. return member ? member.type : 'void';
  22000. }
  22001. getNodeType( builder ) {
  22002. const structType = builder.getStructTypeFromNode( this, this.membersLayout, this.name );
  22003. return structType.name;
  22004. }
  22005. setup( builder ) {
  22006. builder.addInclude( this );
  22007. }
  22008. generate( builder ) {
  22009. return this.getNodeType( builder );
  22010. }
  22011. }
  22012. /**
  22013. * StructNode allows to create custom structures with multiple members.
  22014. * This can also be used to define structures in attribute and uniform data.
  22015. *
  22016. * ```js
  22017. * // Define a custom struct
  22018. * const BoundingBox = struct( { min: 'vec3', max: 'vec3' } );
  22019. *
  22020. * // Create a new instance of the struct
  22021. * const bb = BoundingBox( vec3( 0 ), vec3( 1 ) ); // style 1
  22022. * const bb = BoundingBox( { min: vec3( 0 ), max: vec3( 1 ) } ); // style 2
  22023. *
  22024. * // Access the struct members
  22025. * const min = bb.get( 'min' );
  22026. *
  22027. * // Assign a new value to a member
  22028. * min.assign( vec3() );
  22029. * ```
  22030. * @augments Node
  22031. */
  22032. class StructNode extends Node {
  22033. static get type() {
  22034. return 'StructNode';
  22035. }
  22036. constructor( structLayoutNode, values ) {
  22037. super( 'vec3' );
  22038. this.structLayoutNode = structLayoutNode;
  22039. this.values = values;
  22040. this.isStructNode = true;
  22041. }
  22042. getNodeType( builder ) {
  22043. return this.structLayoutNode.getNodeType( builder );
  22044. }
  22045. getMemberType( builder, name ) {
  22046. return this.structLayoutNode.getMemberType( builder, name );
  22047. }
  22048. generate( builder ) {
  22049. const nodeVar = builder.getVarFromNode( this );
  22050. const structType = nodeVar.type;
  22051. const propertyName = builder.getPropertyName( nodeVar );
  22052. builder.addLineFlowCode( `${ propertyName } = ${ builder.generateStruct( structType, this.structLayoutNode.membersLayout, this.values ) }`, this );
  22053. return nodeVar.name;
  22054. }
  22055. }
  22056. /**
  22057. * TSL function for creating a struct node.
  22058. *
  22059. * @tsl
  22060. * @function
  22061. * @param {Object} membersLayout - The layout of the struct members.
  22062. * @param {?string} [name=null] - The name of the struct.
  22063. * @returns {Function} The struct function.
  22064. */
  22065. const struct = ( membersLayout, name = null ) => {
  22066. const structLayout = new StructTypeNode( membersLayout, name );
  22067. const struct = ( ...params ) => {
  22068. let values = null;
  22069. if ( params.length > 0 ) {
  22070. if ( params[ 0 ].isNode ) {
  22071. values = {};
  22072. const names = Object.keys( membersLayout );
  22073. for ( let i = 0; i < params.length; i ++ ) {
  22074. values[ names[ i ] ] = params[ i ];
  22075. }
  22076. } else {
  22077. values = params[ 0 ];
  22078. }
  22079. }
  22080. return nodeObject( new StructNode( structLayout, values ) );
  22081. };
  22082. struct.layout = structLayout;
  22083. struct.isStruct = true;
  22084. return struct;
  22085. };
  22086. /**
  22087. * This node can be used to define multiple outputs in a shader programs.
  22088. *
  22089. * @augments Node
  22090. */
  22091. class OutputStructNode extends Node {
  22092. static get type() {
  22093. return 'OutputStructNode';
  22094. }
  22095. /**
  22096. * Constructs a new output struct node. The constructor can be invoked with an
  22097. * arbitrary number of nodes representing the members.
  22098. *
  22099. * @param {...Node} members - A parameter list of nodes.
  22100. */
  22101. constructor( ...members ) {
  22102. super();
  22103. /**
  22104. * An array of nodes which defines the output.
  22105. *
  22106. * @type {Array<Node>}
  22107. */
  22108. this.members = members;
  22109. /**
  22110. * This flag can be used for type testing.
  22111. *
  22112. * @type {boolean}
  22113. * @readonly
  22114. * @default true
  22115. */
  22116. this.isOutputStructNode = true;
  22117. }
  22118. getNodeType( builder ) {
  22119. const properties = builder.getNodeProperties( this );
  22120. if ( properties.membersLayout === undefined ) {
  22121. const members = this.members;
  22122. const membersLayout = [];
  22123. for ( let i = 0; i < members.length; i ++ ) {
  22124. const name = 'm' + i;
  22125. const type = members[ i ].getNodeType( builder );
  22126. membersLayout.push( { name, type, index: i } );
  22127. }
  22128. properties.membersLayout = membersLayout;
  22129. properties.structType = builder.getOutputStructTypeFromNode( this, properties.membersLayout );
  22130. }
  22131. return properties.structType.name;
  22132. }
  22133. generate( builder ) {
  22134. const propertyName = builder.getOutputStructName();
  22135. const members = this.members;
  22136. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  22137. for ( let i = 0; i < members.length; i ++ ) {
  22138. const snippet = members[ i ].build( builder );
  22139. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }`, this );
  22140. }
  22141. return propertyName;
  22142. }
  22143. }
  22144. /**
  22145. * TSL function for creating an output struct node.
  22146. *
  22147. * @tsl
  22148. * @function
  22149. * @param {...Node} members - A parameter list of nodes.
  22150. * @returns {OutputStructNode}
  22151. */
  22152. const outputStruct = /*@__PURE__*/ nodeProxy( OutputStructNode );
  22153. /**
  22154. * Returns the MRT texture index for the given name.
  22155. *
  22156. * @param {Array<Texture>} textures - The textures of a MRT-configured render target.
  22157. * @param {string} name - The name of the MRT texture which index is requested.
  22158. * @return {number} The texture index.
  22159. */
  22160. function getTextureIndex( textures, name ) {
  22161. for ( let i = 0; i < textures.length; i ++ ) {
  22162. if ( textures[ i ].name === name ) {
  22163. return i;
  22164. }
  22165. }
  22166. return -1;
  22167. }
  22168. /**
  22169. * This node can be used setup a MRT context for rendering. A typical MRT setup for
  22170. * post-processing is shown below:
  22171. * ```js
  22172. * const mrtNode = mrt( {
  22173. * output: output,
  22174. * normal: normalView
  22175. * } ) );
  22176. * ```
  22177. * The MRT output is defined as a dictionary.
  22178. *
  22179. * @augments OutputStructNode
  22180. */
  22181. class MRTNode extends OutputStructNode {
  22182. static get type() {
  22183. return 'MRTNode';
  22184. }
  22185. /**
  22186. * Constructs a new output struct node.
  22187. *
  22188. * @param {Object<string, Node>} outputNodes - The MRT outputs.
  22189. */
  22190. constructor( outputNodes ) {
  22191. super();
  22192. /**
  22193. * A dictionary representing the MRT outputs. The key
  22194. * is the name of the output, the value the node which produces
  22195. * the output result.
  22196. *
  22197. * @type {Object<string, Node>}
  22198. */
  22199. this.outputNodes = outputNodes;
  22200. /**
  22201. * This flag can be used for type testing.
  22202. *
  22203. * @type {boolean}
  22204. * @readonly
  22205. * @default true
  22206. */
  22207. this.isMRTNode = true;
  22208. }
  22209. /**
  22210. * Returns `true` if the MRT node has an output with the given name.
  22211. *
  22212. * @param {string} name - The name of the output.
  22213. * @return {NodeBuilder} Whether the MRT node has an output for the given name or not.
  22214. */
  22215. has( name ) {
  22216. return this.outputNodes[ name ] !== undefined;
  22217. }
  22218. /**
  22219. * Returns the output node for the given name.
  22220. *
  22221. * @param {string} name - The name of the output.
  22222. * @return {Node} The output node.
  22223. */
  22224. get( name ) {
  22225. return this.outputNodes[ name ];
  22226. }
  22227. /**
  22228. * Merges the outputs of the given MRT node with the outputs of this node.
  22229. *
  22230. * @param {MRTNode} mrtNode - The MRT to merge.
  22231. * @return {MRTNode} A new MRT node with merged outputs..
  22232. */
  22233. merge( mrtNode ) {
  22234. const outputs = { ...this.outputNodes, ...mrtNode.outputNodes };
  22235. return mrt( outputs );
  22236. }
  22237. setup( builder ) {
  22238. const outputNodes = this.outputNodes;
  22239. const mrt = builder.renderer.getRenderTarget();
  22240. const members = [];
  22241. const textures = mrt.textures;
  22242. for ( const name in outputNodes ) {
  22243. const index = getTextureIndex( textures, name );
  22244. members[ index ] = vec4( outputNodes[ name ] );
  22245. }
  22246. this.members = members;
  22247. return super.setup( builder );
  22248. }
  22249. }
  22250. /**
  22251. * TSL function for creating a MRT node.
  22252. *
  22253. * @tsl
  22254. * @function
  22255. * @param {Object<string, Node>} outputNodes - The MRT outputs.
  22256. * @returns {MRTNode}
  22257. */
  22258. const mrt = /*@__PURE__*/ nodeProxy( MRTNode );
  22259. /**
  22260. * Generates a hash value in the range `[0, 1]` from the given seed.
  22261. *
  22262. * @tsl
  22263. * @function
  22264. * @param {Node<float>} seed - The seed.
  22265. * @return {Node<float>} The hash value.
  22266. */
  22267. const hash = /*@__PURE__*/ Fn( ( [ seed ] ) => {
  22268. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  22269. const state = seed.toUint().mul( 747796405 ).add( 2891336453 );
  22270. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  22271. const result = word.shiftRight( 22 ).bitXor( word );
  22272. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  22273. } );
  22274. /**
  22275. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  22276. * The corners are mapped to `0` and the center to `1`.
  22277. * Reference: {@link https://iquilezles.org/articles/functions/}.
  22278. *
  22279. * @tsl
  22280. * @function
  22281. * @param {Node<float>} x - The value to remap.
  22282. * @param {Node<float>} k - Allows to control the remapping functions shape by rising the parabola to a power `k`.
  22283. * @return {Node<float>} The remapped value.
  22284. */
  22285. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  22286. /**
  22287. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  22288. * Expands the sides and compresses the center, and keeps `0.5` mapped to `0.5`.
  22289. * Reference: {@link https://iquilezles.org/articles/functions/}.
  22290. *
  22291. * @tsl
  22292. * @function
  22293. * @param {Node<float>} x - The value to remap.
  22294. * @param {Node<float>} k - `k=1` is the identity curve,`k<1` produces the classic `gain()` shape, and `k>1` produces "s" shaped curves.
  22295. * @return {Node<float>} The remapped value.
  22296. */
  22297. 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 ) );
  22298. /**
  22299. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  22300. * A generalization of the `parabola()`. Keeps the corners mapped to 0 but allows the control of the shape one either side of the curve.
  22301. * Reference: {@link https://iquilezles.org/articles/functions/}.
  22302. *
  22303. * @tsl
  22304. * @function
  22305. * @param {Node<float>} x - The value to remap.
  22306. * @param {Node<float>} a - First control parameter.
  22307. * @param {Node<float>} b - Second control parameter.
  22308. * @return {Node<float>} The remapped value.
  22309. */
  22310. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  22311. /**
  22312. * A phase shifted sinus curve that starts at zero and ends at zero, with bouncing behavior.
  22313. * Reference: {@link https://iquilezles.org/articles/functions/}.
  22314. *
  22315. * @tsl
  22316. * @function
  22317. * @param {Node<float>} x - The value to compute the sin for.
  22318. * @param {Node<float>} k - Controls the amount of bounces.
  22319. * @return {Node<float>} The result value.
  22320. */
  22321. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  22322. // https://github.com/cabbibo/glsl-tri-noise-3d
  22323. const tri = /*@__PURE__*/ Fn( ( [ x ] ) => {
  22324. return x.fract().sub( .5 ).abs();
  22325. } ).setLayout( {
  22326. name: 'tri',
  22327. type: 'float',
  22328. inputs: [
  22329. { name: 'x', type: 'float' }
  22330. ]
  22331. } );
  22332. const tri3 = /*@__PURE__*/ Fn( ( [ p ] ) => {
  22333. 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. ) ) ) ) );
  22334. } ).setLayout( {
  22335. name: 'tri3',
  22336. type: 'vec3',
  22337. inputs: [
  22338. { name: 'p', type: 'vec3' }
  22339. ]
  22340. } );
  22341. /**
  22342. * Generates a noise value from the given position, speed and time parameters.
  22343. *
  22344. * @tsl
  22345. * @function
  22346. * @param {Node<vec3>} position - The position.
  22347. * @param {Node<float>} speed - The speed.
  22348. * @param {Node<float>} time - The time.
  22349. * @return {Node<float>} The generated noise.
  22350. */
  22351. const triNoise3D = /*@__PURE__*/ Fn( ( [ position, speed, time ] ) => {
  22352. const p = vec3( position ).toVar();
  22353. const z = float( 1.4 ).toVar();
  22354. const rz = float( 0.0 ).toVar();
  22355. const bp = vec3( p ).toVar();
  22356. Loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  22357. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  22358. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( speed ) ) ) );
  22359. bp.mulAssign( 1.8 );
  22360. z.mulAssign( 1.5 );
  22361. p.mulAssign( 1.2 );
  22362. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  22363. rz.addAssign( t.div( z ) );
  22364. bp.addAssign( 0.14 );
  22365. } );
  22366. return rz;
  22367. } ).setLayout( {
  22368. name: 'triNoise3D',
  22369. type: 'float',
  22370. inputs: [
  22371. { name: 'position', type: 'vec3' },
  22372. { name: 'speed', type: 'float' },
  22373. { name: 'time', type: 'float' }
  22374. ]
  22375. } );
  22376. /**
  22377. * This class allows to define multiple overloaded versions
  22378. * of the same function. Depending on the parameters of the function
  22379. * call, the node picks the best-fit overloaded version.
  22380. *
  22381. * @augments Node
  22382. */
  22383. class FunctionOverloadingNode extends Node {
  22384. static get type() {
  22385. return 'FunctionOverloadingNode';
  22386. }
  22387. /**
  22388. * Constructs a new function overloading node.
  22389. *
  22390. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  22391. * @param {...Node} parametersNodes - A list of parameter nodes.
  22392. */
  22393. constructor( functionNodes = [], ...parametersNodes ) {
  22394. super();
  22395. /**
  22396. * Array of `Fn` function definitions.
  22397. *
  22398. * @type {Array<Function>}
  22399. */
  22400. this.functionNodes = functionNodes;
  22401. /**
  22402. * A list of parameter nodes.
  22403. *
  22404. * @type {Array<Node>}
  22405. */
  22406. this.parametersNodes = parametersNodes;
  22407. /**
  22408. * The selected overloaded function call.
  22409. *
  22410. * @private
  22411. * @type {ShaderCallNodeInternal}
  22412. */
  22413. this._candidateFnCall = null;
  22414. /**
  22415. * This node is marked as global.
  22416. *
  22417. * @type {boolean}
  22418. * @default true
  22419. */
  22420. this.global = true;
  22421. }
  22422. /**
  22423. * This method is overwritten since the node type is inferred from
  22424. * the function's return type.
  22425. *
  22426. * @param {NodeBuilder} builder - The current node builder.
  22427. * @return {string} The node type.
  22428. */
  22429. getNodeType() {
  22430. return this.functionNodes[ 0 ].shaderNode.layout.type;
  22431. }
  22432. setup( builder ) {
  22433. const params = this.parametersNodes;
  22434. let candidateFnCall = this._candidateFnCall;
  22435. if ( candidateFnCall === null ) {
  22436. let candidateFn = null;
  22437. let candidateScore = -1;
  22438. for ( const functionNode of this.functionNodes ) {
  22439. const shaderNode = functionNode.shaderNode;
  22440. const layout = shaderNode.layout;
  22441. if ( layout === null ) {
  22442. throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' );
  22443. }
  22444. const inputs = layout.inputs;
  22445. if ( params.length === inputs.length ) {
  22446. let score = 0;
  22447. for ( let i = 0; i < params.length; i ++ ) {
  22448. const param = params[ i ];
  22449. const input = inputs[ i ];
  22450. if ( param.getNodeType( builder ) === input.type ) {
  22451. score ++;
  22452. } else {
  22453. score = 0;
  22454. }
  22455. }
  22456. if ( score > candidateScore ) {
  22457. candidateFn = functionNode;
  22458. candidateScore = score;
  22459. }
  22460. }
  22461. }
  22462. this._candidateFnCall = candidateFnCall = candidateFn( ...params );
  22463. }
  22464. return candidateFnCall;
  22465. }
  22466. }
  22467. const overloadingBaseFn = /*@__PURE__*/ nodeProxy( FunctionOverloadingNode );
  22468. /**
  22469. * TSL function for creating a function overloading node.
  22470. *
  22471. * @tsl
  22472. * @function
  22473. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  22474. * @returns {FunctionOverloadingNode}
  22475. */
  22476. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  22477. /**
  22478. * Represents the elapsed time in seconds.
  22479. *
  22480. * @tsl
  22481. * @type {UniformNode<float>}
  22482. */
  22483. const time = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.time );
  22484. /**
  22485. * Represents the delta time in seconds.
  22486. *
  22487. * @tsl
  22488. * @type {UniformNode<float>}
  22489. */
  22490. const deltaTime = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.deltaTime );
  22491. /**
  22492. * Represents the current frame ID.
  22493. *
  22494. * @tsl
  22495. * @type {UniformNode<uint>}
  22496. */
  22497. const frameId = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.frameId );
  22498. // Deprecated
  22499. /**
  22500. * @tsl
  22501. * @function
  22502. * @deprecated since r170. Use {@link time} instead.
  22503. *
  22504. * @param {number} [timeScale=1] - The time scale.
  22505. * @returns {UniformNode<float>}
  22506. */
  22507. const timerLocal = ( timeScale = 1 ) => { // @deprecated, r170
  22508. console.warn( 'TSL: timerLocal() is deprecated. Use "time" instead.' );
  22509. return time.mul( timeScale );
  22510. };
  22511. /**
  22512. * @tsl
  22513. * @function
  22514. * @deprecated since r170. Use {@link time} instead.
  22515. *
  22516. * @param {number} [timeScale=1] - The time scale.
  22517. * @returns {UniformNode<float>}
  22518. */
  22519. const timerGlobal = ( timeScale = 1 ) => { // @deprecated, r170
  22520. console.warn( 'TSL: timerGlobal() is deprecated. Use "time" instead.' );
  22521. return time.mul( timeScale );
  22522. };
  22523. /**
  22524. * @tsl
  22525. * @function
  22526. * @deprecated since r170. Use {@link deltaTime} instead.
  22527. *
  22528. * @param {number} [timeScale=1] - The time scale.
  22529. * @returns {UniformNode<float>}
  22530. */
  22531. const timerDelta = ( timeScale = 1 ) => { // @deprecated, r170
  22532. console.warn( 'TSL: timerDelta() is deprecated. Use "deltaTime" instead.' );
  22533. return deltaTime.mul( timeScale );
  22534. };
  22535. /**
  22536. * Generates a sine wave oscillation based on a timer.
  22537. *
  22538. * @tsl
  22539. * @function
  22540. * @param {Node<float>} t - The timer to generate the oscillation with.
  22541. * @return {Node<float>} The oscillation node.
  22542. */
  22543. const oscSine = ( t = time ) => t.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  22544. /**
  22545. * Generates a square wave oscillation based on a timer.
  22546. *
  22547. * @tsl
  22548. * @function
  22549. * @param {Node<float>} t - The timer to generate the oscillation with.
  22550. * @return {Node<float>} The oscillation node.
  22551. */
  22552. const oscSquare = ( t = time ) => t.fract().round();
  22553. /**
  22554. * Generates a triangle wave oscillation based on a timer.
  22555. *
  22556. * @tsl
  22557. * @function
  22558. * @param {Node<float>} t - The timer to generate the oscillation with.
  22559. * @return {Node<float>} The oscillation node.
  22560. */
  22561. const oscTriangle = ( t = time ) => t.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  22562. /**
  22563. * Generates a sawtooth wave oscillation based on a timer.
  22564. *
  22565. * @tsl
  22566. * @function
  22567. * @param {Node<float>} t - The timer to generate the oscillation with.
  22568. * @return {Node<float>} The oscillation node.
  22569. */
  22570. const oscSawtooth = ( t = time ) => t.fract();
  22571. /**
  22572. * Rotates the given uv coordinates around a center point
  22573. *
  22574. * @tsl
  22575. * @function
  22576. * @param {Node<vec2>} uv - The uv coordinates.
  22577. * @param {Node<float>} rotation - The rotation defined in radians.
  22578. * @param {Node<vec2>} center - The center of rotation
  22579. * @return {Node<vec2>} The rotated uv coordinates.
  22580. */
  22581. const rotateUV = /*@__PURE__*/ Fn( ( [ uv, rotation, center = vec2( 0.5 ) ] ) => {
  22582. return rotate( uv.sub( center ), rotation ).add( center );
  22583. } );
  22584. /**
  22585. * Applies a spherical warping effect to the given uv coordinates.
  22586. *
  22587. * @tsl
  22588. * @function
  22589. * @param {Node<vec2>} uv - The uv coordinates.
  22590. * @param {Node<float>} strength - The strength of the effect.
  22591. * @param {Node<vec2>} center - The center point
  22592. * @return {Node<vec2>} The updated uv coordinates.
  22593. */
  22594. const spherizeUV = /*@__PURE__*/ Fn( ( [ uv, strength, center = vec2( 0.5 ) ] ) => {
  22595. const delta = uv.sub( center );
  22596. const delta2 = delta.dot( delta );
  22597. const delta4 = delta2.mul( delta2 );
  22598. const deltaOffset = delta4.mul( strength );
  22599. return uv.add( delta.mul( deltaOffset ) );
  22600. } );
  22601. /**
  22602. * This can be used to achieve a billboarding behavior for flat meshes. That means they are
  22603. * oriented always towards the camera.
  22604. *
  22605. * ```js
  22606. * material.vertexNode = billboarding();
  22607. * ```
  22608. *
  22609. * @tsl
  22610. * @function
  22611. * @param {Object} config - The configuration object.
  22612. * @param {?Node<vec3>} [config.position=null] - Can be used to define the vertex positions in world space.
  22613. * @param {boolean} [config.horizontal=true] - Whether to follow the camera rotation horizontally or not.
  22614. * @param {boolean} [config.vertical=false] - Whether to follow the camera rotation vertically or not.
  22615. * @return {Node<vec3>} The updated vertex position in clip space.
  22616. */
  22617. const billboarding = /*@__PURE__*/ Fn( ( { position = null, horizontal = true, vertical = false } ) => {
  22618. let worldMatrix;
  22619. if ( position !== null ) {
  22620. worldMatrix = modelWorldMatrix.toVar();
  22621. worldMatrix[ 3 ][ 0 ] = position.x;
  22622. worldMatrix[ 3 ][ 1 ] = position.y;
  22623. worldMatrix[ 3 ][ 2 ] = position.z;
  22624. } else {
  22625. worldMatrix = modelWorldMatrix;
  22626. }
  22627. const modelViewMatrix = cameraViewMatrix.mul( worldMatrix );
  22628. if ( defined( horizontal ) ) {
  22629. modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length();
  22630. modelViewMatrix[ 0 ][ 1 ] = 0;
  22631. modelViewMatrix[ 0 ][ 2 ] = 0;
  22632. }
  22633. if ( defined( vertical ) ) {
  22634. modelViewMatrix[ 1 ][ 0 ] = 0;
  22635. modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length();
  22636. modelViewMatrix[ 1 ][ 2 ] = 0;
  22637. }
  22638. modelViewMatrix[ 2 ][ 0 ] = 0;
  22639. modelViewMatrix[ 2 ][ 1 ] = 0;
  22640. modelViewMatrix[ 2 ][ 2 ] = 1;
  22641. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  22642. } );
  22643. /**
  22644. * A special version of a screen uv function that involves a depth comparison
  22645. * when computing the final uvs. The function mitigates visual errors when
  22646. * using viewport texture nodes for refraction purposes. Without this function
  22647. * objects in front of a refractive surface might appear on the refractive surface
  22648. * which is incorrect.
  22649. *
  22650. * @tsl
  22651. * @function
  22652. * @param {?Node<vec2>} uv - Optional uv coordinates. By default `screenUV` is used.
  22653. * @return {Node<vec2>} The update uv coordinates.
  22654. */
  22655. const viewportSafeUV = /*@__PURE__*/ Fn( ( [ uv = null ] ) => {
  22656. const depth = linearDepth();
  22657. const depthDiff = linearDepth( viewportDepthTexture( uv ) ).sub( depth );
  22658. const finalUV = depthDiff.lessThan( 0 ).select( screenUV, uv );
  22659. return finalUV;
  22660. } );
  22661. /**
  22662. * Can be used to compute texture coordinates for animated sprite sheets.
  22663. *
  22664. * ```js
  22665. * const uvNode = spritesheetUV( vec2( 6, 6 ), uv(), time.mul( animationSpeed ) );
  22666. *
  22667. * material.colorNode = texture( spriteSheet, uvNode );
  22668. * ```
  22669. *
  22670. * @augments Node
  22671. */
  22672. class SpriteSheetUVNode extends Node {
  22673. static get type() {
  22674. return 'SpriteSheetUVNode';
  22675. }
  22676. /**
  22677. * Constructs a new sprite sheet uv node.
  22678. *
  22679. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  22680. * @param {Node<vec2>} [uvNode=uv()] - The uv node.
  22681. * @param {Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  22682. */
  22683. constructor( countNode, uvNode = uv$1(), frameNode = float( 0 ) ) {
  22684. super( 'vec2' );
  22685. /**
  22686. * The node that defines the number of sprites in the x and y direction (e.g 6x6).
  22687. *
  22688. * @type {Node<vec2>}
  22689. */
  22690. this.countNode = countNode;
  22691. /**
  22692. * The uv node.
  22693. *
  22694. * @type {Node<vec2>}
  22695. */
  22696. this.uvNode = uvNode;
  22697. /**
  22698. * The node that defines the current frame/sprite.
  22699. *
  22700. * @type {Node<float>}
  22701. */
  22702. this.frameNode = frameNode;
  22703. }
  22704. setup() {
  22705. const { frameNode, uvNode, countNode } = this;
  22706. const { width, height } = countNode;
  22707. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  22708. const column = frameNum.mod( width );
  22709. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  22710. const scale = countNode.reciprocal();
  22711. const uvFrameOffset = vec2( column, row );
  22712. return uvNode.add( uvFrameOffset ).mul( scale );
  22713. }
  22714. }
  22715. /**
  22716. * TSL function for creating a sprite sheet uv node.
  22717. *
  22718. * @tsl
  22719. * @function
  22720. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  22721. * @param {?Node<vec2>} [uvNode=uv()] - The uv node.
  22722. * @param {?Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  22723. * @returns {SpriteSheetUVNode}
  22724. */
  22725. const spritesheetUV = /*@__PURE__*/ nodeProxy( SpriteSheetUVNode ).setParameterLength( 3 );
  22726. /**
  22727. * TSL function for creating a triplanar textures node.
  22728. *
  22729. * Can be used for triplanar texture mapping.
  22730. *
  22731. * ```js
  22732. * material.colorNode = triplanarTexture( texture( diffuseMap ) );
  22733. * ```
  22734. *
  22735. * @tsl
  22736. * @function
  22737. * @param {Node} textureXNode - First texture node.
  22738. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  22739. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  22740. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  22741. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  22742. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  22743. * @returns {Node<vec4>}
  22744. */
  22745. const triplanarTextures = /*@__PURE__*/ Fn( ( [ textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ] ) => {
  22746. // Reference: https://github.com/keijiro/StandardTriplanar
  22747. // Blending factor of triplanar mapping
  22748. let bf = normalNode.abs().normalize();
  22749. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  22750. // Triplanar mapping
  22751. const tx = positionNode.yz.mul( scaleNode );
  22752. const ty = positionNode.zx.mul( scaleNode );
  22753. const tz = positionNode.xy.mul( scaleNode );
  22754. // Base color
  22755. const textureX = textureXNode.value;
  22756. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  22757. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  22758. const cx = texture( textureX, tx ).mul( bf.x );
  22759. const cy = texture( textureY, ty ).mul( bf.y );
  22760. const cz = texture( textureZ, tz ).mul( bf.z );
  22761. return add( cx, cy, cz );
  22762. } );
  22763. /**
  22764. * TSL function for creating a triplanar textures node.
  22765. *
  22766. * @tsl
  22767. * @function
  22768. * @param {Node} textureXNode - First texture node.
  22769. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  22770. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  22771. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  22772. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  22773. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  22774. * @returns {Node<vec4>}
  22775. */
  22776. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  22777. const _reflectorPlane = new Plane();
  22778. const _normal = new Vector3();
  22779. const _reflectorWorldPosition = new Vector3();
  22780. const _cameraWorldPosition = new Vector3();
  22781. const _rotationMatrix = new Matrix4();
  22782. const _lookAtPosition = new Vector3( 0, 0, -1 );
  22783. const clipPlane = new Vector4();
  22784. const _view = new Vector3();
  22785. const _target = new Vector3();
  22786. const _q = new Vector4();
  22787. const _size$2 = new Vector2();
  22788. const _defaultRT = new RenderTarget();
  22789. const _defaultUV = screenUV.flipX();
  22790. _defaultRT.depthTexture = new DepthTexture( 1, 1 );
  22791. let _inReflector = false;
  22792. /**
  22793. * This node can be used to implement mirror-like flat reflective surfaces.
  22794. *
  22795. * ```js
  22796. * const groundReflector = reflector();
  22797. * material.colorNode = groundReflector;
  22798. *
  22799. * const plane = new Mesh( geometry, material );
  22800. * plane.add( groundReflector.target );
  22801. * ```
  22802. *
  22803. * @augments TextureNode
  22804. */
  22805. class ReflectorNode extends TextureNode {
  22806. static get type() {
  22807. return 'ReflectorNode';
  22808. }
  22809. /**
  22810. * Constructs a new reflector node.
  22811. *
  22812. * @param {Object} [parameters={}] - An object holding configuration parameters.
  22813. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  22814. * @param {number} [parameters.resolution=1] - The resolution scale.
  22815. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  22816. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  22817. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  22818. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  22819. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  22820. */
  22821. constructor( parameters = {} ) {
  22822. super( parameters.defaultTexture || _defaultRT.texture, _defaultUV );
  22823. /**
  22824. * A reference to the internal reflector base node which holds the actual implementation.
  22825. *
  22826. * @private
  22827. * @type {ReflectorBaseNode}
  22828. * @default ReflectorBaseNode
  22829. */
  22830. this._reflectorBaseNode = parameters.reflector || new ReflectorBaseNode( this, parameters );
  22831. /**
  22832. * A reference to the internal depth node.
  22833. *
  22834. * @private
  22835. * @type {?Node}
  22836. * @default null
  22837. */
  22838. this._depthNode = null;
  22839. this.setUpdateMatrix( false );
  22840. }
  22841. /**
  22842. * A reference to the internal reflector node.
  22843. *
  22844. * @type {ReflectorBaseNode}
  22845. */
  22846. get reflector() {
  22847. return this._reflectorBaseNode;
  22848. }
  22849. /**
  22850. * A reference to 3D object the reflector is linked to.
  22851. *
  22852. * @type {Object3D}
  22853. */
  22854. get target() {
  22855. return this._reflectorBaseNode.target;
  22856. }
  22857. /**
  22858. * Returns a node representing the mirror's depth. That can be used
  22859. * to implement more advanced reflection effects like distance attenuation.
  22860. *
  22861. * @return {Node} The depth node.
  22862. */
  22863. getDepthNode() {
  22864. if ( this._depthNode === null ) {
  22865. if ( this._reflectorBaseNode.depth !== true ) {
  22866. throw new Error( 'THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ' );
  22867. }
  22868. this._depthNode = nodeObject( new ReflectorNode( {
  22869. defaultTexture: _defaultRT.depthTexture,
  22870. reflector: this._reflectorBaseNode
  22871. } ) );
  22872. }
  22873. return this._depthNode;
  22874. }
  22875. setup( builder ) {
  22876. // ignore if used in post-processing
  22877. if ( ! builder.object.isQuadMesh ) this._reflectorBaseNode.build( builder );
  22878. return super.setup( builder );
  22879. }
  22880. clone() {
  22881. const newNode = new this.constructor( this.reflectorNode );
  22882. newNode.uvNode = this.uvNode;
  22883. newNode.levelNode = this.levelNode;
  22884. newNode.biasNode = this.biasNode;
  22885. newNode.sampler = this.sampler;
  22886. newNode.depthNode = this.depthNode;
  22887. newNode.compareNode = this.compareNode;
  22888. newNode.gradNode = this.gradNode;
  22889. newNode._reflectorBaseNode = this._reflectorBaseNode;
  22890. return newNode;
  22891. }
  22892. /**
  22893. * Frees internal resources. Should be called when the node is no longer in use.
  22894. */
  22895. dispose() {
  22896. super.dispose();
  22897. this._reflectorBaseNode.dispose();
  22898. }
  22899. }
  22900. /**
  22901. * Holds the actual implementation of the reflector.
  22902. *
  22903. * TODO: Explain why `ReflectorBaseNode`. Originally the entire logic was implemented
  22904. * in `ReflectorNode`, see #29619.
  22905. *
  22906. * @private
  22907. * @augments Node
  22908. */
  22909. class ReflectorBaseNode extends Node {
  22910. static get type() {
  22911. return 'ReflectorBaseNode';
  22912. }
  22913. /**
  22914. * Constructs a new reflector base node.
  22915. *
  22916. * @param {TextureNode} textureNode - Represents the rendered reflections as a texture node.
  22917. * @param {Object} [parameters={}] - An object holding configuration parameters.
  22918. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  22919. * @param {number} [parameters.resolution=1] - The resolution scale.
  22920. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  22921. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  22922. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  22923. */
  22924. constructor( textureNode, parameters = {} ) {
  22925. super();
  22926. const {
  22927. target = new Object3D(),
  22928. resolution = 1,
  22929. generateMipmaps = false,
  22930. bounces = true,
  22931. depth = false
  22932. } = parameters;
  22933. /**
  22934. * Represents the rendered reflections as a texture node.
  22935. *
  22936. * @type {TextureNode}
  22937. */
  22938. this.textureNode = textureNode;
  22939. /**
  22940. * The 3D object the reflector is linked to.
  22941. *
  22942. * @type {Object3D}
  22943. * @default {new Object3D()}
  22944. */
  22945. this.target = target;
  22946. /**
  22947. * The resolution scale.
  22948. *
  22949. * @type {number}
  22950. * @default {1}
  22951. */
  22952. this.resolution = resolution;
  22953. /**
  22954. * Whether mipmaps should be generated or not.
  22955. *
  22956. * @type {boolean}
  22957. * @default {false}
  22958. */
  22959. this.generateMipmaps = generateMipmaps;
  22960. /**
  22961. * Whether reflectors can render other reflector nodes or not.
  22962. *
  22963. * @type {boolean}
  22964. * @default {true}
  22965. */
  22966. this.bounces = bounces;
  22967. /**
  22968. * Whether depth data should be generated or not.
  22969. *
  22970. * @type {boolean}
  22971. * @default {false}
  22972. */
  22973. this.depth = depth;
  22974. /**
  22975. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` when {@link ReflectorBaseNode#bounces}
  22976. * is `true`. Otherwise it's `NodeUpdateType.FRAME`.
  22977. *
  22978. * @type {string}
  22979. * @default 'render'
  22980. */
  22981. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  22982. /**
  22983. * Weak map for managing virtual cameras.
  22984. *
  22985. * @type {WeakMap<Camera, Camera>}
  22986. */
  22987. this.virtualCameras = new WeakMap();
  22988. /**
  22989. * Weak map for managing render targets.
  22990. *
  22991. * @type {Map<Camera, RenderTarget>}
  22992. */
  22993. this.renderTargets = new Map();
  22994. /**
  22995. * Force render even if reflector is facing away from camera.
  22996. *
  22997. * @type {boolean}
  22998. * @default {false}
  22999. */
  23000. this.forceUpdate = false;
  23001. /**
  23002. * Whether the reflector has been rendered or not.
  23003. *
  23004. * When the reflector is facing away from the camera,
  23005. * this flag is set to `false` and the texture will be empty(black).
  23006. *
  23007. * @type {boolean}
  23008. * @default {false}
  23009. */
  23010. this.hasOutput = false;
  23011. }
  23012. /**
  23013. * Updates the resolution of the internal render target.
  23014. *
  23015. * @private
  23016. * @param {RenderTarget} renderTarget - The render target to resize.
  23017. * @param {Renderer} renderer - The renderer that is used to determine the new size.
  23018. */
  23019. _updateResolution( renderTarget, renderer ) {
  23020. const resolution = this.resolution;
  23021. renderer.getDrawingBufferSize( _size$2 );
  23022. renderTarget.setSize( Math.round( _size$2.width * resolution ), Math.round( _size$2.height * resolution ) );
  23023. }
  23024. setup( builder ) {
  23025. this._updateResolution( _defaultRT, builder.renderer );
  23026. return super.setup( builder );
  23027. }
  23028. /**
  23029. * Frees internal resources. Should be called when the node is no longer in use.
  23030. */
  23031. dispose() {
  23032. super.dispose();
  23033. for ( const renderTarget of this.renderTargets.values() ) {
  23034. renderTarget.dispose();
  23035. }
  23036. }
  23037. /**
  23038. * Returns a virtual camera for the given camera. The virtual camera is used to
  23039. * render the scene from the reflector's view so correct reflections can be produced.
  23040. *
  23041. * @param {Camera} camera - The scene's camera.
  23042. * @return {Camera} The corresponding virtual camera.
  23043. */
  23044. getVirtualCamera( camera ) {
  23045. let virtualCamera = this.virtualCameras.get( camera );
  23046. if ( virtualCamera === undefined ) {
  23047. virtualCamera = camera.clone();
  23048. this.virtualCameras.set( camera, virtualCamera );
  23049. }
  23050. return virtualCamera;
  23051. }
  23052. /**
  23053. * Returns a render target for the given camera. The reflections are rendered
  23054. * into this render target.
  23055. *
  23056. * @param {Camera} camera - The scene's camera.
  23057. * @return {RenderTarget} The render target.
  23058. */
  23059. getRenderTarget( camera ) {
  23060. let renderTarget = this.renderTargets.get( camera );
  23061. if ( renderTarget === undefined ) {
  23062. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType } );
  23063. if ( this.generateMipmaps === true ) {
  23064. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  23065. renderTarget.texture.generateMipmaps = true;
  23066. }
  23067. if ( this.depth === true ) {
  23068. renderTarget.depthTexture = new DepthTexture();
  23069. }
  23070. this.renderTargets.set( camera, renderTarget );
  23071. }
  23072. return renderTarget;
  23073. }
  23074. updateBefore( frame ) {
  23075. if ( this.bounces === false && _inReflector ) return false;
  23076. _inReflector = true;
  23077. const { scene, camera, renderer, material } = frame;
  23078. const { target } = this;
  23079. const virtualCamera = this.getVirtualCamera( camera );
  23080. const renderTarget = this.getRenderTarget( virtualCamera );
  23081. renderer.getDrawingBufferSize( _size$2 );
  23082. this._updateResolution( renderTarget, renderer );
  23083. //
  23084. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  23085. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  23086. _rotationMatrix.extractRotation( target.matrixWorld );
  23087. _normal.set( 0, 0, 1 );
  23088. _normal.applyMatrix4( _rotationMatrix );
  23089. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  23090. // Avoid rendering when reflector is facing away unless forcing an update
  23091. const isFacingAway = _view.dot( _normal ) > 0;
  23092. let needsClear = false;
  23093. if ( isFacingAway === true && this.forceUpdate === false ) {
  23094. if ( this.hasOutput === false ) {
  23095. _inReflector = false;
  23096. return;
  23097. }
  23098. needsClear = true;
  23099. }
  23100. _view.reflect( _normal ).negate();
  23101. _view.add( _reflectorWorldPosition );
  23102. _rotationMatrix.extractRotation( camera.matrixWorld );
  23103. _lookAtPosition.set( 0, 0, -1 );
  23104. _lookAtPosition.applyMatrix4( _rotationMatrix );
  23105. _lookAtPosition.add( _cameraWorldPosition );
  23106. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  23107. _target.reflect( _normal ).negate();
  23108. _target.add( _reflectorWorldPosition );
  23109. //
  23110. virtualCamera.coordinateSystem = camera.coordinateSystem;
  23111. virtualCamera.position.copy( _view );
  23112. virtualCamera.up.set( 0, 1, 0 );
  23113. virtualCamera.up.applyMatrix4( _rotationMatrix );
  23114. virtualCamera.up.reflect( _normal );
  23115. virtualCamera.lookAt( _target );
  23116. virtualCamera.near = camera.near;
  23117. virtualCamera.far = camera.far;
  23118. virtualCamera.updateMatrixWorld();
  23119. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  23120. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  23121. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  23122. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  23123. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  23124. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  23125. const projectionMatrix = virtualCamera.projectionMatrix;
  23126. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  23127. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  23128. _q.z = -1;
  23129. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  23130. // Calculate the scaled plane vector
  23131. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  23132. const clipBias = 0;
  23133. // Replacing the third row of the projection matrix
  23134. projectionMatrix.elements[ 2 ] = clipPlane.x;
  23135. projectionMatrix.elements[ 6 ] = clipPlane.y;
  23136. projectionMatrix.elements[ 10 ] = ( renderer.coordinateSystem === WebGPUCoordinateSystem ) ? ( clipPlane.z - clipBias ) : ( clipPlane.z + 1.0 - clipBias );
  23137. projectionMatrix.elements[ 14 ] = clipPlane.w;
  23138. //
  23139. this.textureNode.value = renderTarget.texture;
  23140. if ( this.depth === true ) {
  23141. this.textureNode.getDepthNode().value = renderTarget.depthTexture;
  23142. }
  23143. material.visible = false;
  23144. const currentRenderTarget = renderer.getRenderTarget();
  23145. const currentMRT = renderer.getMRT();
  23146. const currentAutoClear = renderer.autoClear;
  23147. renderer.setMRT( null );
  23148. renderer.setRenderTarget( renderTarget );
  23149. renderer.autoClear = true;
  23150. if ( needsClear ) {
  23151. renderer.clear();
  23152. this.hasOutput = false;
  23153. } else {
  23154. renderer.render( scene, virtualCamera );
  23155. this.hasOutput = true;
  23156. }
  23157. renderer.setMRT( currentMRT );
  23158. renderer.setRenderTarget( currentRenderTarget );
  23159. renderer.autoClear = currentAutoClear;
  23160. material.visible = true;
  23161. _inReflector = false;
  23162. this.forceUpdate = false;
  23163. }
  23164. }
  23165. /**
  23166. * TSL function for creating a reflector node.
  23167. *
  23168. * @tsl
  23169. * @function
  23170. * @param {Object} [parameters={}] - An object holding configuration parameters.
  23171. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  23172. * @param {number} [parameters.resolution=1] - The resolution scale.
  23173. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  23174. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  23175. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  23176. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  23177. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  23178. * @returns {ReflectorNode}
  23179. */
  23180. const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) );
  23181. const _camera = /*@__PURE__*/ new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  23182. /**
  23183. * The purpose of this special geometry is to fill the entire viewport with a single triangle.
  23184. *
  23185. * Reference: {@link https://github.com/mrdoob/three.js/pull/21358}
  23186. *
  23187. * @private
  23188. * @augments BufferGeometry
  23189. */
  23190. class QuadGeometry extends BufferGeometry {
  23191. /**
  23192. * Constructs a new quad geometry.
  23193. *
  23194. * @param {boolean} [flipY=false] - Whether the uv coordinates should be flipped along the vertical axis or not.
  23195. */
  23196. constructor( flipY = false ) {
  23197. super();
  23198. const uv = flipY === false ? [ 0, -1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  23199. this.setAttribute( 'position', new Float32BufferAttribute( [ -1, 3, 0, -1, -1, 0, 3, -1, 0 ], 3 ) );
  23200. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  23201. }
  23202. }
  23203. const _geometry = /*@__PURE__*/ new QuadGeometry();
  23204. /**
  23205. * This module is a helper for passes which need to render a full
  23206. * screen effect which is quite common in context of post processing.
  23207. *
  23208. * The intended usage is to reuse a single quad mesh for rendering
  23209. * subsequent passes by just reassigning the `material` reference.
  23210. *
  23211. * Note: This module can only be used with `WebGPURenderer`.
  23212. *
  23213. * @augments Mesh
  23214. */
  23215. class QuadMesh extends Mesh {
  23216. /**
  23217. * Constructs a new quad mesh.
  23218. *
  23219. * @param {?Material} [material=null] - The material to render the quad mesh with.
  23220. */
  23221. constructor( material = null ) {
  23222. super( _geometry, material );
  23223. /**
  23224. * The camera to render the quad mesh with.
  23225. *
  23226. * @type {OrthographicCamera}
  23227. * @readonly
  23228. */
  23229. this.camera = _camera;
  23230. /**
  23231. * This flag can be used for type testing.
  23232. *
  23233. * @type {boolean}
  23234. * @readonly
  23235. * @default true
  23236. */
  23237. this.isQuadMesh = true;
  23238. }
  23239. /**
  23240. * Async version of `render()`.
  23241. *
  23242. * @async
  23243. * @param {Renderer} renderer - The renderer.
  23244. * @return {Promise} A Promise that resolves when the render has been finished.
  23245. */
  23246. async renderAsync( renderer ) {
  23247. return renderer.renderAsync( this, _camera );
  23248. }
  23249. /**
  23250. * Renders the quad mesh
  23251. *
  23252. * @param {Renderer} renderer - The renderer.
  23253. */
  23254. render( renderer ) {
  23255. renderer.render( this, _camera );
  23256. }
  23257. }
  23258. const _size$1 = /*@__PURE__*/ new Vector2();
  23259. /**
  23260. * `RTTNode` takes another node and uses it with a `QuadMesh` to render into a texture (RTT).
  23261. * This module is especially relevant in context of post processing where certain nodes require
  23262. * texture input for their effects. With the helper function `convertToTexture()` which is based
  23263. * on this module, the node system can automatically ensure texture input if required.
  23264. *
  23265. * @augments TextureNode
  23266. */
  23267. class RTTNode extends TextureNode {
  23268. static get type() {
  23269. return 'RTTNode';
  23270. }
  23271. /**
  23272. * Constructs a new RTT node.
  23273. *
  23274. * @param {Node} node - The node to render a texture with.
  23275. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  23276. * @param {?number} [height=null] - The height of the internal render target.
  23277. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  23278. */
  23279. constructor( node, width = null, height = null, options = { type: HalfFloatType } ) {
  23280. const renderTarget = new RenderTarget( width, height, options );
  23281. super( renderTarget.texture, uv$1() );
  23282. /**
  23283. * This flag can be used for type testing.
  23284. *
  23285. * @type {boolean}
  23286. * @readonly
  23287. * @default true
  23288. */
  23289. this.isRTTNode = true;
  23290. /**
  23291. * The node to render a texture with.
  23292. *
  23293. * @type {Node}
  23294. */
  23295. this.node = node;
  23296. /**
  23297. * The width of the internal render target.
  23298. * If not width is applied, the render target is automatically resized.
  23299. *
  23300. * @type {?number}
  23301. * @default null
  23302. */
  23303. this.width = width;
  23304. /**
  23305. * The height of the internal render target.
  23306. *
  23307. * @type {?number}
  23308. * @default null
  23309. */
  23310. this.height = height;
  23311. /**
  23312. * The pixel ratio
  23313. *
  23314. * @type {number}
  23315. * @default 1
  23316. */
  23317. this.pixelRatio = 1;
  23318. /**
  23319. * The render target
  23320. *
  23321. * @type {RenderTarget}
  23322. */
  23323. this.renderTarget = renderTarget;
  23324. /**
  23325. * Whether the texture requires an update or not.
  23326. *
  23327. * @type {boolean}
  23328. * @default true
  23329. */
  23330. this.textureNeedsUpdate = true;
  23331. /**
  23332. * Whether the texture should automatically be updated or not.
  23333. *
  23334. * @type {boolean}
  23335. * @default true
  23336. */
  23337. this.autoUpdate = true;
  23338. /**
  23339. * The node which is used with the quad mesh for RTT.
  23340. *
  23341. * @private
  23342. * @type {Node}
  23343. * @default null
  23344. */
  23345. this._rttNode = null;
  23346. /**
  23347. * The internal quad mesh for RTT.
  23348. *
  23349. * @private
  23350. * @type {QuadMesh}
  23351. */
  23352. this._quadMesh = new QuadMesh( new NodeMaterial() );
  23353. /**
  23354. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  23355. * the texture once per render in its {@link RTTNode#updateBefore} method.
  23356. *
  23357. * @type {string}
  23358. * @default 'render'
  23359. */
  23360. this.updateBeforeType = NodeUpdateType.RENDER;
  23361. }
  23362. /**
  23363. * Whether the internal render target should automatically be resized or not.
  23364. *
  23365. * @type {boolean}
  23366. * @readonly
  23367. * @default true
  23368. */
  23369. get autoResize() {
  23370. return this.width === null;
  23371. }
  23372. setup( builder ) {
  23373. this._rttNode = this.node.context( builder.getSharedContext() );
  23374. this._quadMesh.material.name = 'RTT';
  23375. this._quadMesh.material.needsUpdate = true;
  23376. return super.setup( builder );
  23377. }
  23378. /**
  23379. * Sets the size of the internal render target
  23380. *
  23381. * @param {number} width - The width to set.
  23382. * @param {number} height - The width to set.
  23383. */
  23384. setSize( width, height ) {
  23385. this.width = width;
  23386. this.height = height;
  23387. const effectiveWidth = width * this.pixelRatio;
  23388. const effectiveHeight = height * this.pixelRatio;
  23389. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  23390. this.textureNeedsUpdate = true;
  23391. }
  23392. /**
  23393. * Sets the pixel ratio. This will also resize the render target.
  23394. *
  23395. * @param {number} pixelRatio - The pixel ratio to set.
  23396. */
  23397. setPixelRatio( pixelRatio ) {
  23398. this.pixelRatio = pixelRatio;
  23399. this.setSize( this.width, this.height );
  23400. }
  23401. updateBefore( { renderer } ) {
  23402. if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return;
  23403. this.textureNeedsUpdate = false;
  23404. //
  23405. if ( this.autoResize === true ) {
  23406. const pixelRatio = renderer.getPixelRatio();
  23407. const size = renderer.getSize( _size$1 );
  23408. const effectiveWidth = size.width * pixelRatio;
  23409. const effectiveHeight = size.height * pixelRatio;
  23410. if ( effectiveWidth !== this.renderTarget.width || effectiveHeight !== this.renderTarget.height ) {
  23411. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  23412. this.textureNeedsUpdate = true;
  23413. }
  23414. }
  23415. //
  23416. this._quadMesh.material.fragmentNode = this._rttNode;
  23417. //
  23418. const currentRenderTarget = renderer.getRenderTarget();
  23419. renderer.setRenderTarget( this.renderTarget );
  23420. this._quadMesh.render( renderer );
  23421. renderer.setRenderTarget( currentRenderTarget );
  23422. }
  23423. clone() {
  23424. const newNode = new TextureNode( this.value, this.uvNode, this.levelNode );
  23425. newNode.sampler = this.sampler;
  23426. newNode.referenceNode = this;
  23427. return newNode;
  23428. }
  23429. }
  23430. /**
  23431. * TSL function for creating a RTT node.
  23432. *
  23433. * @tsl
  23434. * @function
  23435. * @param {Node} node - The node to render a texture with.
  23436. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  23437. * @param {?number} [height=null] - The height of the internal render target.
  23438. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  23439. * @returns {RTTNode}
  23440. */
  23441. const rtt = ( node, ...params ) => nodeObject( new RTTNode( nodeObject( node ), ...params ) );
  23442. /**
  23443. * TSL function for converting nodes to textures nodes.
  23444. *
  23445. * @tsl
  23446. * @function
  23447. * @param {Node} node - The node to render a texture with.
  23448. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  23449. * @param {?number} [height=null] - The height of the internal render target.
  23450. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  23451. * @returns {RTTNode}
  23452. */
  23453. const convertToTexture = ( node, ...params ) => {
  23454. if ( node.isTextureNode ) return node;
  23455. if ( node.isPassNode ) return node.getTextureNode();
  23456. return rtt( node, ...params );
  23457. };
  23458. /**
  23459. * Computes a position in view space based on a fragment's screen position expressed as uv coordinates, the fragments
  23460. * depth value and the camera's inverse projection matrix.
  23461. *
  23462. * @tsl
  23463. * @function
  23464. * @param {Node<vec2>} screenPosition - The fragment's screen position expressed as uv coordinates.
  23465. * @param {Node<float>} depth - The fragment's depth value.
  23466. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  23467. * @return {Node<vec3>} The fragments position in view space.
  23468. */
  23469. const getViewPosition = /*@__PURE__*/ Fn( ( [ screenPosition, depth, projectionMatrixInverse ], builder ) => {
  23470. let clipSpacePosition;
  23471. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  23472. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  23473. clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  23474. } else {
  23475. clipSpacePosition = vec4( vec3( screenPosition.x, screenPosition.y.oneMinus(), depth ).mul( 2.0 ).sub( 1.0 ), 1.0 );
  23476. }
  23477. const viewSpacePosition = vec4( projectionMatrixInverse.mul( clipSpacePosition ) );
  23478. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  23479. } );
  23480. /**
  23481. * Computes a screen position expressed as uv coordinates based on a fragment's position in view space
  23482. * and the camera's projection matrix
  23483. *
  23484. * @tsl
  23485. * @function
  23486. * @param {Node<vec3>} viewPosition - The fragments position in view space.
  23487. * @param {Node<mat4>} projectionMatrix - The camera's projection matrix.
  23488. * @return {Node<vec2>} The fragment's screen position expressed as uv coordinates.
  23489. */
  23490. const getScreenPosition = /*@__PURE__*/ Fn( ( [ viewPosition, projectionMatrix ] ) => {
  23491. const sampleClipPos = projectionMatrix.mul( vec4( viewPosition, 1.0 ) );
  23492. const sampleUv = sampleClipPos.xy.div( sampleClipPos.w ).mul( 0.5 ).add( 0.5 ).toVar();
  23493. return vec2( sampleUv.x, sampleUv.y.oneMinus() );
  23494. } );
  23495. /**
  23496. * Computes a normal vector based on depth data. Can be used as a fallback when no normal render
  23497. * target is available or if flat surface normals are required.
  23498. *
  23499. * @tsl
  23500. * @function
  23501. * @param {Node<vec2>} uv - The texture coordinate.
  23502. * @param {DepthTexture} depthTexture - The depth texture.
  23503. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  23504. * @return {Node<vec3>} The computed normal vector.
  23505. */
  23506. const getNormalFromDepth = /*@__PURE__*/ Fn( ( [ uv, depthTexture, projectionMatrixInverse ] ) => {
  23507. const size = textureSize( textureLoad( depthTexture ) );
  23508. const p = ivec2( uv.mul( size ) ).toVar();
  23509. const c0 = textureLoad( depthTexture, p ).toVar();
  23510. const l2 = textureLoad( depthTexture, p.sub( ivec2( 2, 0 ) ) ).toVar();
  23511. const l1 = textureLoad( depthTexture, p.sub( ivec2( 1, 0 ) ) ).toVar();
  23512. const r1 = textureLoad( depthTexture, p.add( ivec2( 1, 0 ) ) ).toVar();
  23513. const r2 = textureLoad( depthTexture, p.add( ivec2( 2, 0 ) ) ).toVar();
  23514. const b2 = textureLoad( depthTexture, p.add( ivec2( 0, 2 ) ) ).toVar();
  23515. const b1 = textureLoad( depthTexture, p.add( ivec2( 0, 1 ) ) ).toVar();
  23516. const t1 = textureLoad( depthTexture, p.sub( ivec2( 0, 1 ) ) ).toVar();
  23517. const t2 = textureLoad( depthTexture, p.sub( ivec2( 0, 2 ) ) ).toVar();
  23518. const dl = abs( sub( float( 2 ).mul( l1 ).sub( l2 ), c0 ) ).toVar();
  23519. const dr = abs( sub( float( 2 ).mul( r1 ).sub( r2 ), c0 ) ).toVar();
  23520. const db = abs( sub( float( 2 ).mul( b1 ).sub( b2 ), c0 ) ).toVar();
  23521. const dt = abs( sub( float( 2 ).mul( t1 ).sub( t2 ), c0 ) ).toVar();
  23522. const ce = getViewPosition( uv, c0, projectionMatrixInverse ).toVar();
  23523. 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 ) ) );
  23524. 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 ) ) );
  23525. return normalize( cross( dpdx, dpdy ) );
  23526. } );
  23527. /**
  23528. * Class representing a node that samples a value using a provided callback function.
  23529. *
  23530. * @extends Node
  23531. */
  23532. class SampleNode extends Node {
  23533. /**
  23534. * Returns the type of the node.
  23535. *
  23536. * @type {string}
  23537. * @readonly
  23538. * @static
  23539. */
  23540. static get type() {
  23541. return 'SampleNode';
  23542. }
  23543. /**
  23544. * Creates an instance of SampleNode.
  23545. *
  23546. * @param {Function} callback - The function to be called when sampling. Should accept a UV node and return a value.
  23547. */
  23548. constructor( callback ) {
  23549. super();
  23550. this.callback = callback;
  23551. /**
  23552. * This flag can be used for type testing.
  23553. *
  23554. * @type {boolean}
  23555. * @readonly
  23556. * @default true
  23557. */
  23558. this.isSampleNode = true;
  23559. }
  23560. /**
  23561. * Sets up the node by sampling with the default UV accessor.
  23562. *
  23563. * @returns {Node} The result of the callback function when called with the UV node.
  23564. */
  23565. setup() {
  23566. return this.sample( uv$1() );
  23567. }
  23568. /**
  23569. * Calls the callback function with the provided UV node.
  23570. *
  23571. * @param {Node<vec2>} uv - The UV node or value to be passed to the callback.
  23572. * @returns {Node} The result of the callback function.
  23573. */
  23574. sample( uv ) {
  23575. return this.callback( uv );
  23576. }
  23577. }
  23578. /**
  23579. * Helper function to create a SampleNode wrapped as a node object.
  23580. *
  23581. * @function
  23582. * @param {Function} callback - The function to be called when sampling. Should accept a UV node and return a value.
  23583. * @returns {SampleNode} The created SampleNode instance wrapped as a node object.
  23584. */
  23585. const sample = ( callback ) => nodeObject( new SampleNode( callback ) );
  23586. /**
  23587. * This special type of instanced buffer attribute is intended for compute shaders.
  23588. * In earlier three.js versions it was only possible to update attribute data
  23589. * on the CPU via JavaScript and then upload the data to the GPU. With the
  23590. * new material system and renderer it is now possible to use compute shaders
  23591. * to compute the data for an attribute more efficiently on the GPU.
  23592. *
  23593. * The idea is to create an instance of this class and provide it as an input
  23594. * to {@link StorageBufferNode}.
  23595. *
  23596. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  23597. *
  23598. * @augments InstancedBufferAttribute
  23599. */
  23600. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  23601. /**
  23602. * Constructs a new storage instanced buffer attribute.
  23603. *
  23604. * @param {number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  23605. * The subsequent parameters are then obsolete.
  23606. * @param {number} itemSize - The item size.
  23607. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  23608. */
  23609. constructor( count, itemSize, typeClass = Float32Array ) {
  23610. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  23611. super( array, itemSize );
  23612. /**
  23613. * This flag can be used for type testing.
  23614. *
  23615. * @type {boolean}
  23616. * @readonly
  23617. * @default true
  23618. */
  23619. this.isStorageInstancedBufferAttribute = true;
  23620. }
  23621. }
  23622. /**
  23623. * This special type of buffer attribute is intended for compute shaders.
  23624. * In earlier three.js versions it was only possible to update attribute data
  23625. * on the CPU via JavaScript and then upload the data to the GPU. With the
  23626. * new material system and renderer it is now possible to use compute shaders
  23627. * to compute the data for an attribute more efficiently on the GPU.
  23628. *
  23629. * The idea is to create an instance of this class and provide it as an input
  23630. * to {@link StorageBufferNode}.
  23631. *
  23632. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  23633. *
  23634. * @augments BufferAttribute
  23635. */
  23636. class StorageBufferAttribute extends BufferAttribute {
  23637. /**
  23638. * Constructs a new storage buffer attribute.
  23639. *
  23640. * @param {number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  23641. * The subsequent parameters are then obsolete.
  23642. * @param {number} itemSize - The item size.
  23643. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  23644. */
  23645. constructor( count, itemSize, typeClass = Float32Array ) {
  23646. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  23647. super( array, itemSize );
  23648. /**
  23649. * This flag can be used for type testing.
  23650. *
  23651. * @type {boolean}
  23652. * @readonly
  23653. * @default true
  23654. */
  23655. this.isStorageBufferAttribute = true;
  23656. }
  23657. }
  23658. /**
  23659. * TSL function for creating a storage buffer node with a configured `StorageBufferAttribute`.
  23660. *
  23661. * @tsl
  23662. * @function
  23663. * @param {number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  23664. * @param {string|Struct} [type='float'] - The data type.
  23665. * @returns {StorageBufferNode}
  23666. */
  23667. const attributeArray = ( count, type = 'float' ) => {
  23668. let itemSize, typedArray;
  23669. if ( type.isStruct === true ) {
  23670. itemSize = type.layout.getLength();
  23671. typedArray = getTypedArrayFromType( 'float' );
  23672. } else {
  23673. itemSize = getLengthFromType( type );
  23674. typedArray = getTypedArrayFromType( type );
  23675. }
  23676. const buffer = new StorageBufferAttribute( count, itemSize, typedArray );
  23677. const node = storage( buffer, type, count );
  23678. return node;
  23679. };
  23680. /**
  23681. * TSL function for creating a storage buffer node with a configured `StorageInstancedBufferAttribute`.
  23682. *
  23683. * @tsl
  23684. * @function
  23685. * @param {number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  23686. * @param {string|Struct} [type='float'] - The data type.
  23687. * @returns {StorageBufferNode}
  23688. */
  23689. const instancedArray = ( count, type = 'float' ) => {
  23690. let itemSize, typedArray;
  23691. if ( type.isStruct === true ) {
  23692. itemSize = type.layout.getLength();
  23693. typedArray = getTypedArrayFromType( 'float' );
  23694. } else {
  23695. itemSize = getLengthFromType( type );
  23696. typedArray = getTypedArrayFromType( type );
  23697. }
  23698. const buffer = new StorageInstancedBufferAttribute( count, itemSize, typedArray );
  23699. const node = storage( buffer, type, count );
  23700. return node;
  23701. };
  23702. /**
  23703. * A node for representing the uv coordinates of points.
  23704. *
  23705. * Can only be used with a WebGL backend. In WebGPU, point
  23706. * primitives always have the size of one pixel and can thus
  23707. * can't be used as sprite-like objects that display textures.
  23708. *
  23709. * @augments Node
  23710. */
  23711. class PointUVNode extends Node {
  23712. static get type() {
  23713. return 'PointUVNode';
  23714. }
  23715. /**
  23716. * Constructs a new point uv node.
  23717. */
  23718. constructor() {
  23719. super( 'vec2' );
  23720. /**
  23721. * This flag can be used for type testing.
  23722. *
  23723. * @type {boolean}
  23724. * @readonly
  23725. * @default true
  23726. */
  23727. this.isPointUVNode = true;
  23728. }
  23729. generate( /*builder*/ ) {
  23730. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  23731. }
  23732. }
  23733. /**
  23734. * TSL object that represents the uv coordinates of points.
  23735. *
  23736. * @tsl
  23737. * @type {PointUVNode}
  23738. */
  23739. const pointUV = /*@__PURE__*/ nodeImmutable( PointUVNode );
  23740. const _e1 = /*@__PURE__*/ new Euler();
  23741. const _m1 = /*@__PURE__*/ new Matrix4();
  23742. /**
  23743. * This module allows access to a collection of scene properties. The following predefined TSL objects
  23744. * are available for easier use:
  23745. *
  23746. * - `backgroundBlurriness`: A node that represents the scene's background blurriness.
  23747. * - `backgroundIntensity`: A node that represents the scene's background intensity.
  23748. * - `backgroundRotation`: A node that represents the scene's background rotation.
  23749. *
  23750. * @augments Node
  23751. */
  23752. class SceneNode extends Node {
  23753. static get type() {
  23754. return 'SceneNode';
  23755. }
  23756. /**
  23757. * Constructs a new scene node.
  23758. *
  23759. * @param {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')} scope - The scope defines the type of scene property that is accessed.
  23760. * @param {?Scene} [scene=null] - A reference to the scene.
  23761. */
  23762. constructor( scope = SceneNode.BACKGROUND_BLURRINESS, scene = null ) {
  23763. super();
  23764. /**
  23765. * The scope defines the type of scene property that is accessed.
  23766. *
  23767. * @type {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')}
  23768. */
  23769. this.scope = scope;
  23770. /**
  23771. * A reference to the scene that is going to be accessed.
  23772. *
  23773. * @type {?Scene}
  23774. * @default null
  23775. */
  23776. this.scene = scene;
  23777. }
  23778. /**
  23779. * Depending on the scope, the method returns a different type of node that represents
  23780. * the respective scene property.
  23781. *
  23782. * @param {NodeBuilder} builder - The current node builder.
  23783. * @return {Node} The output node.
  23784. */
  23785. setup( builder ) {
  23786. const scope = this.scope;
  23787. const scene = this.scene !== null ? this.scene : builder.scene;
  23788. let output;
  23789. if ( scope === SceneNode.BACKGROUND_BLURRINESS ) {
  23790. output = reference( 'backgroundBlurriness', 'float', scene );
  23791. } else if ( scope === SceneNode.BACKGROUND_INTENSITY ) {
  23792. output = reference( 'backgroundIntensity', 'float', scene );
  23793. } else if ( scope === SceneNode.BACKGROUND_ROTATION ) {
  23794. output = uniform( 'mat4' ).label( 'backgroundRotation' ).setGroup( renderGroup ).onRenderUpdate( () => {
  23795. const background = scene.background;
  23796. if ( background !== null && background.isTexture && background.mapping !== UVMapping ) {
  23797. _e1.copy( scene.backgroundRotation );
  23798. // accommodate left-handed frame
  23799. _e1.x *= -1; _e1.y *= -1; _e1.z *= -1;
  23800. _m1.makeRotationFromEuler( _e1 );
  23801. } else {
  23802. _m1.identity();
  23803. }
  23804. return _m1;
  23805. } );
  23806. } else {
  23807. console.error( 'THREE.SceneNode: Unknown scope:', scope );
  23808. }
  23809. return output;
  23810. }
  23811. }
  23812. SceneNode.BACKGROUND_BLURRINESS = 'backgroundBlurriness';
  23813. SceneNode.BACKGROUND_INTENSITY = 'backgroundIntensity';
  23814. SceneNode.BACKGROUND_ROTATION = 'backgroundRotation';
  23815. /**
  23816. * TSL object that represents the scene's background blurriness.
  23817. *
  23818. * @tsl
  23819. * @type {SceneNode}
  23820. */
  23821. const backgroundBlurriness = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_BLURRINESS );
  23822. /**
  23823. * TSL object that represents the scene's background intensity.
  23824. *
  23825. * @tsl
  23826. * @type {SceneNode}
  23827. */
  23828. const backgroundIntensity = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_INTENSITY );
  23829. /**
  23830. * TSL object that represents the scene's background rotation.
  23831. *
  23832. * @tsl
  23833. * @type {SceneNode}
  23834. */
  23835. const backgroundRotation = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_ROTATION );
  23836. /**
  23837. * This special version of a texture node can be used to
  23838. * write data into a storage texture with a compute shader.
  23839. *
  23840. * ```js
  23841. * const storageTexture = new THREE.StorageTexture( width, height );
  23842. *
  23843. * const computeTexture = Fn( ( { storageTexture } ) => {
  23844. *
  23845. * const posX = instanceIndex.mod( width );
  23846. * const posY = instanceIndex.div( width );
  23847. * const indexUV = uvec2( posX, posY );
  23848. *
  23849. * // generate RGB values
  23850. *
  23851. * const r = 1;
  23852. * const g = 1;
  23853. * const b = 1;
  23854. *
  23855. * textureStore( storageTexture, indexUV, vec4( r, g, b, 1 ) ).toWriteOnly();
  23856. *
  23857. * } );
  23858. *
  23859. * const computeNode = computeTexture( { storageTexture } ).compute( width * height );
  23860. * renderer.computeAsync( computeNode );
  23861. * ```
  23862. *
  23863. * This node can only be used with a WebGPU backend.
  23864. *
  23865. * @augments TextureNode
  23866. */
  23867. class StorageTextureNode extends TextureNode {
  23868. static get type() {
  23869. return 'StorageTextureNode';
  23870. }
  23871. /**
  23872. * Constructs a new storage texture node.
  23873. *
  23874. * @param {StorageTexture} value - The storage texture.
  23875. * @param {Node<vec2|vec3>} uvNode - The uv node.
  23876. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  23877. */
  23878. constructor( value, uvNode, storeNode = null ) {
  23879. super( value, uvNode );
  23880. /**
  23881. * The value node that should be stored in the texture.
  23882. *
  23883. * @type {?Node}
  23884. * @default null
  23885. */
  23886. this.storeNode = storeNode;
  23887. /**
  23888. * This flag can be used for type testing.
  23889. *
  23890. * @type {boolean}
  23891. * @readonly
  23892. * @default true
  23893. */
  23894. this.isStorageTextureNode = true;
  23895. /**
  23896. * The access type of the texture node.
  23897. *
  23898. * @type {string}
  23899. * @default 'writeOnly'
  23900. */
  23901. this.access = NodeAccess.WRITE_ONLY;
  23902. }
  23903. /**
  23904. * Overwrites the default implementation to return a fixed value `'storageTexture'`.
  23905. *
  23906. * @param {NodeBuilder} builder - The current node builder.
  23907. * @return {string} The input type.
  23908. */
  23909. getInputType( /*builder*/ ) {
  23910. return 'storageTexture';
  23911. }
  23912. setup( builder ) {
  23913. super.setup( builder );
  23914. const properties = builder.getNodeProperties( this );
  23915. properties.storeNode = this.storeNode;
  23916. return properties;
  23917. }
  23918. /**
  23919. * Defines the node access.
  23920. *
  23921. * @param {string} value - The node access.
  23922. * @return {StorageTextureNode} A reference to this node.
  23923. */
  23924. setAccess( value ) {
  23925. this.access = value;
  23926. return this;
  23927. }
  23928. /**
  23929. * Generates the code snippet of the storage node. If no `storeNode`
  23930. * is defined, the texture node is generated as normal texture.
  23931. *
  23932. * @param {NodeBuilder} builder - The current node builder.
  23933. * @param {string} output - The current output.
  23934. * @return {string} The generated code snippet.
  23935. */
  23936. generate( builder, output ) {
  23937. let snippet;
  23938. if ( this.storeNode !== null ) {
  23939. snippet = this.generateStore( builder );
  23940. } else {
  23941. snippet = super.generate( builder, output );
  23942. }
  23943. return snippet;
  23944. }
  23945. /**
  23946. * Convenience method for configuring a read/write node access.
  23947. *
  23948. * @return {StorageTextureNode} A reference to this node.
  23949. */
  23950. toReadWrite() {
  23951. return this.setAccess( NodeAccess.READ_WRITE );
  23952. }
  23953. /**
  23954. * Convenience method for configuring a read-only node access.
  23955. *
  23956. * @return {StorageTextureNode} A reference to this node.
  23957. */
  23958. toReadOnly() {
  23959. return this.setAccess( NodeAccess.READ_ONLY );
  23960. }
  23961. /**
  23962. * Convenience method for configuring a write-only node access.
  23963. *
  23964. * @return {StorageTextureNode} A reference to this node.
  23965. */
  23966. toWriteOnly() {
  23967. return this.setAccess( NodeAccess.WRITE_ONLY );
  23968. }
  23969. /**
  23970. * Generates the code snippet of the storage texture node.
  23971. *
  23972. * @param {NodeBuilder} builder - The current node builder.
  23973. */
  23974. generateStore( builder ) {
  23975. const properties = builder.getNodeProperties( this );
  23976. const { uvNode, storeNode, depthNode } = properties;
  23977. const textureProperty = super.generate( builder, 'property' );
  23978. const uvSnippet = uvNode.build( builder, this.value.is3DTexture === true ? 'uvec3' : 'uvec2' );
  23979. const storeSnippet = storeNode.build( builder, 'vec4' );
  23980. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  23981. const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, depthSnippet, storeSnippet );
  23982. builder.addLineFlowCode( snippet, this );
  23983. }
  23984. clone() {
  23985. const newNode = super.clone();
  23986. newNode.storeNode = this.storeNode;
  23987. return newNode;
  23988. }
  23989. }
  23990. /**
  23991. * TSL function for creating a storage texture node.
  23992. *
  23993. * @tsl
  23994. * @function
  23995. * @param {StorageTexture} value - The storage texture.
  23996. * @param {?Node<vec2|vec3>} uvNode - The uv node.
  23997. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  23998. * @returns {StorageTextureNode}
  23999. */
  24000. const storageTexture = /*@__PURE__*/ nodeProxy( StorageTextureNode ).setParameterLength( 1, 3 );
  24001. /**
  24002. * TODO: Explain difference to `storageTexture()`.
  24003. *
  24004. * @tsl
  24005. * @function
  24006. * @param {StorageTexture} value - The storage texture.
  24007. * @param {Node<vec2|vec3>} uvNode - The uv node.
  24008. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  24009. * @returns {StorageTextureNode}
  24010. */
  24011. const textureStore = ( value, uvNode, storeNode ) => {
  24012. const node = storageTexture( value, uvNode, storeNode );
  24013. if ( storeNode !== null ) node.toStack();
  24014. return node;
  24015. };
  24016. const normal = Fn( ( { texture, uv } ) => {
  24017. const epsilon = 0.0001;
  24018. const ret = vec3().toVar();
  24019. If( uv.x.lessThan( epsilon ), () => {
  24020. ret.assign( vec3( 1, 0, 0 ) );
  24021. } ).ElseIf( uv.y.lessThan( epsilon ), () => {
  24022. ret.assign( vec3( 0, 1, 0 ) );
  24023. } ).ElseIf( uv.z.lessThan( epsilon ), () => {
  24024. ret.assign( vec3( 0, 0, 1 ) );
  24025. } ).ElseIf( uv.x.greaterThan( 1 - epsilon ), () => {
  24026. ret.assign( vec3( -1, 0, 0 ) );
  24027. } ).ElseIf( uv.y.greaterThan( 1 - epsilon ), () => {
  24028. ret.assign( vec3( 0, -1, 0 ) );
  24029. } ).ElseIf( uv.z.greaterThan( 1 - epsilon ), () => {
  24030. ret.assign( vec3( 0, 0, -1 ) );
  24031. } ).Else( () => {
  24032. const step = 0.01;
  24033. const x = texture.sample( uv.add( vec3( - step, 0.0, 0.0 ) ) ).r.sub( texture.sample( uv.add( vec3( step, 0.0, 0.0 ) ) ).r );
  24034. const y = texture.sample( uv.add( vec3( 0.0, - step, 0.0 ) ) ).r.sub( texture.sample( uv.add( vec3( 0.0, step, 0.0 ) ) ).r );
  24035. const z = texture.sample( uv.add( vec3( 0.0, 0.0, - step ) ) ).r.sub( texture.sample( uv.add( vec3( 0.0, 0.0, step ) ) ).r );
  24036. ret.assign( vec3( x, y, z ) );
  24037. } );
  24038. return ret.normalize();
  24039. } );
  24040. /**
  24041. * This type of uniform node represents a 3D texture.
  24042. *
  24043. * @augments TextureNode
  24044. */
  24045. class Texture3DNode extends TextureNode {
  24046. static get type() {
  24047. return 'Texture3DNode';
  24048. }
  24049. /**
  24050. * Constructs a new 3D texture node.
  24051. *
  24052. * @param {Data3DTexture} value - The 3D texture.
  24053. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  24054. * @param {?Node<int>} [levelNode=null] - The level node.
  24055. */
  24056. constructor( value, uvNode = null, levelNode = null ) {
  24057. super( value, uvNode, levelNode );
  24058. /**
  24059. * This flag can be used for type testing.
  24060. *
  24061. * @type {boolean}
  24062. * @readonly
  24063. * @default true
  24064. */
  24065. this.isTexture3DNode = true;
  24066. }
  24067. /**
  24068. * Overwrites the default implementation to return a fixed value `'texture3D'`.
  24069. *
  24070. * @param {NodeBuilder} builder - The current node builder.
  24071. * @return {string} The input type.
  24072. */
  24073. getInputType( /*builder*/ ) {
  24074. return 'texture3D';
  24075. }
  24076. /**
  24077. * Returns a default uv node which is in context of 3D textures a three-dimensional
  24078. * uv node.
  24079. *
  24080. * @return {Node<vec3>} The default uv node.
  24081. */
  24082. getDefaultUV() {
  24083. return vec3( 0.5, 0.5, 0.5 );
  24084. }
  24085. /**
  24086. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  24087. * for 3D textures. The uv transformation matrix is not applied to 3D textures.
  24088. *
  24089. * @param {boolean} value - The update toggle.
  24090. */
  24091. setUpdateMatrix( /*value*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  24092. /**
  24093. * Overwrites the default implementation to return the unmodified uv node.
  24094. *
  24095. * @param {NodeBuilder} builder - The current node builder.
  24096. * @param {Node} uvNode - The uv node to setup.
  24097. * @return {Node} The unmodified uv node.
  24098. */
  24099. setupUV( builder, uvNode ) {
  24100. const texture = this.value;
  24101. if ( builder.isFlipY() && ( texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true ) ) {
  24102. if ( this.sampler ) {
  24103. uvNode = uvNode.flipY();
  24104. } else {
  24105. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  24106. }
  24107. }
  24108. return uvNode;
  24109. }
  24110. /**
  24111. * Generates the uv code snippet.
  24112. *
  24113. * @param {NodeBuilder} builder - The current node builder.
  24114. * @param {Node} uvNode - The uv node to generate code for.
  24115. * @return {string} The generated code snippet.
  24116. */
  24117. generateUV( builder, uvNode ) {
  24118. return uvNode.build( builder, 'vec3' );
  24119. }
  24120. /**
  24121. * TODO.
  24122. *
  24123. * @param {Node<vec3>} uvNode - The uv node .
  24124. * @return {Node<vec3>} TODO.
  24125. */
  24126. normal( uvNode ) {
  24127. return normal( { texture: this, uv: uvNode } );
  24128. }
  24129. }
  24130. /**
  24131. * TSL function for creating a 3D texture node.
  24132. *
  24133. * @tsl
  24134. * @function
  24135. * @param {Data3DTexture} value - The 3D texture.
  24136. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  24137. * @param {?Node<int>} [levelNode=null] - The level node.
  24138. * @returns {Texture3DNode}
  24139. */
  24140. const texture3D = /*@__PURE__*/ nodeProxy( Texture3DNode ).setParameterLength( 1, 3 );
  24141. /**
  24142. * A special type of reference node that allows to link values in
  24143. * `userData` fields to node objects.
  24144. * ```js
  24145. * sprite.userData.rotation = 1; // stores individual rotation per sprite
  24146. *
  24147. * const material = new THREE.SpriteNodeMaterial();
  24148. * material.rotationNode = userData( 'rotation', 'float' );
  24149. * ```
  24150. * Since `UserDataNode` is extended from {@link ReferenceNode}, the node value
  24151. * will automatically be updated when the `rotation` user data field changes.
  24152. *
  24153. * @augments ReferenceNode
  24154. */
  24155. class UserDataNode extends ReferenceNode {
  24156. static get type() {
  24157. return 'UserDataNode';
  24158. }
  24159. /**
  24160. * Constructs a new user data node.
  24161. *
  24162. * @param {string} property - The property name that should be referenced by the node.
  24163. * @param {string} inputType - The node data type of the reference.
  24164. * @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.
  24165. */
  24166. constructor( property, inputType, userData = null ) {
  24167. super( property, inputType, userData );
  24168. /**
  24169. * A reference to the `userData` object. If not provided, the `userData`
  24170. * property of the 3D object that uses the node material is evaluated.
  24171. *
  24172. * @type {?Object}
  24173. * @default null
  24174. */
  24175. this.userData = userData;
  24176. }
  24177. /**
  24178. * Overwritten to make sure {@link ReferenceNode#reference} points to the correct
  24179. * `userData` field.
  24180. *
  24181. * @param {(NodeFrame|NodeBuilder)} state - The current state to evaluate.
  24182. * @return {Object} A reference to the `userData` field.
  24183. */
  24184. updateReference( state ) {
  24185. this.reference = this.userData !== null ? this.userData : state.object.userData;
  24186. return this.reference;
  24187. }
  24188. }
  24189. /**
  24190. * TSL function for creating a user data node.
  24191. *
  24192. * @tsl
  24193. * @function
  24194. * @param {string} name - The property name that should be referenced by the node.
  24195. * @param {string} inputType - The node data type of the reference.
  24196. * @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.
  24197. * @returns {UserDataNode}
  24198. */
  24199. const userData = ( name, inputType, userData ) => nodeObject( new UserDataNode( name, inputType, userData ) );
  24200. const _objectData = new WeakMap();
  24201. /**
  24202. * A node for representing motion or velocity vectors. Foundation
  24203. * for advanced post processing effects like motion blur or TRAA.
  24204. *
  24205. * The node keeps track of the model, view and projection matrices
  24206. * of the previous frame and uses them to compute offsets in NDC space.
  24207. * These offsets represent the final velocity.
  24208. *
  24209. * @augments TempNode
  24210. */
  24211. class VelocityNode extends TempNode {
  24212. static get type() {
  24213. return 'VelocityNode';
  24214. }
  24215. /**
  24216. * Constructs a new vertex color node.
  24217. */
  24218. constructor() {
  24219. super( 'vec2' );
  24220. /**
  24221. * The current projection matrix.
  24222. *
  24223. * @type {?Matrix4}
  24224. * @default null
  24225. */
  24226. this.projectionMatrix = null;
  24227. /**
  24228. * Overwritten since velocity nodes are updated per object.
  24229. *
  24230. * @type {string}
  24231. * @default 'object'
  24232. */
  24233. this.updateType = NodeUpdateType.OBJECT;
  24234. /**
  24235. * Overwritten since velocity nodes save data after the update.
  24236. *
  24237. * @type {string}
  24238. * @default 'object'
  24239. */
  24240. this.updateAfterType = NodeUpdateType.OBJECT;
  24241. /**
  24242. * Uniform node representing the previous model matrix in world space.
  24243. *
  24244. * @type {UniformNode<mat4>}
  24245. * @default null
  24246. */
  24247. this.previousModelWorldMatrix = uniform( new Matrix4() );
  24248. /**
  24249. * Uniform node representing the previous projection matrix.
  24250. *
  24251. * @type {UniformNode<mat4>}
  24252. * @default null
  24253. */
  24254. this.previousProjectionMatrix = uniform( new Matrix4() ).setGroup( renderGroup );
  24255. /**
  24256. * Uniform node representing the previous view matrix.
  24257. *
  24258. * @type {UniformNode<mat4>}
  24259. * @default null
  24260. */
  24261. this.previousCameraViewMatrix = uniform( new Matrix4() );
  24262. }
  24263. /**
  24264. * Sets the given projection matrix.
  24265. *
  24266. * @param {Matrix4} projectionMatrix - The projection matrix to set.
  24267. */
  24268. setProjectionMatrix( projectionMatrix ) {
  24269. this.projectionMatrix = projectionMatrix;
  24270. }
  24271. /**
  24272. * Updates velocity specific uniforms.
  24273. *
  24274. * @param {NodeFrame} frame - A reference to the current node frame.
  24275. */
  24276. update( { frameId, camera, object } ) {
  24277. const previousModelMatrix = getPreviousMatrix( object );
  24278. this.previousModelWorldMatrix.value.copy( previousModelMatrix );
  24279. //
  24280. const cameraData = getData( camera );
  24281. if ( cameraData.frameId !== frameId ) {
  24282. cameraData.frameId = frameId;
  24283. if ( cameraData.previousProjectionMatrix === undefined ) {
  24284. cameraData.previousProjectionMatrix = new Matrix4();
  24285. cameraData.previousCameraViewMatrix = new Matrix4();
  24286. cameraData.currentProjectionMatrix = new Matrix4();
  24287. cameraData.currentCameraViewMatrix = new Matrix4();
  24288. cameraData.previousProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  24289. cameraData.previousCameraViewMatrix.copy( camera.matrixWorldInverse );
  24290. } else {
  24291. cameraData.previousProjectionMatrix.copy( cameraData.currentProjectionMatrix );
  24292. cameraData.previousCameraViewMatrix.copy( cameraData.currentCameraViewMatrix );
  24293. }
  24294. cameraData.currentProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  24295. cameraData.currentCameraViewMatrix.copy( camera.matrixWorldInverse );
  24296. this.previousProjectionMatrix.value.copy( cameraData.previousProjectionMatrix );
  24297. this.previousCameraViewMatrix.value.copy( cameraData.previousCameraViewMatrix );
  24298. }
  24299. }
  24300. /**
  24301. * Overwritten to updated velocity specific uniforms.
  24302. *
  24303. * @param {NodeFrame} frame - A reference to the current node frame.
  24304. */
  24305. updateAfter( { object } ) {
  24306. getPreviousMatrix( object ).copy( object.matrixWorld );
  24307. }
  24308. /**
  24309. * Implements the velocity computation based on the previous and current vertex data.
  24310. *
  24311. * @param {NodeBuilder} builder - A reference to the current node builder.
  24312. * @return {Node<vec2>} The motion vector.
  24313. */
  24314. setup( /*builder*/ ) {
  24315. const projectionMatrix = ( this.projectionMatrix === null ) ? cameraProjectionMatrix : uniform( this.projectionMatrix );
  24316. const previousModelViewMatrix = this.previousCameraViewMatrix.mul( this.previousModelWorldMatrix );
  24317. const clipPositionCurrent = projectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  24318. const clipPositionPrevious = this.previousProjectionMatrix.mul( previousModelViewMatrix ).mul( positionPrevious );
  24319. const ndcPositionCurrent = clipPositionCurrent.xy.div( clipPositionCurrent.w );
  24320. const ndcPositionPrevious = clipPositionPrevious.xy.div( clipPositionPrevious.w );
  24321. const velocity = sub( ndcPositionCurrent, ndcPositionPrevious );
  24322. return velocity;
  24323. }
  24324. }
  24325. function getData( object ) {
  24326. let objectData = _objectData.get( object );
  24327. if ( objectData === undefined ) {
  24328. objectData = {};
  24329. _objectData.set( object, objectData );
  24330. }
  24331. return objectData;
  24332. }
  24333. function getPreviousMatrix( object, index = 0 ) {
  24334. const objectData = getData( object );
  24335. let matrix = objectData[ index ];
  24336. if ( matrix === undefined ) {
  24337. objectData[ index ] = matrix = new Matrix4();
  24338. objectData[ index ].copy( object.matrixWorld );
  24339. }
  24340. return matrix;
  24341. }
  24342. /**
  24343. * TSL object that represents the velocity of a render pass.
  24344. *
  24345. * @tsl
  24346. * @type {VelocityNode}
  24347. */
  24348. const velocity = /*@__PURE__*/ nodeImmutable( VelocityNode );
  24349. /**
  24350. * Computes a grayscale value for the given RGB color value.
  24351. *
  24352. * @tsl
  24353. * @function
  24354. * @param {Node<vec3>} color - The color value to compute the grayscale for.
  24355. * @return {Node<vec3>} The grayscale color.
  24356. */
  24357. const grayscale = /*@__PURE__*/ Fn( ( [ color ] ) => {
  24358. return luminance( color.rgb );
  24359. } );
  24360. /**
  24361. * Super-saturates or desaturates the given RGB color.
  24362. *
  24363. * @tsl
  24364. * @function
  24365. * @param {Node<vec3>} color - The input color.
  24366. * @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.
  24367. * @return {Node<vec3>} The saturated color.
  24368. */
  24369. const saturation = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  24370. return adjustment.mix( luminance( color.rgb ), color.rgb );
  24371. } );
  24372. /**
  24373. * Selectively enhance the intensity of less saturated RGB colors. Can result
  24374. * in a more natural and visually appealing image with enhanced color depth
  24375. * compared to {@link ColorAdjustment#saturation}.
  24376. *
  24377. * @tsl
  24378. * @function
  24379. * @param {Node<vec3>} color - The input color.
  24380. * @param {Node<float>} [adjustment=1] - Controls the intensity of the vibrance effect.
  24381. * @return {Node<vec3>} The updated color.
  24382. */
  24383. const vibrance = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  24384. const average = add( color.r, color.g, color.b ).div( 3.0 );
  24385. const mx = color.r.max( color.g.max( color.b ) );
  24386. const amt = mx.sub( average ).mul( adjustment ).mul( -3 );
  24387. return mix( color.rgb, mx, amt );
  24388. } );
  24389. /**
  24390. * Updates the hue component of the given RGB color while preserving its luminance and saturation.
  24391. *
  24392. * @tsl
  24393. * @function
  24394. * @param {Node<vec3>} color - The input color.
  24395. * @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.
  24396. * @return {Node<vec3>} The updated color.
  24397. */
  24398. const hue = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  24399. const k = vec3( 0.57735, 0.57735, 0.57735 );
  24400. const cosAngle = adjustment.cos();
  24401. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) );
  24402. } );
  24403. /**
  24404. * Computes the luminance for the given RGB color value.
  24405. *
  24406. * @tsl
  24407. * @function
  24408. * @param {Node<vec3>} color - The color value to compute the luminance for.
  24409. * @param {?Node<vec3>} luminanceCoefficients - The luminance coefficients. By default predefined values of the current working color space are used.
  24410. * @return {Node<vec3>} The luminance.
  24411. */
  24412. const luminance = (
  24413. color,
  24414. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3() ) )
  24415. ) => dot( color, luminanceCoefficients );
  24416. /**
  24417. * Color Decision List (CDL) v1.2
  24418. *
  24419. * Compact representation of color grading information, defined by slope, offset, power, and
  24420. * saturation. The CDL should be typically be given input in a log space (such as LogC, ACEScc,
  24421. * or AgX Log), and will return output in the same space. Output may require clamping >=0.
  24422. *
  24423. * @tsl
  24424. * @function
  24425. * @param {Node<vec4>} color Input (-Infinity < input < +Infinity)
  24426. * @param {Node<vec3>} slope Slope (0 ≤ slope < +Infinity)
  24427. * @param {Node<vec3>} offset Offset (-Infinity < offset < +Infinity; typically -1 < offset < 1)
  24428. * @param {Node<vec3>} power Power (0 < power < +Infinity)
  24429. * @param {Node<float>} saturation Saturation (0 ≤ saturation < +Infinity; typically 0 ≤ saturation < 4)
  24430. * @param {Node<vec3>} luminanceCoefficients Luminance coefficients for saturation term, typically Rec. 709
  24431. * @return {Node<vec4>} Output, -Infinity < output < +Infinity
  24432. *
  24433. * References:
  24434. * - ASC CDL v1.2
  24435. * - {@link https://blender.stackexchange.com/a/55239/43930}
  24436. * - {@link https://docs.acescentral.com/specifications/acescc/}
  24437. */
  24438. const cdl = /*@__PURE__*/ Fn( ( [
  24439. color,
  24440. slope = vec3( 1 ),
  24441. offset = vec3( 0 ),
  24442. power = vec3( 1 ),
  24443. saturation = float( 1 ),
  24444. // ASC CDL v1.2 explicitly requires Rec. 709 luminance coefficients.
  24445. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3(), LinearSRGBColorSpace ) )
  24446. ] ) => {
  24447. // NOTE: The ASC CDL v1.2 defines a [0, 1] clamp on the slope+offset term, and another on the
  24448. // saturation term. Per the ACEScc specification and Filament, limits may be omitted to support
  24449. // values outside [0, 1], requiring a workaround for negative values in the power expression.
  24450. const luma = color.rgb.dot( vec3( luminanceCoefficients ) );
  24451. const v = max$1( color.rgb.mul( slope ).add( offset ), 0.0 ).toVar();
  24452. const pv = v.pow( power ).toVar();
  24453. If( v.r.greaterThan( 0.0 ), () => { v.r.assign( pv.r ); } ); // eslint-disable-line
  24454. If( v.g.greaterThan( 0.0 ), () => { v.g.assign( pv.g ); } ); // eslint-disable-line
  24455. If( v.b.greaterThan( 0.0 ), () => { v.b.assign( pv.b ); } ); // eslint-disable-line
  24456. v.assign( luma.add( v.sub( luma ).mul( saturation ) ) );
  24457. return vec4( v.rgb, color.a );
  24458. } );
  24459. /**
  24460. * Represents a posterize effect which reduces the number of colors
  24461. * in an image, resulting in a more blocky and stylized appearance.
  24462. *
  24463. * @augments TempNode
  24464. */
  24465. class PosterizeNode extends TempNode {
  24466. static get type() {
  24467. return 'PosterizeNode';
  24468. }
  24469. /**
  24470. * Constructs a new posterize node.
  24471. *
  24472. * @param {Node} sourceNode - The input color.
  24473. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  24474. */
  24475. constructor( sourceNode, stepsNode ) {
  24476. super();
  24477. /**
  24478. * The input color.
  24479. *
  24480. * @type {Node}
  24481. */
  24482. this.sourceNode = sourceNode;
  24483. /**
  24484. * Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  24485. *
  24486. * @type {Node}
  24487. */
  24488. this.stepsNode = stepsNode;
  24489. }
  24490. setup() {
  24491. const { sourceNode, stepsNode } = this;
  24492. return sourceNode.mul( stepsNode ).floor().div( stepsNode );
  24493. }
  24494. }
  24495. /**
  24496. * TSL function for creating a posterize node.
  24497. *
  24498. * @tsl
  24499. * @function
  24500. * @param {Node} sourceNode - The input color.
  24501. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  24502. * @returns {PosterizeNode}
  24503. */
  24504. const posterize = /*@__PURE__*/ nodeProxy( PosterizeNode ).setParameterLength( 2 );
  24505. const _size = /*@__PURE__*/ new Vector2();
  24506. /**
  24507. * Represents the texture of a pass node.
  24508. *
  24509. * @augments TextureNode
  24510. */
  24511. class PassTextureNode extends TextureNode {
  24512. static get type() {
  24513. return 'PassTextureNode';
  24514. }
  24515. /**
  24516. * Constructs a new pass texture node.
  24517. *
  24518. * @param {PassNode} passNode - The pass node.
  24519. * @param {Texture} texture - The output texture.
  24520. */
  24521. constructor( passNode, texture ) {
  24522. super( texture );
  24523. /**
  24524. * A reference to the pass node.
  24525. *
  24526. * @type {PassNode}
  24527. */
  24528. this.passNode = passNode;
  24529. this.setUpdateMatrix( false );
  24530. }
  24531. setup( builder ) {
  24532. this.passNode.build( builder );
  24533. return super.setup( builder );
  24534. }
  24535. clone() {
  24536. return new this.constructor( this.passNode, this.value );
  24537. }
  24538. }
  24539. /**
  24540. * An extension of `PassTextureNode` which allows to manage more than one
  24541. * internal texture. Relevant for the `getPreviousTexture()` related API.
  24542. *
  24543. * @augments PassTextureNode
  24544. */
  24545. class PassMultipleTextureNode extends PassTextureNode {
  24546. static get type() {
  24547. return 'PassMultipleTextureNode';
  24548. }
  24549. /**
  24550. * Constructs a new pass texture node.
  24551. *
  24552. * @param {PassNode} passNode - The pass node.
  24553. * @param {string} textureName - The output texture name.
  24554. * @param {boolean} [previousTexture=false] - Whether previous frame data should be used or not.
  24555. */
  24556. constructor( passNode, textureName, previousTexture = false ) {
  24557. // null is passed to the super call since this class does not
  24558. // use an external texture for rendering pass data into. Instead
  24559. // the texture is managed by the pass node itself
  24560. super( passNode, null );
  24561. /**
  24562. * The output texture name.
  24563. *
  24564. * @type {string}
  24565. */
  24566. this.textureName = textureName;
  24567. /**
  24568. * Whether previous frame data should be used or not.
  24569. *
  24570. * @type {boolean}
  24571. */
  24572. this.previousTexture = previousTexture;
  24573. }
  24574. /**
  24575. * Updates the texture reference of this node.
  24576. */
  24577. updateTexture() {
  24578. this.value = this.previousTexture ? this.passNode.getPreviousTexture( this.textureName ) : this.passNode.getTexture( this.textureName );
  24579. }
  24580. setup( builder ) {
  24581. this.updateTexture();
  24582. return super.setup( builder );
  24583. }
  24584. clone() {
  24585. const newNode = new this.constructor( this.passNode, this.textureName, this.previousTexture );
  24586. newNode.uvNode = this.uvNode;
  24587. newNode.levelNode = this.levelNode;
  24588. newNode.biasNode = this.biasNode;
  24589. newNode.sampler = this.sampler;
  24590. newNode.depthNode = this.depthNode;
  24591. newNode.compareNode = this.compareNode;
  24592. newNode.gradNode = this.gradNode;
  24593. return newNode;
  24594. }
  24595. }
  24596. /**
  24597. * Represents a render pass (sometimes called beauty pass) in context of post processing.
  24598. * This pass produces a render for the given scene and camera and can provide multiple outputs
  24599. * via MRT for further processing.
  24600. *
  24601. * ```js
  24602. * const postProcessing = new PostProcessing( renderer );
  24603. *
  24604. * const scenePass = pass( scene, camera );
  24605. *
  24606. * postProcessing.outputNode = scenePass;
  24607. * ```
  24608. *
  24609. * @augments TempNode
  24610. */
  24611. class PassNode extends TempNode {
  24612. static get type() {
  24613. return 'PassNode';
  24614. }
  24615. /**
  24616. * Constructs a new pass node.
  24617. *
  24618. * @param {('color'|'depth')} scope - The scope of the pass. The scope determines whether the node outputs color or depth.
  24619. * @param {Scene} scene - A reference to the scene.
  24620. * @param {Camera} camera - A reference to the camera.
  24621. * @param {Object} options - Options for the internal render target.
  24622. */
  24623. constructor( scope, scene, camera, options = {} ) {
  24624. super( 'vec4' );
  24625. /**
  24626. * The scope of the pass. The scope determines whether the node outputs color or depth.
  24627. *
  24628. * @type {('color'|'depth')}
  24629. */
  24630. this.scope = scope;
  24631. /**
  24632. * A reference to the scene.
  24633. *
  24634. * @type {Scene}
  24635. */
  24636. this.scene = scene;
  24637. /**
  24638. * A reference to the camera.
  24639. *
  24640. * @type {Camera}
  24641. */
  24642. this.camera = camera;
  24643. /**
  24644. * Options for the internal render target.
  24645. *
  24646. * @type {Object}
  24647. */
  24648. this.options = options;
  24649. /**
  24650. * The pass's pixel ratio. Will be kept automatically kept in sync with the renderer's pixel ratio.
  24651. *
  24652. * @private
  24653. * @type {number}
  24654. * @default 1
  24655. */
  24656. this._pixelRatio = 1;
  24657. /**
  24658. * The pass's pixel width. Will be kept automatically kept in sync with the renderer's width.
  24659. * @private
  24660. * @type {number}
  24661. * @default 1
  24662. */
  24663. this._width = 1;
  24664. /**
  24665. * The pass's pixel height. Will be kept automatically kept in sync with the renderer's height.
  24666. * @private
  24667. * @type {number}
  24668. * @default 1
  24669. */
  24670. this._height = 1;
  24671. const depthTexture = new DepthTexture();
  24672. depthTexture.isRenderTargetTexture = true;
  24673. //depthTexture.type = FloatType;
  24674. depthTexture.name = 'depth';
  24675. const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType, ...options, } );
  24676. renderTarget.texture.name = 'output';
  24677. renderTarget.depthTexture = depthTexture;
  24678. /**
  24679. * The pass's render target.
  24680. *
  24681. * @type {RenderTarget}
  24682. */
  24683. this.renderTarget = renderTarget;
  24684. /**
  24685. * A dictionary holding the internal result textures.
  24686. *
  24687. * @private
  24688. * @type {Object<string, Texture>}
  24689. */
  24690. this._textures = {
  24691. output: renderTarget.texture,
  24692. depth: depthTexture
  24693. };
  24694. /**
  24695. * A dictionary holding the internal texture nodes.
  24696. *
  24697. * @private
  24698. * @type {Object<string, TextureNode>}
  24699. */
  24700. this._textureNodes = {};
  24701. /**
  24702. * A dictionary holding the internal depth nodes.
  24703. *
  24704. * @private
  24705. * @type {Object}
  24706. */
  24707. this._linearDepthNodes = {};
  24708. /**
  24709. * A dictionary holding the internal viewZ nodes.
  24710. *
  24711. * @private
  24712. * @type {Object}
  24713. */
  24714. this._viewZNodes = {};
  24715. /**
  24716. * A dictionary holding the texture data of the previous frame.
  24717. * Used for computing velocity/motion vectors.
  24718. *
  24719. * @private
  24720. * @type {Object<string, Texture>}
  24721. */
  24722. this._previousTextures = {};
  24723. /**
  24724. * A dictionary holding the texture nodes of the previous frame.
  24725. * Used for computing velocity/motion vectors.
  24726. *
  24727. * @private
  24728. * @type {Object<string, TextureNode>}
  24729. */
  24730. this._previousTextureNodes = {};
  24731. /**
  24732. * The `near` property of the camera as a uniform.
  24733. *
  24734. * @private
  24735. * @type {UniformNode}
  24736. */
  24737. this._cameraNear = uniform( 0 );
  24738. /**
  24739. * The `far` property of the camera as a uniform.
  24740. *
  24741. * @private
  24742. * @type {UniformNode}
  24743. */
  24744. this._cameraFar = uniform( 0 );
  24745. /**
  24746. * A MRT node configuring the MRT settings.
  24747. *
  24748. * @private
  24749. * @type {?MRTNode}
  24750. * @default null
  24751. */
  24752. this._mrt = null;
  24753. /**
  24754. * Layer object for configuring the camera that is used
  24755. * to produce the pass.
  24756. *
  24757. * @private
  24758. * @type {?Layers}
  24759. * @default null
  24760. */
  24761. this._layers = null;
  24762. /**
  24763. * Scales the resolution of the internal render target.
  24764. *
  24765. * @private
  24766. * @type {number}
  24767. * @default 1
  24768. */
  24769. this._resolution = 1;
  24770. /**
  24771. * Custom viewport definition.
  24772. *
  24773. * @private
  24774. * @type {?Vector4}
  24775. * @default null
  24776. */
  24777. this._viewport = null;
  24778. /**
  24779. * Custom scissor definition.
  24780. *
  24781. * @private
  24782. * @type {?Vector4}
  24783. * @default null
  24784. */
  24785. this._scissor = null;
  24786. /**
  24787. * This flag can be used for type testing.
  24788. *
  24789. * @type {boolean}
  24790. * @readonly
  24791. * @default true
  24792. */
  24793. this.isPassNode = true;
  24794. /**
  24795. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  24796. * scene once per frame in its {@link PassNode#updateBefore} method.
  24797. *
  24798. * @type {string}
  24799. * @default 'frame'
  24800. */
  24801. this.updateBeforeType = NodeUpdateType.FRAME;
  24802. /**
  24803. * This flag is used for global cache.
  24804. *
  24805. * @type {boolean}
  24806. * @default true
  24807. */
  24808. this.global = true;
  24809. }
  24810. /**
  24811. * Sets the resolution for the pass.
  24812. * The resolution is a factor that is multiplied with the renderer's width and height.
  24813. *
  24814. * @param {number} resolution - The resolution to set. A value of `1` means full resolution.
  24815. * @return {PassNode} A reference to this pass.
  24816. */
  24817. setResolution( resolution ) {
  24818. this._resolution = resolution;
  24819. return this;
  24820. }
  24821. /**
  24822. * Gets the current resolution of the pass.
  24823. *
  24824. * @return {number} The current resolution. A value of `1` means full resolution.
  24825. */
  24826. getResolution() {
  24827. return this._resolution;
  24828. }
  24829. /**
  24830. * Sets the layer configuration that should be used when rendering the pass.
  24831. *
  24832. * @param {Layers} layers - The layers object to set.
  24833. * @return {PassNode} A reference to this pass.
  24834. */
  24835. setLayers( layers ) {
  24836. this._layers = layers;
  24837. return this;
  24838. }
  24839. /**
  24840. * Gets the current layer configuration of the pass.
  24841. *
  24842. * @return {?Layers} .
  24843. */
  24844. getLayers() {
  24845. return this._layers;
  24846. }
  24847. /**
  24848. * Sets the given MRT node to setup MRT for this pass.
  24849. *
  24850. * @param {MRTNode} mrt - The MRT object.
  24851. * @return {PassNode} A reference to this pass.
  24852. */
  24853. setMRT( mrt ) {
  24854. this._mrt = mrt;
  24855. return this;
  24856. }
  24857. /**
  24858. * Returns the current MRT node.
  24859. *
  24860. * @return {MRTNode} The current MRT node.
  24861. */
  24862. getMRT() {
  24863. return this._mrt;
  24864. }
  24865. /**
  24866. * Returns the texture for the given output name.
  24867. *
  24868. * @param {string} name - The output name to get the texture for.
  24869. * @return {Texture} The texture.
  24870. */
  24871. getTexture( name ) {
  24872. let texture = this._textures[ name ];
  24873. if ( texture === undefined ) {
  24874. const refTexture = this.renderTarget.texture;
  24875. texture = refTexture.clone();
  24876. texture.name = name;
  24877. this._textures[ name ] = texture;
  24878. this.renderTarget.textures.push( texture );
  24879. }
  24880. return texture;
  24881. }
  24882. /**
  24883. * Returns the texture holding the data of the previous frame for the given output name.
  24884. *
  24885. * @param {string} name - The output name to get the texture for.
  24886. * @return {Texture} The texture holding the data of the previous frame.
  24887. */
  24888. getPreviousTexture( name ) {
  24889. let texture = this._previousTextures[ name ];
  24890. if ( texture === undefined ) {
  24891. texture = this.getTexture( name ).clone();
  24892. this._previousTextures[ name ] = texture;
  24893. }
  24894. return texture;
  24895. }
  24896. /**
  24897. * Switches current and previous textures for the given output name.
  24898. *
  24899. * @param {string} name - The output name.
  24900. */
  24901. toggleTexture( name ) {
  24902. const prevTexture = this._previousTextures[ name ];
  24903. if ( prevTexture !== undefined ) {
  24904. const texture = this._textures[ name ];
  24905. const index = this.renderTarget.textures.indexOf( texture );
  24906. this.renderTarget.textures[ index ] = prevTexture;
  24907. this._textures[ name ] = prevTexture;
  24908. this._previousTextures[ name ] = texture;
  24909. this._textureNodes[ name ].updateTexture();
  24910. this._previousTextureNodes[ name ].updateTexture();
  24911. }
  24912. }
  24913. /**
  24914. * Returns the texture node for the given output name.
  24915. *
  24916. * @param {string} [name='output'] - The output name to get the texture node for.
  24917. * @return {TextureNode} The texture node.
  24918. */
  24919. getTextureNode( name = 'output' ) {
  24920. let textureNode = this._textureNodes[ name ];
  24921. if ( textureNode === undefined ) {
  24922. textureNode = nodeObject( new PassMultipleTextureNode( this, name ) );
  24923. textureNode.updateTexture();
  24924. this._textureNodes[ name ] = textureNode;
  24925. }
  24926. return textureNode;
  24927. }
  24928. /**
  24929. * Returns the previous texture node for the given output name.
  24930. *
  24931. * @param {string} [name='output'] - The output name to get the previous texture node for.
  24932. * @return {TextureNode} The previous texture node.
  24933. */
  24934. getPreviousTextureNode( name = 'output' ) {
  24935. let textureNode = this._previousTextureNodes[ name ];
  24936. if ( textureNode === undefined ) {
  24937. if ( this._textureNodes[ name ] === undefined ) this.getTextureNode( name );
  24938. textureNode = nodeObject( new PassMultipleTextureNode( this, name, true ) );
  24939. textureNode.updateTexture();
  24940. this._previousTextureNodes[ name ] = textureNode;
  24941. }
  24942. return textureNode;
  24943. }
  24944. /**
  24945. * Returns a viewZ node of this pass.
  24946. *
  24947. * @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.
  24948. * @return {Node} The viewZ node.
  24949. */
  24950. getViewZNode( name = 'depth' ) {
  24951. let viewZNode = this._viewZNodes[ name ];
  24952. if ( viewZNode === undefined ) {
  24953. const cameraNear = this._cameraNear;
  24954. const cameraFar = this._cameraFar;
  24955. this._viewZNodes[ name ] = viewZNode = perspectiveDepthToViewZ( this.getTextureNode( name ), cameraNear, cameraFar );
  24956. }
  24957. return viewZNode;
  24958. }
  24959. /**
  24960. * Returns a linear depth node of this pass.
  24961. *
  24962. * @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.
  24963. * @return {Node} The linear depth node.
  24964. */
  24965. getLinearDepthNode( name = 'depth' ) {
  24966. let linearDepthNode = this._linearDepthNodes[ name ];
  24967. if ( linearDepthNode === undefined ) {
  24968. const cameraNear = this._cameraNear;
  24969. const cameraFar = this._cameraFar;
  24970. const viewZNode = this.getViewZNode( name );
  24971. // TODO: just if ( builder.camera.isPerspectiveCamera )
  24972. this._linearDepthNodes[ name ] = linearDepthNode = viewZToOrthographicDepth( viewZNode, cameraNear, cameraFar );
  24973. }
  24974. return linearDepthNode;
  24975. }
  24976. setup( { renderer } ) {
  24977. this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples;
  24978. this.renderTarget.texture.type = renderer.getColorBufferType();
  24979. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  24980. }
  24981. updateBefore( frame ) {
  24982. const { renderer } = frame;
  24983. const { scene } = this;
  24984. let camera;
  24985. let pixelRatio;
  24986. const outputRenderTarget = renderer.getOutputRenderTarget();
  24987. if ( outputRenderTarget && outputRenderTarget.isXRRenderTarget === true ) {
  24988. pixelRatio = 1;
  24989. camera = renderer.xr.getCamera();
  24990. renderer.xr.updateCamera( camera );
  24991. _size.set( outputRenderTarget.width, outputRenderTarget.height );
  24992. } else {
  24993. camera = this.camera;
  24994. pixelRatio = renderer.getPixelRatio();
  24995. renderer.getSize( _size );
  24996. }
  24997. this._pixelRatio = pixelRatio;
  24998. this.setSize( _size.width, _size.height );
  24999. const currentRenderTarget = renderer.getRenderTarget();
  25000. const currentMRT = renderer.getMRT();
  25001. const currentMask = camera.layers.mask;
  25002. this._cameraNear.value = camera.near;
  25003. this._cameraFar.value = camera.far;
  25004. if ( this._layers !== null ) {
  25005. camera.layers.mask = this._layers.mask;
  25006. }
  25007. for ( const name in this._previousTextures ) {
  25008. this.toggleTexture( name );
  25009. }
  25010. renderer.setRenderTarget( this.renderTarget );
  25011. renderer.setMRT( this._mrt );
  25012. renderer.render( scene, camera );
  25013. renderer.setRenderTarget( currentRenderTarget );
  25014. renderer.setMRT( currentMRT );
  25015. camera.layers.mask = currentMask;
  25016. }
  25017. /**
  25018. * Sets the size of the pass's render target. Honors the pixel ratio.
  25019. *
  25020. * @param {number} width - The width to set.
  25021. * @param {number} height - The height to set.
  25022. */
  25023. setSize( width, height ) {
  25024. this._width = width;
  25025. this._height = height;
  25026. const effectiveWidth = this._width * this._pixelRatio * this._resolution;
  25027. const effectiveHeight = this._height * this._pixelRatio * this._resolution;
  25028. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  25029. if ( this._scissor !== null ) this.renderTarget.scissor.copy( this._scissor );
  25030. if ( this._viewport !== null ) this.renderTarget.viewport.copy( this._viewport );
  25031. }
  25032. /**
  25033. * This method allows to define the pass's scissor rectangle. By default, the scissor rectangle is kept
  25034. * in sync with the pass's dimensions. To reverse the process and use auto-sizing again, call the method
  25035. * with `null` as the single argument.
  25036. *
  25037. * @param {?(number | Vector4)} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  25038. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  25039. * @param {number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  25040. * @param {number} width - The width of the scissor box in logical pixel unit.
  25041. * @param {number} height - The height of the scissor box in logical pixel unit.
  25042. */
  25043. setScissor( x, y, width, height ) {
  25044. if ( x === null ) {
  25045. this._scissor = null;
  25046. } else {
  25047. if ( this._scissor === null ) this._scissor = new Vector4();
  25048. if ( x.isVector4 ) {
  25049. this._scissor.copy( x );
  25050. } else {
  25051. this._scissor.set( x, y, width, height );
  25052. }
  25053. this._scissor.multiplyScalar( this._pixelRatio * this._resolution ).floor();
  25054. }
  25055. }
  25056. /**
  25057. * This method allows to define the pass's viewport. By default, the viewport is kept in sync
  25058. * with the pass's dimensions. To reverse the process and use auto-sizing again, call the method
  25059. * with `null` as the single argument.
  25060. *
  25061. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  25062. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  25063. * @param {number} width - The width of the viewport in logical pixel unit.
  25064. * @param {number} height - The height of the viewport in logical pixel unit.
  25065. */
  25066. setViewport( x, y, width, height ) {
  25067. if ( x === null ) {
  25068. this._viewport = null;
  25069. } else {
  25070. if ( this._viewport === null ) this._viewport = new Vector4();
  25071. if ( x.isVector4 ) {
  25072. this._viewport.copy( x );
  25073. } else {
  25074. this._viewport.set( x, y, width, height );
  25075. }
  25076. this._viewport.multiplyScalar( this._pixelRatio * this._resolution ).floor();
  25077. }
  25078. }
  25079. /**
  25080. * Sets the pixel ratio the pass's render target and updates the size.
  25081. *
  25082. * @param {number} pixelRatio - The pixel ratio to set.
  25083. */
  25084. setPixelRatio( pixelRatio ) {
  25085. this._pixelRatio = pixelRatio;
  25086. this.setSize( this._width, this._height );
  25087. }
  25088. /**
  25089. * Frees internal resources. Should be called when the node is no longer in use.
  25090. */
  25091. dispose() {
  25092. this.renderTarget.dispose();
  25093. }
  25094. }
  25095. /**
  25096. * @static
  25097. * @type {'color'}
  25098. * @default 'color'
  25099. */
  25100. PassNode.COLOR = 'color';
  25101. /**
  25102. * @static
  25103. * @type {'depth'}
  25104. * @default 'depth'
  25105. */
  25106. PassNode.DEPTH = 'depth';
  25107. /**
  25108. * TSL function for creating a pass node.
  25109. *
  25110. * @tsl
  25111. * @function
  25112. * @param {Scene} scene - A reference to the scene.
  25113. * @param {Camera} camera - A reference to the camera.
  25114. * @param {Object} options - Options for the internal render target.
  25115. * @returns {PassNode}
  25116. */
  25117. const pass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera, options ) );
  25118. /**
  25119. * TSL function for creating a pass texture node.
  25120. *
  25121. * @tsl
  25122. * @function
  25123. * @param {PassNode} pass - The pass node.
  25124. * @param {Texture} texture - The output texture.
  25125. * @returns {PassTextureNode}
  25126. */
  25127. const passTexture = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) );
  25128. /**
  25129. * TSL function for creating a depth pass node.
  25130. *
  25131. * @tsl
  25132. * @function
  25133. * @param {Scene} scene - A reference to the scene.
  25134. * @param {Camera} camera - A reference to the camera.
  25135. * @param {Object} options - Options for the internal render target.
  25136. * @returns {PassNode}
  25137. */
  25138. const depthPass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera, options ) );
  25139. /**
  25140. * Represents a render pass for producing a toon outline effect on compatible objects.
  25141. * Only 3D objects with materials of type `MeshToonMaterial` and `MeshToonNodeMaterial`
  25142. * will receive the outline.
  25143. *
  25144. * ```js
  25145. * const postProcessing = new PostProcessing( renderer );
  25146. *
  25147. * const scenePass = toonOutlinePass( scene, camera );
  25148. *
  25149. * postProcessing.outputNode = scenePass;
  25150. * ```
  25151. * @augments PassNode
  25152. */
  25153. class ToonOutlinePassNode extends PassNode {
  25154. static get type() {
  25155. return 'ToonOutlinePassNode';
  25156. }
  25157. /**
  25158. * Constructs a new outline pass node.
  25159. *
  25160. * @param {Scene} scene - A reference to the scene.
  25161. * @param {Camera} camera - A reference to the camera.
  25162. * @param {Node} colorNode - Defines the outline's color.
  25163. * @param {Node} thicknessNode - Defines the outline's thickness.
  25164. * @param {Node} alphaNode - Defines the outline's alpha.
  25165. */
  25166. constructor( scene, camera, colorNode, thicknessNode, alphaNode ) {
  25167. super( PassNode.COLOR, scene, camera );
  25168. /**
  25169. * Defines the outline's color.
  25170. *
  25171. * @type {Node}
  25172. */
  25173. this.colorNode = colorNode;
  25174. /**
  25175. * Defines the outline's thickness.
  25176. *
  25177. * @type {Node}
  25178. */
  25179. this.thicknessNode = thicknessNode;
  25180. /**
  25181. * Defines the outline's alpha.
  25182. *
  25183. * @type {Node}
  25184. */
  25185. this.alphaNode = alphaNode;
  25186. /**
  25187. * An internal material cache.
  25188. *
  25189. * @private
  25190. * @type {WeakMap<Material, NodeMaterial>}
  25191. */
  25192. this._materialCache = new WeakMap();
  25193. }
  25194. updateBefore( frame ) {
  25195. const { renderer } = frame;
  25196. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  25197. renderer.setRenderObjectFunction( ( object, scene, camera, geometry, material, group, lightsNode, clippingContext ) => {
  25198. // only render outline for supported materials
  25199. if ( material.isMeshToonMaterial || material.isMeshToonNodeMaterial ) {
  25200. if ( material.wireframe === false ) {
  25201. const outlineMaterial = this._getOutlineMaterial( material );
  25202. renderer.renderObject( object, scene, camera, geometry, outlineMaterial, group, lightsNode, clippingContext );
  25203. }
  25204. }
  25205. // default
  25206. renderer.renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext );
  25207. } );
  25208. super.updateBefore( frame );
  25209. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  25210. }
  25211. /**
  25212. * Creates the material used for outline rendering.
  25213. *
  25214. * @private
  25215. * @return {NodeMaterial} The outline material.
  25216. */
  25217. _createMaterial() {
  25218. const material = new NodeMaterial();
  25219. material.isMeshToonOutlineMaterial = true;
  25220. material.name = 'Toon_Outline';
  25221. material.side = BackSide;
  25222. // vertex node
  25223. const outlineNormal = normalLocal.negate();
  25224. const mvp = cameraProjectionMatrix.mul( modelViewMatrix );
  25225. const ratio = float( 1.0 ); // TODO: support outline thickness ratio for each vertex
  25226. const pos = mvp.mul( vec4( positionLocal, 1.0 ) );
  25227. const pos2 = mvp.mul( vec4( positionLocal.add( outlineNormal ), 1.0 ) );
  25228. const norm = normalize( pos.sub( pos2 ) ); // NOTE: subtract pos2 from pos because BackSide objectNormal is negative
  25229. material.vertexNode = pos.add( norm.mul( this.thicknessNode ).mul( pos.w ).mul( ratio ) );
  25230. // color node
  25231. material.colorNode = vec4( this.colorNode, this.alphaNode );
  25232. return material;
  25233. }
  25234. /**
  25235. * For the given toon material, this method returns a corresponding
  25236. * outline material.
  25237. *
  25238. * @private
  25239. * @param {(MeshToonMaterial|MeshToonNodeMaterial)} originalMaterial - The toon material.
  25240. * @return {NodeMaterial} The outline material.
  25241. */
  25242. _getOutlineMaterial( originalMaterial ) {
  25243. let outlineMaterial = this._materialCache.get( originalMaterial );
  25244. if ( outlineMaterial === undefined ) {
  25245. outlineMaterial = this._createMaterial();
  25246. this._materialCache.set( originalMaterial, outlineMaterial );
  25247. }
  25248. return outlineMaterial;
  25249. }
  25250. }
  25251. /**
  25252. * TSL function for creating a toon outline pass node.
  25253. *
  25254. * @tsl
  25255. * @function
  25256. * @param {Scene} scene - A reference to the scene.
  25257. * @param {Camera} camera - A reference to the camera.
  25258. * @param {Color} color - Defines the outline's color.
  25259. * @param {number} [thickness=0.003] - Defines the outline's thickness.
  25260. * @param {number} [alpha=1] - Defines the outline's alpha.
  25261. * @returns {ToonOutlinePassNode}
  25262. */
  25263. 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 ) ) );
  25264. /**
  25265. * Linear tone mapping, exposure only.
  25266. *
  25267. * @tsl
  25268. * @function
  25269. * @param {Node<vec3>} color - The color that should be tone mapped.
  25270. * @param {Node<float>} exposure - The exposure.
  25271. * @return {Node<vec3>} The tone mapped color.
  25272. */
  25273. const linearToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  25274. return color.mul( exposure ).clamp();
  25275. } ).setLayout( {
  25276. name: 'linearToneMapping',
  25277. type: 'vec3',
  25278. inputs: [
  25279. { name: 'color', type: 'vec3' },
  25280. { name: 'exposure', type: 'float' }
  25281. ]
  25282. } );
  25283. /**
  25284. * Reinhard tone mapping.
  25285. *
  25286. * Reference: {@link https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf}
  25287. *
  25288. * @tsl
  25289. * @function
  25290. * @param {Node<vec3>} color - The color that should be tone mapped.
  25291. * @param {Node<float>} exposure - The exposure.
  25292. * @return {Node<vec3>} The tone mapped color.
  25293. */
  25294. const reinhardToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  25295. color = color.mul( exposure );
  25296. return color.div( color.add( 1.0 ) ).clamp();
  25297. } ).setLayout( {
  25298. name: 'reinhardToneMapping',
  25299. type: 'vec3',
  25300. inputs: [
  25301. { name: 'color', type: 'vec3' },
  25302. { name: 'exposure', type: 'float' }
  25303. ]
  25304. } );
  25305. /**
  25306. * Cineon tone mapping.
  25307. *
  25308. * Reference: {@link http://filmicworlds.com/blog/filmic-tonemapping-operators/}
  25309. *
  25310. * @tsl
  25311. * @function
  25312. * @param {Node<vec3>} color - The color that should be tone mapped.
  25313. * @param {Node<float>} exposure - The exposure.
  25314. * @return {Node<vec3>} The tone mapped color.
  25315. */
  25316. const cineonToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  25317. // filmic operator by Jim Hejl and Richard Burgess-Dawson
  25318. color = color.mul( exposure );
  25319. color = color.sub( 0.004 ).max( 0.0 );
  25320. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  25321. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  25322. return a.div( b ).pow( 2.2 );
  25323. } ).setLayout( {
  25324. name: 'cineonToneMapping',
  25325. type: 'vec3',
  25326. inputs: [
  25327. { name: 'color', type: 'vec3' },
  25328. { name: 'exposure', type: 'float' }
  25329. ]
  25330. } );
  25331. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  25332. const RRTAndODTFit = /*@__PURE__*/ Fn( ( [ color ] ) => {
  25333. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  25334. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  25335. return a.div( b );
  25336. } );
  25337. /**
  25338. * ACESFilmic tone mapping.
  25339. *
  25340. * Reference: {@link https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs}
  25341. *
  25342. * @tsl
  25343. * @function
  25344. * @param {Node<vec3>} color - The color that should be tone mapped.
  25345. * @param {Node<float>} exposure - The exposure.
  25346. * @return {Node<vec3>} The tone mapped color.
  25347. */
  25348. const acesFilmicToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  25349. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  25350. const ACESInputMat = mat3(
  25351. 0.59719, 0.35458, 0.04823,
  25352. 0.07600, 0.90834, 0.01566,
  25353. 0.02840, 0.13383, 0.83777
  25354. );
  25355. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  25356. const ACESOutputMat = mat3(
  25357. 1.60475, -0.53108, -0.07367,
  25358. -0.10208, 1.10813, -605e-5,
  25359. -327e-5, -0.07276, 1.07602
  25360. );
  25361. color = color.mul( exposure ).div( 0.6 );
  25362. color = ACESInputMat.mul( color );
  25363. // Apply RRT and ODT
  25364. color = RRTAndODTFit( color );
  25365. color = ACESOutputMat.mul( color );
  25366. // Clamp to [0, 1]
  25367. return color.clamp();
  25368. } ).setLayout( {
  25369. name: 'acesFilmicToneMapping',
  25370. type: 'vec3',
  25371. inputs: [
  25372. { name: 'color', type: 'vec3' },
  25373. { name: 'exposure', type: 'float' }
  25374. ]
  25375. } );
  25376. 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 ) );
  25377. 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 ) );
  25378. const agxDefaultContrastApprox = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  25379. const x = vec3( x_immutable ).toVar();
  25380. const x2 = vec3( x.mul( x ) ).toVar();
  25381. const x4 = vec3( x2.mul( x2 ) ).toVar();
  25382. 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 ) ) ) );
  25383. } );
  25384. /**
  25385. * AgX tone mapping.
  25386. *
  25387. * @tsl
  25388. * @function
  25389. * @param {Node<vec3>} color - The color that should be tone mapped.
  25390. * @param {Node<float>} exposure - The exposure.
  25391. * @return {Node<vec3>} The tone mapped color.
  25392. */
  25393. const agxToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  25394. const colortone = vec3( color ).toVar();
  25395. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  25396. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, -0.1413297634984383, -0.14132976349843826 ), vec3( -0.11060664309660323, 1.157823702216272, -0.11060664309660294 ), vec3( -0.016493938717834573, -0.016493938717834257, 1.2519364065950405 ) );
  25397. const AgxMinEv = float( -12.47393 );
  25398. const AgxMaxEv = float( 4.026069 );
  25399. colortone.mulAssign( exposure );
  25400. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  25401. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  25402. colortone.assign( max$1( colortone, 1e-10 ) );
  25403. colortone.assign( log2( colortone ) );
  25404. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  25405. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  25406. colortone.assign( agxDefaultContrastApprox( colortone ) );
  25407. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  25408. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  25409. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  25410. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  25411. return colortone;
  25412. } ).setLayout( {
  25413. name: 'agxToneMapping',
  25414. type: 'vec3',
  25415. inputs: [
  25416. { name: 'color', type: 'vec3' },
  25417. { name: 'exposure', type: 'float' }
  25418. ]
  25419. } );
  25420. /**
  25421. * Neutral tone mapping.
  25422. *
  25423. * Reference: {@link https://modelviewer.dev/examples/tone-mapping}
  25424. *
  25425. * @tsl
  25426. * @function
  25427. * @param {Node<vec3>} color - The color that should be tone mapped.
  25428. * @param {Node<float>} exposure - The exposure.
  25429. * @return {Node<vec3>} The tone mapped color.
  25430. */
  25431. const neutralToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  25432. const StartCompression = float( 0.8 - 0.04 );
  25433. const Desaturation = float( 0.15 );
  25434. color = color.mul( exposure );
  25435. const x = min$1( color.r, min$1( color.g, color.b ) );
  25436. const offset = select( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  25437. color.subAssign( offset );
  25438. const peak = max$1( color.r, max$1( color.g, color.b ) );
  25439. If( peak.lessThan( StartCompression ), () => {
  25440. return color;
  25441. } );
  25442. const d = sub( 1, StartCompression );
  25443. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  25444. color.mulAssign( newPeak.div( peak ) );
  25445. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  25446. return mix( color, vec3( newPeak ), g );
  25447. } ).setLayout( {
  25448. name: 'neutralToneMapping',
  25449. type: 'vec3',
  25450. inputs: [
  25451. { name: 'color', type: 'vec3' },
  25452. { name: 'exposure', type: 'float' }
  25453. ]
  25454. } );
  25455. /**
  25456. * This class represents native code sections. It is the base
  25457. * class for modules like {@link FunctionNode} which allows to implement
  25458. * functions with native shader languages.
  25459. *
  25460. * @augments Node
  25461. */
  25462. class CodeNode extends Node {
  25463. static get type() {
  25464. return 'CodeNode';
  25465. }
  25466. /**
  25467. * Constructs a new code node.
  25468. *
  25469. * @param {string} [code=''] - The native code.
  25470. * @param {Array<Node>} [includes=[]] - An array of includes.
  25471. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  25472. */
  25473. constructor( code = '', includes = [], language = '' ) {
  25474. super( 'code' );
  25475. /**
  25476. * This flag can be used for type testing.
  25477. *
  25478. * @type {boolean}
  25479. * @readonly
  25480. * @default true
  25481. */
  25482. this.isCodeNode = true;
  25483. /**
  25484. * This flag is used for global cache.
  25485. *
  25486. * @type {boolean}
  25487. * @default true
  25488. */
  25489. this.global = true;
  25490. /**
  25491. * The native code.
  25492. *
  25493. * @type {string}
  25494. * @default ''
  25495. */
  25496. this.code = code;
  25497. /**
  25498. * An array of includes
  25499. *
  25500. * @type {Array<Node>}
  25501. * @default []
  25502. */
  25503. this.includes = includes;
  25504. /**
  25505. * The used language.
  25506. *
  25507. * @type {('js'|'wgsl'|'glsl')}
  25508. * @default ''
  25509. */
  25510. this.language = language;
  25511. }
  25512. /**
  25513. * Sets the includes of this code node.
  25514. *
  25515. * @param {Array<Node>} includes - The includes to set.
  25516. * @return {CodeNode} A reference to this node.
  25517. */
  25518. setIncludes( includes ) {
  25519. this.includes = includes;
  25520. return this;
  25521. }
  25522. /**
  25523. * Returns the includes of this code node.
  25524. *
  25525. * @param {NodeBuilder} builder - The current node builder.
  25526. * @return {Array<Node>} The includes.
  25527. */
  25528. getIncludes( /*builder*/ ) {
  25529. return this.includes;
  25530. }
  25531. generate( builder ) {
  25532. const includes = this.getIncludes( builder );
  25533. for ( const include of includes ) {
  25534. include.build( builder );
  25535. }
  25536. const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) );
  25537. nodeCode.code = this.code;
  25538. return nodeCode.code;
  25539. }
  25540. serialize( data ) {
  25541. super.serialize( data );
  25542. data.code = this.code;
  25543. data.language = this.language;
  25544. }
  25545. deserialize( data ) {
  25546. super.deserialize( data );
  25547. this.code = data.code;
  25548. this.language = data.language;
  25549. }
  25550. }
  25551. /**
  25552. * TSL function for creating a code node.
  25553. *
  25554. * @tsl
  25555. * @function
  25556. * @param {string} [code] - The native code.
  25557. * @param {?Array<Node>} [includes=[]] - An array of includes.
  25558. * @param {?('js'|'wgsl'|'glsl')} [language=''] - The used language.
  25559. * @returns {CodeNode}
  25560. */
  25561. const code = /*@__PURE__*/ nodeProxy( CodeNode ).setParameterLength( 1, 3 );
  25562. /**
  25563. * TSL function for creating a JS code node.
  25564. *
  25565. * @tsl
  25566. * @function
  25567. * @param {string} src - The native code.
  25568. * @param {Array<Node>} includes - An array of includes.
  25569. * @returns {CodeNode}
  25570. */
  25571. const js = ( src, includes ) => code( src, includes, 'js' );
  25572. /**
  25573. * TSL function for creating a WGSL code node.
  25574. *
  25575. * @tsl
  25576. * @function
  25577. * @param {string} src - The native code.
  25578. * @param {Array<Node>} includes - An array of includes.
  25579. * @returns {CodeNode}
  25580. */
  25581. const wgsl = ( src, includes ) => code( src, includes, 'wgsl' );
  25582. /**
  25583. * TSL function for creating a GLSL code node.
  25584. *
  25585. * @tsl
  25586. * @function
  25587. * @param {string} src - The native code.
  25588. * @param {Array<Node>} includes - An array of includes.
  25589. * @returns {CodeNode}
  25590. */
  25591. const glsl = ( src, includes ) => code( src, includes, 'glsl' );
  25592. /**
  25593. * This class represents a native shader function. It can be used to implement
  25594. * certain aspects of a node material with native shader code. There are two predefined
  25595. * TSL functions for easier usage.
  25596. *
  25597. * - `wgslFn`: Creates a WGSL function node.
  25598. * - `glslFn`: Creates a GLSL function node.
  25599. *
  25600. * A basic example with one include looks like so:
  25601. *
  25602. * ```js
  25603. * const desaturateWGSLFn = wgslFn( `
  25604. * fn desaturate( color:vec3<f32> ) -> vec3<f32> {
  25605. * let lum = vec3<f32>( 0.299, 0.587, 0.114 );
  25606. * return vec3<f32>( dot( lum, color ) );
  25607. * }`
  25608. *);
  25609. * const someWGSLFn = wgslFn( `
  25610. * fn someFn( color:vec3<f32> ) -> vec3<f32> {
  25611. * return desaturate( color );
  25612. * }
  25613. * `, [ desaturateWGSLFn ] );
  25614. * material.colorNode = someWGSLFn( { color: texture( map ) } );
  25615. *```
  25616. * @augments CodeNode
  25617. */
  25618. class FunctionNode extends CodeNode {
  25619. static get type() {
  25620. return 'FunctionNode';
  25621. }
  25622. /**
  25623. * Constructs a new function node.
  25624. *
  25625. * @param {string} [code=''] - The native code.
  25626. * @param {Array<Node>} [includes=[]] - An array of includes.
  25627. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  25628. */
  25629. constructor( code = '', includes = [], language = '' ) {
  25630. super( code, includes, language );
  25631. }
  25632. getNodeType( builder ) {
  25633. return this.getNodeFunction( builder ).type;
  25634. }
  25635. /**
  25636. * Returns the inputs of this function node.
  25637. *
  25638. * @param {NodeBuilder} builder - The current node builder.
  25639. * @return {Array<NodeFunctionInput>} The inputs.
  25640. */
  25641. getInputs( builder ) {
  25642. return this.getNodeFunction( builder ).inputs;
  25643. }
  25644. /**
  25645. * Returns the node function for this function node.
  25646. *
  25647. * @param {NodeBuilder} builder - The current node builder.
  25648. * @return {NodeFunction} The node function.
  25649. */
  25650. getNodeFunction( builder ) {
  25651. const nodeData = builder.getDataFromNode( this );
  25652. let nodeFunction = nodeData.nodeFunction;
  25653. if ( nodeFunction === undefined ) {
  25654. nodeFunction = builder.parser.parseFunction( this.code );
  25655. nodeData.nodeFunction = nodeFunction;
  25656. }
  25657. return nodeFunction;
  25658. }
  25659. generate( builder, output ) {
  25660. super.generate( builder );
  25661. const nodeFunction = this.getNodeFunction( builder );
  25662. const name = nodeFunction.name;
  25663. const type = nodeFunction.type;
  25664. const nodeCode = builder.getCodeFromNode( this, type );
  25665. if ( name !== '' ) {
  25666. // use a custom property name
  25667. nodeCode.name = name;
  25668. }
  25669. const propertyName = builder.getPropertyName( nodeCode );
  25670. const code = this.getNodeFunction( builder ).getCode( propertyName );
  25671. nodeCode.code = code + '\n';
  25672. if ( output === 'property' ) {
  25673. return propertyName;
  25674. } else {
  25675. return builder.format( `${ propertyName }()`, type, output );
  25676. }
  25677. }
  25678. }
  25679. const nativeFn = ( code, includes = [], language = '' ) => {
  25680. for ( let i = 0; i < includes.length; i ++ ) {
  25681. const include = includes[ i ];
  25682. // TSL Function: glslFn, wgslFn
  25683. if ( typeof include === 'function' ) {
  25684. includes[ i ] = include.functionNode;
  25685. }
  25686. }
  25687. const functionNode = nodeObject( new FunctionNode( code, includes, language ) );
  25688. const fn = ( ...params ) => functionNode.call( ...params );
  25689. fn.functionNode = functionNode;
  25690. return fn;
  25691. };
  25692. const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' );
  25693. const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' );
  25694. /**
  25695. * `ScriptableNode` uses this class to manage script inputs and outputs.
  25696. *
  25697. * @augments Node
  25698. */
  25699. class ScriptableValueNode extends Node {
  25700. static get type() {
  25701. return 'ScriptableValueNode';
  25702. }
  25703. /**
  25704. * Constructs a new scriptable node.
  25705. *
  25706. * @param {any} [value=null] - The value.
  25707. */
  25708. constructor( value = null ) {
  25709. super();
  25710. /**
  25711. * A reference to the value.
  25712. *
  25713. * @private
  25714. * @default null
  25715. */
  25716. this._value = value;
  25717. /**
  25718. * Depending on the type of `_value`, this property might cache parsed data.
  25719. *
  25720. * @private
  25721. * @default null
  25722. */
  25723. this._cache = null;
  25724. /**
  25725. * If this node represents an input, this property represents the input type.
  25726. *
  25727. * @type {?string}
  25728. * @default null
  25729. */
  25730. this.inputType = null;
  25731. /**
  25732. * If this node represents an output, this property represents the output type.
  25733. *
  25734. * @type {?string}
  25735. * @default null
  25736. */
  25737. this.outputType = null;
  25738. /**
  25739. * An event dispatcher for managing events.
  25740. *
  25741. * @type {EventDispatcher}
  25742. */
  25743. this.events = new EventDispatcher();
  25744. /**
  25745. * This flag can be used for type testing.
  25746. *
  25747. * @type {boolean}
  25748. * @readonly
  25749. * @default true
  25750. */
  25751. this.isScriptableValueNode = true;
  25752. }
  25753. /**
  25754. * Whether this node represents an output or not.
  25755. *
  25756. * @type {boolean}
  25757. * @readonly
  25758. * @default true
  25759. */
  25760. get isScriptableOutputNode() {
  25761. return this.outputType !== null;
  25762. }
  25763. set value( val ) {
  25764. if ( this._value === val ) return;
  25765. if ( this._cache && this.inputType === 'URL' && this.value.value instanceof ArrayBuffer ) {
  25766. URL.revokeObjectURL( this._cache );
  25767. this._cache = null;
  25768. }
  25769. this._value = val;
  25770. this.events.dispatchEvent( { type: 'change' } );
  25771. this.refresh();
  25772. }
  25773. /**
  25774. * The node's value.
  25775. *
  25776. * @type {any}
  25777. */
  25778. get value() {
  25779. return this._value;
  25780. }
  25781. /**
  25782. * Dispatches the `refresh` event.
  25783. */
  25784. refresh() {
  25785. this.events.dispatchEvent( { type: 'refresh' } );
  25786. }
  25787. /**
  25788. * The `value` property usually represents a node or even binary data in form of array buffers.
  25789. * In this case, this method tries to return the actual value behind the complex type.
  25790. *
  25791. * @return {any} The value.
  25792. */
  25793. getValue() {
  25794. const value = this.value;
  25795. if ( value && this._cache === null && this.inputType === 'URL' && value.value instanceof ArrayBuffer ) {
  25796. this._cache = URL.createObjectURL( new Blob( [ value.value ] ) );
  25797. } else if ( value && value.value !== null && value.value !== undefined && (
  25798. ( ( this.inputType === 'URL' || this.inputType === 'String' ) && typeof value.value === 'string' ) ||
  25799. ( this.inputType === 'Number' && typeof value.value === 'number' ) ||
  25800. ( this.inputType === 'Vector2' && value.value.isVector2 ) ||
  25801. ( this.inputType === 'Vector3' && value.value.isVector3 ) ||
  25802. ( this.inputType === 'Vector4' && value.value.isVector4 ) ||
  25803. ( this.inputType === 'Color' && value.value.isColor ) ||
  25804. ( this.inputType === 'Matrix3' && value.value.isMatrix3 ) ||
  25805. ( this.inputType === 'Matrix4' && value.value.isMatrix4 )
  25806. ) ) {
  25807. return value.value;
  25808. }
  25809. return this._cache || value;
  25810. }
  25811. /**
  25812. * Overwritten since the node type is inferred from the value.
  25813. *
  25814. * @param {NodeBuilder} builder - The current node builder.
  25815. * @return {string} The node type.
  25816. */
  25817. getNodeType( builder ) {
  25818. return this.value && this.value.isNode ? this.value.getNodeType( builder ) : 'float';
  25819. }
  25820. setup() {
  25821. return this.value && this.value.isNode ? this.value : float();
  25822. }
  25823. serialize( data ) {
  25824. super.serialize( data );
  25825. if ( this.value !== null ) {
  25826. if ( this.inputType === 'ArrayBuffer' ) {
  25827. data.value = arrayBufferToBase64( this.value );
  25828. } else {
  25829. data.value = this.value ? this.value.toJSON( data.meta ).uuid : null;
  25830. }
  25831. } else {
  25832. data.value = null;
  25833. }
  25834. data.inputType = this.inputType;
  25835. data.outputType = this.outputType;
  25836. }
  25837. deserialize( data ) {
  25838. super.deserialize( data );
  25839. let value = null;
  25840. if ( data.value !== null ) {
  25841. if ( data.inputType === 'ArrayBuffer' ) {
  25842. value = base64ToArrayBuffer( data.value );
  25843. } else if ( data.inputType === 'Texture' ) {
  25844. value = data.meta.textures[ data.value ];
  25845. } else {
  25846. value = data.meta.nodes[ data.value ] || null;
  25847. }
  25848. }
  25849. this.value = value;
  25850. this.inputType = data.inputType;
  25851. this.outputType = data.outputType;
  25852. }
  25853. }
  25854. /**
  25855. * TSL function for creating a scriptable value node.
  25856. *
  25857. * @tsl
  25858. * @function
  25859. * @param {any} [value] - The value.
  25860. * @returns {ScriptableValueNode}
  25861. */
  25862. const scriptableValue = /*@__PURE__*/ nodeProxy( ScriptableValueNode ).setParameterLength( 1 );
  25863. /**
  25864. * A Map-like data structure for managing resources of scriptable nodes.
  25865. *
  25866. * @augments Map
  25867. */
  25868. class Resources extends Map {
  25869. get( key, callback = null, ...params ) {
  25870. if ( this.has( key ) ) return super.get( key );
  25871. if ( callback !== null ) {
  25872. const value = callback( ...params );
  25873. this.set( key, value );
  25874. return value;
  25875. }
  25876. }
  25877. }
  25878. class Parameters {
  25879. constructor( scriptableNode ) {
  25880. this.scriptableNode = scriptableNode;
  25881. }
  25882. get parameters() {
  25883. return this.scriptableNode.parameters;
  25884. }
  25885. get layout() {
  25886. return this.scriptableNode.getLayout();
  25887. }
  25888. getInputLayout( id ) {
  25889. return this.scriptableNode.getInputLayout( id );
  25890. }
  25891. get( name ) {
  25892. const param = this.parameters[ name ];
  25893. const value = param ? param.getValue() : null;
  25894. return value;
  25895. }
  25896. }
  25897. /**
  25898. * Defines the resources (e.g. namespaces) of scriptable nodes.
  25899. *
  25900. * @type {Resources}
  25901. */
  25902. const ScriptableNodeResources = new Resources();
  25903. /**
  25904. * This type of node allows to implement nodes with custom scripts. The script
  25905. * section is represented as an instance of `CodeNode` written with JavaScript.
  25906. * The script itself must adhere to a specific structure.
  25907. *
  25908. * - main(): Executed once by default and every time `node.needsUpdate` is set.
  25909. * - layout: The layout object defines the script's interface (inputs and outputs).
  25910. *
  25911. * ```js
  25912. * ScriptableNodeResources.set( 'TSL', TSL );
  25913. *
  25914. * const scriptableNode = scriptable( js( `
  25915. * layout = {
  25916. * outputType: 'node',
  25917. * elements: [
  25918. * { name: 'source', inputType: 'node' },
  25919. * ]
  25920. * };
  25921. *
  25922. * const { mul, oscSine } = TSL;
  25923. *
  25924. * function main() {
  25925. * const source = parameters.get( 'source' ) || float();
  25926. * return mul( source, oscSine() ) );
  25927. * }
  25928. *
  25929. * ` ) );
  25930. *
  25931. * scriptableNode.setParameter( 'source', color( 1, 0, 0 ) );
  25932. *
  25933. * const material = new THREE.MeshBasicNodeMaterial();
  25934. * material.colorNode = scriptableNode;
  25935. * ```
  25936. *
  25937. * @augments Node
  25938. */
  25939. class ScriptableNode extends Node {
  25940. static get type() {
  25941. return 'ScriptableNode';
  25942. }
  25943. /**
  25944. * Constructs a new scriptable node.
  25945. *
  25946. * @param {?CodeNode} [codeNode=null] - The code node.
  25947. * @param {Object} [parameters={}] - The parameters definition.
  25948. */
  25949. constructor( codeNode = null, parameters = {} ) {
  25950. super();
  25951. /**
  25952. * The code node.
  25953. *
  25954. * @type {?CodeNode}
  25955. * @default null
  25956. */
  25957. this.codeNode = codeNode;
  25958. /**
  25959. * The parameters definition.
  25960. *
  25961. * @type {Object}
  25962. * @default {}
  25963. */
  25964. this.parameters = parameters;
  25965. this._local = new Resources();
  25966. this._output = scriptableValue( null );
  25967. this._outputs = {};
  25968. this._source = this.source;
  25969. this._method = null;
  25970. this._object = null;
  25971. this._value = null;
  25972. this._needsOutputUpdate = true;
  25973. this.onRefresh = this.onRefresh.bind( this );
  25974. /**
  25975. * This flag can be used for type testing.
  25976. *
  25977. * @type {boolean}
  25978. * @readonly
  25979. * @default true
  25980. */
  25981. this.isScriptableNode = true;
  25982. }
  25983. /**
  25984. * The source code of the scriptable node.
  25985. *
  25986. * @type {string}
  25987. */
  25988. get source() {
  25989. return this.codeNode ? this.codeNode.code : '';
  25990. }
  25991. /**
  25992. * Sets the reference of a local script variable.
  25993. *
  25994. * @param {string} name - The variable name.
  25995. * @param {Object} value - The reference to set.
  25996. * @return {Resources} The resource map
  25997. */
  25998. setLocal( name, value ) {
  25999. return this._local.set( name, value );
  26000. }
  26001. /**
  26002. * Gets the value of a local script variable.
  26003. *
  26004. * @param {string} name - The variable name.
  26005. * @return {Object} The value.
  26006. */
  26007. getLocal( name ) {
  26008. return this._local.get( name );
  26009. }
  26010. /**
  26011. * Event listener for the `refresh` event.
  26012. */
  26013. onRefresh() {
  26014. this._refresh();
  26015. }
  26016. /**
  26017. * Returns an input from the layout with the given id/name.
  26018. *
  26019. * @param {string} id - The id/name of the input.
  26020. * @return {Object} The element entry.
  26021. */
  26022. getInputLayout( id ) {
  26023. for ( const element of this.getLayout() ) {
  26024. if ( element.inputType && ( element.id === id || element.name === id ) ) {
  26025. return element;
  26026. }
  26027. }
  26028. }
  26029. /**
  26030. * Returns an output from the layout with the given id/name.
  26031. *
  26032. * @param {string} id - The id/name of the output.
  26033. * @return {Object} The element entry.
  26034. */
  26035. getOutputLayout( id ) {
  26036. for ( const element of this.getLayout() ) {
  26037. if ( element.outputType && ( element.id === id || element.name === id ) ) {
  26038. return element;
  26039. }
  26040. }
  26041. }
  26042. /**
  26043. * Defines a script output for the given name and value.
  26044. *
  26045. * @param {string} name - The name of the output.
  26046. * @param {Node} value - The node value.
  26047. * @return {ScriptableNode} A reference to this node.
  26048. */
  26049. setOutput( name, value ) {
  26050. const outputs = this._outputs;
  26051. if ( outputs[ name ] === undefined ) {
  26052. outputs[ name ] = scriptableValue( value );
  26053. } else {
  26054. outputs[ name ].value = value;
  26055. }
  26056. return this;
  26057. }
  26058. /**
  26059. * Returns a script output for the given name.
  26060. *
  26061. * @param {string} name - The name of the output.
  26062. * @return {ScriptableValueNode} The node value.
  26063. */
  26064. getOutput( name ) {
  26065. return this._outputs[ name ];
  26066. }
  26067. /**
  26068. * Returns a parameter for the given name
  26069. *
  26070. * @param {string} name - The name of the parameter.
  26071. * @return {ScriptableValueNode} The node value.
  26072. */
  26073. getParameter( name ) {
  26074. return this.parameters[ name ];
  26075. }
  26076. /**
  26077. * Sets a value for the given parameter name.
  26078. *
  26079. * @param {string} name - The parameter name.
  26080. * @param {any} value - The parameter value.
  26081. * @return {ScriptableNode} A reference to this node.
  26082. */
  26083. setParameter( name, value ) {
  26084. const parameters = this.parameters;
  26085. if ( value && value.isScriptableNode ) {
  26086. this.deleteParameter( name );
  26087. parameters[ name ] = value;
  26088. parameters[ name ].getDefaultOutput().events.addEventListener( 'refresh', this.onRefresh );
  26089. } else if ( value && value.isScriptableValueNode ) {
  26090. this.deleteParameter( name );
  26091. parameters[ name ] = value;
  26092. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  26093. } else if ( parameters[ name ] === undefined ) {
  26094. parameters[ name ] = scriptableValue( value );
  26095. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  26096. } else {
  26097. parameters[ name ].value = value;
  26098. }
  26099. return this;
  26100. }
  26101. /**
  26102. * Returns the value of this node which is the value of
  26103. * the default output.
  26104. *
  26105. * @return {Node} The value.
  26106. */
  26107. getValue() {
  26108. return this.getDefaultOutput().getValue();
  26109. }
  26110. /**
  26111. * Deletes a parameter from the script.
  26112. *
  26113. * @param {string} name - The parameter to remove.
  26114. * @return {ScriptableNode} A reference to this node.
  26115. */
  26116. deleteParameter( name ) {
  26117. let valueNode = this.parameters[ name ];
  26118. if ( valueNode ) {
  26119. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  26120. valueNode.events.removeEventListener( 'refresh', this.onRefresh );
  26121. }
  26122. return this;
  26123. }
  26124. /**
  26125. * Deletes all parameters from the script.
  26126. *
  26127. * @return {ScriptableNode} A reference to this node.
  26128. */
  26129. clearParameters() {
  26130. for ( const name of Object.keys( this.parameters ) ) {
  26131. this.deleteParameter( name );
  26132. }
  26133. this.needsUpdate = true;
  26134. return this;
  26135. }
  26136. /**
  26137. * Calls a function from the script.
  26138. *
  26139. * @param {string} name - The function name.
  26140. * @param {...any} params - A list of parameters.
  26141. * @return {any} The result of the function call.
  26142. */
  26143. call( name, ...params ) {
  26144. const object = this.getObject();
  26145. const method = object[ name ];
  26146. if ( typeof method === 'function' ) {
  26147. return method( ...params );
  26148. }
  26149. }
  26150. /**
  26151. * Asynchronously calls a function from the script.
  26152. *
  26153. * @param {string} name - The function name.
  26154. * @param {...any} params - A list of parameters.
  26155. * @return {Promise<any>} The result of the function call.
  26156. */
  26157. async callAsync( name, ...params ) {
  26158. const object = this.getObject();
  26159. const method = object[ name ];
  26160. if ( typeof method === 'function' ) {
  26161. return method.constructor.name === 'AsyncFunction' ? await method( ...params ) : method( ...params );
  26162. }
  26163. }
  26164. /**
  26165. * Overwritten since the node types is inferred from the script's output.
  26166. *
  26167. * @param {NodeBuilder} builder - The current node builder
  26168. * @return {string} The node type.
  26169. */
  26170. getNodeType( builder ) {
  26171. return this.getDefaultOutputNode().getNodeType( builder );
  26172. }
  26173. /**
  26174. * Refreshes the script node.
  26175. *
  26176. * @param {?string} [output=null] - An optional output.
  26177. */
  26178. refresh( output = null ) {
  26179. if ( output !== null ) {
  26180. this.getOutput( output ).refresh();
  26181. } else {
  26182. this._refresh();
  26183. }
  26184. }
  26185. /**
  26186. * Returns an object representation of the script.
  26187. *
  26188. * @return {Object} The result object.
  26189. */
  26190. getObject() {
  26191. if ( this.needsUpdate ) this.dispose();
  26192. if ( this._object !== null ) return this._object;
  26193. //
  26194. const refresh = () => this.refresh();
  26195. const setOutput = ( id, value ) => this.setOutput( id, value );
  26196. const parameters = new Parameters( this );
  26197. const THREE = ScriptableNodeResources.get( 'THREE' );
  26198. const TSL = ScriptableNodeResources.get( 'TSL' );
  26199. const method = this.getMethod();
  26200. const params = [ parameters, this._local, ScriptableNodeResources, refresh, setOutput, THREE, TSL ];
  26201. this._object = method( ...params );
  26202. const layout = this._object.layout;
  26203. if ( layout ) {
  26204. if ( layout.cache === false ) {
  26205. this._local.clear();
  26206. }
  26207. // default output
  26208. this._output.outputType = layout.outputType || null;
  26209. if ( Array.isArray( layout.elements ) ) {
  26210. for ( const element of layout.elements ) {
  26211. const id = element.id || element.name;
  26212. if ( element.inputType ) {
  26213. if ( this.getParameter( id ) === undefined ) this.setParameter( id, null );
  26214. this.getParameter( id ).inputType = element.inputType;
  26215. }
  26216. if ( element.outputType ) {
  26217. if ( this.getOutput( id ) === undefined ) this.setOutput( id, null );
  26218. this.getOutput( id ).outputType = element.outputType;
  26219. }
  26220. }
  26221. }
  26222. }
  26223. return this._object;
  26224. }
  26225. deserialize( data ) {
  26226. super.deserialize( data );
  26227. for ( const name in this.parameters ) {
  26228. let valueNode = this.parameters[ name ];
  26229. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  26230. valueNode.events.addEventListener( 'refresh', this.onRefresh );
  26231. }
  26232. }
  26233. /**
  26234. * Returns the layout of the script.
  26235. *
  26236. * @return {Object} The script's layout.
  26237. */
  26238. getLayout() {
  26239. return this.getObject().layout;
  26240. }
  26241. /**
  26242. * Returns default node output of the script.
  26243. *
  26244. * @return {Node} The default node output.
  26245. */
  26246. getDefaultOutputNode() {
  26247. const output = this.getDefaultOutput().value;
  26248. if ( output && output.isNode ) {
  26249. return output;
  26250. }
  26251. return float();
  26252. }
  26253. /**
  26254. * Returns default output of the script.
  26255. *
  26256. * @return {ScriptableValueNode} The default output.
  26257. */
  26258. getDefaultOutput() {
  26259. return this._exec()._output;
  26260. }
  26261. /**
  26262. * Returns a function created from the node's script.
  26263. *
  26264. * @return {Function} The function representing the node's code.
  26265. */
  26266. getMethod() {
  26267. if ( this.needsUpdate ) this.dispose();
  26268. if ( this._method !== null ) return this._method;
  26269. //
  26270. const parametersProps = [ 'parameters', 'local', 'global', 'refresh', 'setOutput', 'THREE', 'TSL' ];
  26271. const interfaceProps = [ 'layout', 'init', 'main', 'dispose' ];
  26272. const properties = interfaceProps.join( ', ' );
  26273. const declarations = 'var ' + properties + '; var output = {};\n';
  26274. const returns = '\nreturn { ...output, ' + properties + ' };';
  26275. const code = declarations + this.codeNode.code + returns;
  26276. //
  26277. this._method = new Function( ...parametersProps, code );
  26278. return this._method;
  26279. }
  26280. /**
  26281. * Frees all internal resources.
  26282. */
  26283. dispose() {
  26284. if ( this._method === null ) return;
  26285. if ( this._object && typeof this._object.dispose === 'function' ) {
  26286. this._object.dispose();
  26287. }
  26288. this._method = null;
  26289. this._object = null;
  26290. this._source = null;
  26291. this._value = null;
  26292. this._needsOutputUpdate = true;
  26293. this._output.value = null;
  26294. this._outputs = {};
  26295. }
  26296. setup() {
  26297. return this.getDefaultOutputNode();
  26298. }
  26299. getCacheKey( force ) {
  26300. const values = [ hashString( this.source ), this.getDefaultOutputNode().getCacheKey( force ) ];
  26301. for ( const param in this.parameters ) {
  26302. values.push( this.parameters[ param ].getCacheKey( force ) );
  26303. }
  26304. return hashArray( values );
  26305. }
  26306. set needsUpdate( value ) {
  26307. if ( value === true ) this.dispose();
  26308. }
  26309. get needsUpdate() {
  26310. return this.source !== this._source;
  26311. }
  26312. /**
  26313. * Executes the `main` function of the script.
  26314. *
  26315. * @private
  26316. * @return {ScriptableNode} A reference to this node.
  26317. */
  26318. _exec() {
  26319. if ( this.codeNode === null ) return this;
  26320. if ( this._needsOutputUpdate === true ) {
  26321. this._value = this.call( 'main' );
  26322. this._needsOutputUpdate = false;
  26323. }
  26324. this._output.value = this._value;
  26325. return this;
  26326. }
  26327. /**
  26328. * Executes the refresh.
  26329. *
  26330. * @private
  26331. */
  26332. _refresh() {
  26333. this.needsUpdate = true;
  26334. this._exec();
  26335. this._output.refresh();
  26336. }
  26337. }
  26338. /**
  26339. * TSL function for creating a scriptable node.
  26340. *
  26341. * @tsl
  26342. * @function
  26343. * @param {CodeNode} [codeNode] - The code node.
  26344. * @param {?Object} [parameters={}] - The parameters definition.
  26345. * @returns {ScriptableNode}
  26346. */
  26347. const scriptable = /*@__PURE__*/ nodeProxy( ScriptableNode ).setParameterLength( 1, 2 );
  26348. /**
  26349. * Returns a node that represents the `z` coordinate in view space
  26350. * for the current fragment. It's a different representation of the
  26351. * default depth value.
  26352. *
  26353. * This value can be part of a computation that defines how the fog
  26354. * density increases when moving away from the camera.
  26355. *
  26356. * @param {NodeBuilder} builder - The current node builder.
  26357. * @return {Node} The viewZ node.
  26358. */
  26359. function getViewZNode( builder ) {
  26360. let viewZ;
  26361. const getViewZ = builder.context.getViewZ;
  26362. if ( getViewZ !== undefined ) {
  26363. viewZ = getViewZ( this );
  26364. }
  26365. return ( viewZ || positionView.z ).negate();
  26366. }
  26367. /**
  26368. * Constructs a new range factor node.
  26369. *
  26370. * @tsl
  26371. * @function
  26372. * @param {Node} near - Defines the near value.
  26373. * @param {Node} far - Defines the far value.
  26374. */
  26375. const rangeFogFactor = Fn( ( [ near, far ], builder ) => {
  26376. const viewZ = getViewZNode( builder );
  26377. return smoothstep( near, far, viewZ );
  26378. } );
  26379. /**
  26380. * Represents an exponential squared fog. This type of fog gives
  26381. * a clear view near the camera and a faster than exponentially
  26382. * densening fog farther from the camera.
  26383. *
  26384. * @tsl
  26385. * @function
  26386. * @param {Node} density - Defines the fog density.
  26387. */
  26388. const densityFogFactor = Fn( ( [ density ], builder ) => {
  26389. const viewZ = getViewZNode( builder );
  26390. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  26391. } );
  26392. /**
  26393. * This class can be used to configure a fog for the scene.
  26394. * Nodes of this type are assigned to `Scene.fogNode`.
  26395. *
  26396. * @tsl
  26397. * @function
  26398. * @param {Node} color - Defines the color of the fog.
  26399. * @param {Node} factor - Defines how the fog is factored in the scene.
  26400. */
  26401. const fog = Fn( ( [ color, factor ] ) => {
  26402. return vec4( factor.toFloat().mix( output.rgb, color.toVec3() ), output.a );
  26403. } );
  26404. // Deprecated
  26405. /**
  26406. * @tsl
  26407. * @function
  26408. * @deprecated since r171. Use `fog( color, rangeFogFactor( near, far ) )` instead.
  26409. *
  26410. * @param {Node} color
  26411. * @param {Node} near
  26412. * @param {Node} far
  26413. * @returns {Function}
  26414. */
  26415. function rangeFog( color, near, far ) { // @deprecated, r171
  26416. console.warn( 'THREE.TSL: "rangeFog( color, near, far )" is deprecated. Use "fog( color, rangeFogFactor( near, far ) )" instead.' );
  26417. return fog( color, rangeFogFactor( near, far ) );
  26418. }
  26419. /**
  26420. * @tsl
  26421. * @function
  26422. * @deprecated since r171. Use `fog( color, densityFogFactor( density ) )` instead.
  26423. *
  26424. * @param {Node} color
  26425. * @param {Node} density
  26426. * @returns {Function}
  26427. */
  26428. function densityFog( color, density ) { // @deprecated, r171
  26429. console.warn( 'THREE.TSL: "densityFog( color, density )" is deprecated. Use "fog( color, densityFogFactor( density ) )" instead.' );
  26430. return fog( color, densityFogFactor( density ) );
  26431. }
  26432. let min = null;
  26433. let max = null;
  26434. /**
  26435. * `RangeNode` generates random instanced attribute data in a defined range.
  26436. * An exemplary use case for this utility node is to generate random per-instance
  26437. * colors:
  26438. * ```js
  26439. * const material = new MeshBasicNodeMaterial();
  26440. * material.colorNode = range( new Color( 0x000000 ), new Color( 0xFFFFFF ) );
  26441. * const mesh = new InstancedMesh( geometry, material, count );
  26442. * ```
  26443. * @augments Node
  26444. */
  26445. class RangeNode extends Node {
  26446. static get type() {
  26447. return 'RangeNode';
  26448. }
  26449. /**
  26450. * Constructs a new range node.
  26451. *
  26452. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  26453. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  26454. */
  26455. constructor( minNode = float(), maxNode = float() ) {
  26456. super();
  26457. /**
  26458. * A node defining the lower bound of the range.
  26459. *
  26460. * @type {Node<any>}
  26461. * @default float()
  26462. */
  26463. this.minNode = minNode;
  26464. /**
  26465. * A node defining the upper bound of the range.
  26466. *
  26467. * @type {Node<any>}
  26468. * @default float()
  26469. */
  26470. this.maxNode = maxNode;
  26471. }
  26472. /**
  26473. * Returns the vector length which is computed based on the range definition.
  26474. *
  26475. * @param {NodeBuilder} builder - The current node builder.
  26476. * @return {number} The vector length.
  26477. */
  26478. getVectorLength( builder ) {
  26479. const minLength = builder.getTypeLength( getValueType( this.minNode.value ) );
  26480. const maxLength = builder.getTypeLength( getValueType( this.maxNode.value ) );
  26481. return minLength > maxLength ? minLength : maxLength;
  26482. }
  26483. /**
  26484. * This method is overwritten since the node type is inferred from range definition.
  26485. *
  26486. * @param {NodeBuilder} builder - The current node builder.
  26487. * @return {string} The node type.
  26488. */
  26489. getNodeType( builder ) {
  26490. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  26491. }
  26492. setup( builder ) {
  26493. const object = builder.object;
  26494. let output = null;
  26495. if ( object.count > 1 ) {
  26496. const minValue = this.minNode.value;
  26497. const maxValue = this.maxNode.value;
  26498. const minLength = builder.getTypeLength( getValueType( minValue ) );
  26499. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  26500. min = min || new Vector4();
  26501. max = max || new Vector4();
  26502. min.setScalar( 0 );
  26503. max.setScalar( 0 );
  26504. if ( minLength === 1 ) min.setScalar( minValue );
  26505. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b, 1 );
  26506. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  26507. if ( maxLength === 1 ) max.setScalar( maxValue );
  26508. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b, 1 );
  26509. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  26510. const stride = 4;
  26511. const length = stride * object.count;
  26512. const array = new Float32Array( length );
  26513. for ( let i = 0; i < length; i ++ ) {
  26514. const index = i % stride;
  26515. const minElementValue = min.getComponent( index );
  26516. const maxElementValue = max.getComponent( index );
  26517. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  26518. }
  26519. const nodeType = this.getNodeType( builder );
  26520. if ( object.count <= 4096 ) {
  26521. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  26522. } else {
  26523. // TODO: Improve anonymous buffer attribute creation removing this part
  26524. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  26525. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  26526. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  26527. }
  26528. } else {
  26529. output = float( 0 );
  26530. }
  26531. return output;
  26532. }
  26533. }
  26534. /**
  26535. * TSL function for creating a range node.
  26536. *
  26537. * @tsl
  26538. * @function
  26539. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  26540. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  26541. * @returns {RangeNode}
  26542. */
  26543. const range = /*@__PURE__*/ nodeProxy( RangeNode ).setParameterLength( 2 );
  26544. /**
  26545. * `ComputeBuiltinNode` represents a compute-scope builtin value that expose information
  26546. * about the currently running dispatch and/or the device it is running on.
  26547. *
  26548. * This node can only be used with a WebGPU backend.
  26549. *
  26550. * @augments Node
  26551. */
  26552. class ComputeBuiltinNode extends Node {
  26553. static get type() {
  26554. return 'ComputeBuiltinNode';
  26555. }
  26556. /**
  26557. * Constructs a new compute builtin node.
  26558. *
  26559. * @param {string} builtinName - The built-in name.
  26560. * @param {string} nodeType - The node type.
  26561. */
  26562. constructor( builtinName, nodeType ) {
  26563. super( nodeType );
  26564. /**
  26565. * The built-in name.
  26566. *
  26567. * @private
  26568. * @type {string}
  26569. */
  26570. this._builtinName = builtinName;
  26571. }
  26572. /**
  26573. * This method is overwritten since hash is derived from the built-in name.
  26574. *
  26575. * @param {NodeBuilder} builder - The current node builder.
  26576. * @return {string} The hash.
  26577. */
  26578. getHash( builder ) {
  26579. return this.getBuiltinName( builder );
  26580. }
  26581. /**
  26582. * This method is overwritten since the node type is simply derived from `nodeType`..
  26583. *
  26584. * @param {NodeBuilder} builder - The current node builder.
  26585. * @return {string} The node type.
  26586. */
  26587. getNodeType( /*builder*/ ) {
  26588. return this.nodeType;
  26589. }
  26590. /**
  26591. * Sets the builtin name.
  26592. *
  26593. * @param {string} builtinName - The built-in name.
  26594. * @return {ComputeBuiltinNode} A reference to this node.
  26595. */
  26596. setBuiltinName( builtinName ) {
  26597. this._builtinName = builtinName;
  26598. return this;
  26599. }
  26600. /**
  26601. * Returns the builtin name.
  26602. *
  26603. * @param {NodeBuilder} builder - The current node builder.
  26604. * @return {string} The builtin name.
  26605. */
  26606. getBuiltinName( /*builder*/ ) {
  26607. return this._builtinName;
  26608. }
  26609. /**
  26610. * Whether the current node builder has the builtin or not.
  26611. *
  26612. * @param {NodeBuilder} builder - The current node builder.
  26613. * @return {boolean} Whether the builder has the builtin or not.
  26614. */
  26615. hasBuiltin( builder ) {
  26616. return builder.hasBuiltin( this._builtinName );
  26617. }
  26618. generate( builder, output ) {
  26619. const builtinName = this.getBuiltinName( builder );
  26620. const nodeType = this.getNodeType( builder );
  26621. if ( builder.shaderStage === 'compute' ) {
  26622. return builder.format( builtinName, nodeType, output );
  26623. } else {
  26624. console.warn( `ComputeBuiltinNode: Compute built-in value ${builtinName} can not be accessed in the ${builder.shaderStage} stage` );
  26625. return builder.generateConst( nodeType );
  26626. }
  26627. }
  26628. serialize( data ) {
  26629. super.serialize( data );
  26630. data.global = this.global;
  26631. data._builtinName = this._builtinName;
  26632. }
  26633. deserialize( data ) {
  26634. super.deserialize( data );
  26635. this.global = data.global;
  26636. this._builtinName = data._builtinName;
  26637. }
  26638. }
  26639. /**
  26640. * TSL function for creating a compute builtin node.
  26641. *
  26642. * @tsl
  26643. * @function
  26644. * @param {string} name - The built-in name.
  26645. * @param {string} nodeType - The node type.
  26646. * @returns {ComputeBuiltinNode}
  26647. */
  26648. const computeBuiltin = ( name, nodeType ) => nodeObject( new ComputeBuiltinNode( name, nodeType ) );
  26649. /**
  26650. * Represents the number of workgroups dispatched by the compute shader.
  26651. * ```js
  26652. * // Run 512 invocations/threads with a workgroup size of 128.
  26653. * const computeFn = Fn(() => {
  26654. *
  26655. * // numWorkgroups.x = 4
  26656. * storageBuffer.element(0).assign(numWorkgroups.x)
  26657. *
  26658. * })().compute(512, [128]);
  26659. *
  26660. * // Run 512 invocations/threads with the default workgroup size of 64.
  26661. * const computeFn = Fn(() => {
  26662. *
  26663. * // numWorkgroups.x = 8
  26664. * storageBuffer.element(0).assign(numWorkgroups.x)
  26665. *
  26666. * })().compute(512);
  26667. * ```
  26668. *
  26669. * @tsl
  26670. * @type {ComputeBuiltinNode<uvec3>}
  26671. */
  26672. const numWorkgroups = /*@__PURE__*/ computeBuiltin( 'numWorkgroups', 'uvec3' );
  26673. /**
  26674. * Represents the 3-dimensional index of the workgroup the current compute invocation belongs to.
  26675. * ```js
  26676. * // Execute 12 compute threads with a workgroup size of 3.
  26677. * const computeFn = Fn( () => {
  26678. *
  26679. * If( workgroupId.x.mod( 2 ).equal( 0 ), () => {
  26680. *
  26681. * storageBuffer.element( instanceIndex ).assign( instanceIndex );
  26682. *
  26683. * } ).Else( () => {
  26684. *
  26685. * storageBuffer.element( instanceIndex ).assign( 0 );
  26686. *
  26687. * } );
  26688. *
  26689. * } )().compute( 12, [ 3 ] );
  26690. *
  26691. * // workgroupId.x = [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3];
  26692. * // Buffer Output = [0, 1, 2, 0, 0, 0, 6, 7, 8, 0, 0, 0];
  26693. * ```
  26694. *
  26695. * @tsl
  26696. * @type {ComputeBuiltinNode<uvec3>}
  26697. */
  26698. const workgroupId = /*@__PURE__*/ computeBuiltin( 'workgroupId', 'uvec3' );
  26699. /**
  26700. * A non-linearized 3-dimensional representation of the current invocation's position within a 3D global grid.
  26701. *
  26702. * @tsl
  26703. * @type {ComputeBuiltinNode<uvec3>}
  26704. */
  26705. const globalId = /*@__PURE__*/ computeBuiltin( 'globalId', 'uvec3' );
  26706. /**
  26707. * A non-linearized 3-dimensional representation of the current invocation's position within a 3D workgroup grid.
  26708. *
  26709. * @tsl
  26710. * @type {ComputeBuiltinNode<uvec3>}
  26711. */
  26712. const localId = /*@__PURE__*/ computeBuiltin( 'localId', 'uvec3' );
  26713. /**
  26714. * A device dependent variable that exposes the size of the current invocation's subgroup.
  26715. *
  26716. * @tsl
  26717. * @type {ComputeBuiltinNode<uint>}
  26718. */
  26719. const subgroupSize = /*@__PURE__*/ computeBuiltin( 'subgroupSize', 'uint' );
  26720. /**
  26721. * Represents a GPU control barrier that synchronizes compute operations within a given scope.
  26722. *
  26723. * This node can only be used with a WebGPU backend.
  26724. *
  26725. * @augments Node
  26726. */
  26727. class BarrierNode extends Node {
  26728. /**
  26729. * Constructs a new barrier node.
  26730. *
  26731. * @param {string} scope - The scope defines the behavior of the node.
  26732. */
  26733. constructor( scope ) {
  26734. super();
  26735. this.scope = scope;
  26736. }
  26737. generate( builder ) {
  26738. const { scope } = this;
  26739. const { renderer } = builder;
  26740. if ( renderer.backend.isWebGLBackend === true ) {
  26741. builder.addFlowCode( `\t// ${scope}Barrier \n` );
  26742. } else {
  26743. builder.addLineFlowCode( `${scope}Barrier()`, this );
  26744. }
  26745. }
  26746. }
  26747. /**
  26748. * TSL function for creating a barrier node.
  26749. *
  26750. * @tsl
  26751. * @function
  26752. * @param {string} scope - The scope defines the behavior of the node..
  26753. * @returns {BarrierNode}
  26754. */
  26755. const barrier = nodeProxy( BarrierNode );
  26756. /**
  26757. * TSL function for creating a workgroup barrier. All compute shader
  26758. * invocations must wait for each invocation within a workgroup to
  26759. * complete before the barrier can be surpassed.
  26760. *
  26761. * @tsl
  26762. * @function
  26763. * @returns {BarrierNode}
  26764. */
  26765. const workgroupBarrier = () => barrier( 'workgroup' ).toStack();
  26766. /**
  26767. * TSL function for creating a storage barrier. All invocations must
  26768. * wait for each access to variables within the 'storage' address space
  26769. * to complete before the barrier can be passed.
  26770. *
  26771. * @tsl
  26772. * @function
  26773. * @returns {BarrierNode}
  26774. */
  26775. const storageBarrier = () => barrier( 'storage' ).toStack();
  26776. /**
  26777. * TSL function for creating a texture barrier. All invocations must
  26778. * wait for each access to variables within the 'texture' address space
  26779. * to complete before the barrier can be passed.
  26780. *
  26781. * @tsl
  26782. * @function
  26783. * @returns {BarrierNode}
  26784. */
  26785. const textureBarrier = () => barrier( 'texture' ).toStack();
  26786. /**
  26787. * Represents an element of a 'workgroup' scoped buffer.
  26788. *
  26789. * @augments ArrayElementNode
  26790. */
  26791. class WorkgroupInfoElementNode extends ArrayElementNode {
  26792. /**
  26793. * Constructs a new workgroup info element node.
  26794. *
  26795. * @param {Node} workgroupInfoNode - The workgroup info node.
  26796. * @param {Node} indexNode - The index node that defines the element access.
  26797. */
  26798. constructor( workgroupInfoNode, indexNode ) {
  26799. super( workgroupInfoNode, indexNode );
  26800. /**
  26801. * This flag can be used for type testing.
  26802. *
  26803. * @type {boolean}
  26804. * @readonly
  26805. * @default true
  26806. */
  26807. this.isWorkgroupInfoElementNode = true;
  26808. }
  26809. generate( builder, output ) {
  26810. let snippet;
  26811. const isAssignContext = builder.context.assign;
  26812. snippet = super.generate( builder );
  26813. if ( isAssignContext !== true ) {
  26814. const type = this.getNodeType( builder );
  26815. snippet = builder.format( snippet, type, output );
  26816. }
  26817. // TODO: Possibly activate clip distance index on index access rather than from clipping context
  26818. return snippet;
  26819. }
  26820. }
  26821. /**
  26822. * A node allowing the user to create a 'workgroup' scoped buffer within the
  26823. * context of a compute shader. Typically, workgroup scoped buffers are
  26824. * created to hold data that is transferred from a global storage scope into
  26825. * a local workgroup scope. For invocations within a workgroup, data
  26826. * access speeds on 'workgroup' scoped buffers can be significantly faster
  26827. * than similar access operations on globally accessible storage buffers.
  26828. *
  26829. * This node can only be used with a WebGPU backend.
  26830. *
  26831. * @augments Node
  26832. */
  26833. class WorkgroupInfoNode extends Node {
  26834. /**
  26835. * Constructs a new buffer scoped to type scope.
  26836. *
  26837. * @param {string} scope - TODO.
  26838. * @param {string} bufferType - The data type of a 'workgroup' scoped buffer element.
  26839. * @param {number} [bufferCount=0] - The number of elements in the buffer.
  26840. */
  26841. constructor( scope, bufferType, bufferCount = 0 ) {
  26842. super( bufferType );
  26843. /**
  26844. * The buffer type.
  26845. *
  26846. * @type {string}
  26847. */
  26848. this.bufferType = bufferType;
  26849. /**
  26850. * The buffer count.
  26851. *
  26852. * @type {number}
  26853. * @default 0
  26854. */
  26855. this.bufferCount = bufferCount;
  26856. /**
  26857. * This flag can be used for type testing.
  26858. *
  26859. * @type {boolean}
  26860. * @readonly
  26861. * @default true
  26862. */
  26863. this.isWorkgroupInfoNode = true;
  26864. /**
  26865. * The data type of the array buffer.
  26866. *
  26867. * @type {string}
  26868. */
  26869. this.elementType = bufferType;
  26870. /**
  26871. * TODO.
  26872. *
  26873. * @type {string}
  26874. */
  26875. this.scope = scope;
  26876. }
  26877. /**
  26878. * Sets the name/label of this node.
  26879. *
  26880. * @param {string} name - The name to set.
  26881. * @return {WorkgroupInfoNode} A reference to this node.
  26882. */
  26883. label( name ) {
  26884. this.name = name;
  26885. return this;
  26886. }
  26887. /**
  26888. * Sets the scope of this node.
  26889. *
  26890. * @param {string} scope - The scope to set.
  26891. * @return {WorkgroupInfoNode} A reference to this node.
  26892. */
  26893. setScope( scope ) {
  26894. this.scope = scope;
  26895. return this;
  26896. }
  26897. /**
  26898. * The data type of the array buffer.
  26899. *
  26900. * @return {string} The element type.
  26901. */
  26902. getElementType() {
  26903. return this.elementType;
  26904. }
  26905. /**
  26906. * Overwrites the default implementation since the input type
  26907. * is inferred from the scope.
  26908. *
  26909. * @param {NodeBuilder} builder - The current node builder.
  26910. * @return {string} The input type.
  26911. */
  26912. getInputType( /*builder*/ ) {
  26913. return `${this.scope}Array`;
  26914. }
  26915. /**
  26916. * This method can be used to access elements via an index node.
  26917. *
  26918. * @param {IndexNode} indexNode - indexNode.
  26919. * @return {WorkgroupInfoElementNode} A reference to an element.
  26920. */
  26921. element( indexNode ) {
  26922. return nodeObject( new WorkgroupInfoElementNode( this, indexNode ) );
  26923. }
  26924. generate( builder ) {
  26925. return builder.getScopedArray( this.name || `${this.scope}Array_${this.id}`, this.scope.toLowerCase(), this.bufferType, this.bufferCount );
  26926. }
  26927. }
  26928. /**
  26929. * TSL function for creating a workgroup info node.
  26930. * Creates a new 'workgroup' scoped array buffer.
  26931. *
  26932. * @tsl
  26933. * @function
  26934. * @param {string} type - The data type of a 'workgroup' scoped buffer element.
  26935. * @param {number} [count=0] - The number of elements in the buffer.
  26936. * @returns {WorkgroupInfoNode}
  26937. */
  26938. const workgroupArray = ( type, count ) => nodeObject( new WorkgroupInfoNode( 'Workgroup', type, count ) );
  26939. /**
  26940. * `AtomicFunctionNode` represents any function that can operate on atomic variable types
  26941. * within a shader. In an atomic function, any modification to an atomic variable will
  26942. * occur as an indivisible step with a defined order relative to other modifications.
  26943. * Accordingly, even if multiple atomic functions are modifying an atomic variable at once
  26944. * atomic operations will not interfere with each other.
  26945. *
  26946. * This node can only be used with a WebGPU backend.
  26947. *
  26948. * @augments Node
  26949. */
  26950. class AtomicFunctionNode extends Node {
  26951. static get type() {
  26952. return 'AtomicFunctionNode';
  26953. }
  26954. /**
  26955. * Constructs a new atomic function node.
  26956. *
  26957. * @param {string} method - The signature of the atomic function to construct.
  26958. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  26959. * @param {Node} valueNode - The value that mutates the atomic variable.
  26960. */
  26961. constructor( method, pointerNode, valueNode ) {
  26962. super( 'uint' );
  26963. /**
  26964. * The signature of the atomic function to construct.
  26965. *
  26966. * @type {string}
  26967. */
  26968. this.method = method;
  26969. /**
  26970. * An atomic variable or element of an atomic buffer.
  26971. *
  26972. * @type {Node}
  26973. */
  26974. this.pointerNode = pointerNode;
  26975. /**
  26976. * A value that modifies the atomic variable.
  26977. *
  26978. * @type {Node}
  26979. */
  26980. this.valueNode = valueNode;
  26981. /**
  26982. * Creates a list of the parents for this node for detecting if the node needs to return a value.
  26983. *
  26984. * @type {boolean}
  26985. * @default true
  26986. */
  26987. this.parents = true;
  26988. }
  26989. /**
  26990. * Overwrites the default implementation to return the type of
  26991. * the pointer node.
  26992. *
  26993. * @param {NodeBuilder} builder - The current node builder.
  26994. * @return {string} The input type.
  26995. */
  26996. getInputType( builder ) {
  26997. return this.pointerNode.getNodeType( builder );
  26998. }
  26999. /**
  27000. * Overwritten since the node type is inferred from the input type.
  27001. *
  27002. * @param {NodeBuilder} builder - The current node builder.
  27003. * @return {string} The node type.
  27004. */
  27005. getNodeType( builder ) {
  27006. return this.getInputType( builder );
  27007. }
  27008. generate( builder ) {
  27009. const properties = builder.getNodeProperties( this );
  27010. const parents = properties.parents;
  27011. const method = this.method;
  27012. const type = this.getNodeType( builder );
  27013. const inputType = this.getInputType( builder );
  27014. const a = this.pointerNode;
  27015. const b = this.valueNode;
  27016. const params = [];
  27017. params.push( `&${ a.build( builder, inputType ) }` );
  27018. if ( b !== null ) {
  27019. params.push( b.build( builder, inputType ) );
  27020. }
  27021. const methodSnippet = `${ builder.getMethod( method, type ) }( ${ params.join( ', ' ) } )`;
  27022. const isVoid = parents.length === 1 && parents[ 0 ].isStackNode === true;
  27023. if ( isVoid ) {
  27024. builder.addLineFlowCode( methodSnippet, this );
  27025. } else {
  27026. if ( properties.constNode === undefined ) {
  27027. properties.constNode = expression( methodSnippet, type ).toConst();
  27028. }
  27029. return properties.constNode.build( builder );
  27030. }
  27031. }
  27032. }
  27033. AtomicFunctionNode.ATOMIC_LOAD = 'atomicLoad';
  27034. AtomicFunctionNode.ATOMIC_STORE = 'atomicStore';
  27035. AtomicFunctionNode.ATOMIC_ADD = 'atomicAdd';
  27036. AtomicFunctionNode.ATOMIC_SUB = 'atomicSub';
  27037. AtomicFunctionNode.ATOMIC_MAX = 'atomicMax';
  27038. AtomicFunctionNode.ATOMIC_MIN = 'atomicMin';
  27039. AtomicFunctionNode.ATOMIC_AND = 'atomicAnd';
  27040. AtomicFunctionNode.ATOMIC_OR = 'atomicOr';
  27041. AtomicFunctionNode.ATOMIC_XOR = 'atomicXor';
  27042. /**
  27043. * TSL function for creating an atomic function node.
  27044. *
  27045. * @tsl
  27046. * @function
  27047. * @param {string} method - The signature of the atomic function to construct.
  27048. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  27049. * @param {Node} valueNode - The value that mutates the atomic variable.
  27050. * @returns {AtomicFunctionNode}
  27051. */
  27052. const atomicNode = nodeProxy( AtomicFunctionNode );
  27053. /**
  27054. * TSL function for appending an atomic function call into the programmatic flow of a compute shader.
  27055. *
  27056. * @tsl
  27057. * @function
  27058. * @param {string} method - The signature of the atomic function to construct.
  27059. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  27060. * @param {Node} valueNode - The value that mutates the atomic variable.
  27061. * @returns {AtomicFunctionNode}
  27062. */
  27063. const atomicFunc = ( method, pointerNode, valueNode ) => {
  27064. return atomicNode( method, pointerNode, valueNode ).toStack();
  27065. };
  27066. /**
  27067. * Loads the value stored in the atomic variable.
  27068. *
  27069. * @tsl
  27070. * @function
  27071. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  27072. * @returns {AtomicFunctionNode}
  27073. */
  27074. const atomicLoad = ( pointerNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_LOAD, pointerNode, null );
  27075. /**
  27076. * Stores a value in the atomic variable.
  27077. *
  27078. * @tsl
  27079. * @function
  27080. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  27081. * @param {Node} valueNode - The value that mutates the atomic variable.
  27082. * @returns {AtomicFunctionNode}
  27083. */
  27084. const atomicStore = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_STORE, pointerNode, valueNode );
  27085. /**
  27086. * Increments the value stored in the atomic variable.
  27087. *
  27088. * @tsl
  27089. * @function
  27090. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  27091. * @param {Node} valueNode - The value that mutates the atomic variable.
  27092. * @returns {AtomicFunctionNode}
  27093. */
  27094. const atomicAdd = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_ADD, pointerNode, valueNode );
  27095. /**
  27096. * Decrements the value stored in the atomic variable.
  27097. *
  27098. * @tsl
  27099. * @function
  27100. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  27101. * @param {Node} valueNode - The value that mutates the atomic variable.
  27102. * @returns {AtomicFunctionNode}
  27103. */
  27104. const atomicSub = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_SUB, pointerNode, valueNode );
  27105. /**
  27106. * Stores in an atomic variable the maximum between its current value and a parameter.
  27107. *
  27108. * @tsl
  27109. * @function
  27110. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  27111. * @param {Node} valueNode - The value that mutates the atomic variable.
  27112. * @returns {AtomicFunctionNode}
  27113. */
  27114. const atomicMax = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_MAX, pointerNode, valueNode );
  27115. /**
  27116. * Stores in an atomic variable the minimum between its current value and a parameter.
  27117. *
  27118. * @tsl
  27119. * @function
  27120. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  27121. * @param {Node} valueNode - The value that mutates the atomic variable.
  27122. * @returns {AtomicFunctionNode}
  27123. */
  27124. const atomicMin = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_MIN, pointerNode, valueNode );
  27125. /**
  27126. * Stores in an atomic variable the bitwise AND of its value with a parameter.
  27127. *
  27128. * @tsl
  27129. * @function
  27130. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  27131. * @param {Node} valueNode - The value that mutates the atomic variable.
  27132. * @returns {AtomicFunctionNode}
  27133. */
  27134. const atomicAnd = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_AND, pointerNode, valueNode );
  27135. /**
  27136. * Stores in an atomic variable the bitwise OR of its value with a parameter.
  27137. *
  27138. * @tsl
  27139. * @function
  27140. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  27141. * @param {Node} valueNode - The value that mutates the atomic variable.
  27142. * @returns {AtomicFunctionNode}
  27143. */
  27144. const atomicOr = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_OR, pointerNode, valueNode );
  27145. /**
  27146. * Stores in an atomic variable the bitwise XOR of its value with a parameter.
  27147. *
  27148. * @tsl
  27149. * @function
  27150. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  27151. * @param {Node} valueNode - The value that mutates the atomic variable.
  27152. * @returns {AtomicFunctionNode}
  27153. */
  27154. const atomicXor = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_XOR, pointerNode, valueNode );
  27155. let uniformsLib;
  27156. function getLightData( light ) {
  27157. uniformsLib = uniformsLib || new WeakMap();
  27158. let uniforms = uniformsLib.get( light );
  27159. if ( uniforms === undefined ) uniformsLib.set( light, uniforms = {} );
  27160. return uniforms;
  27161. }
  27162. /**
  27163. * TSL function for getting a shadow matrix uniform node for the given light.
  27164. *
  27165. * @tsl
  27166. * @function
  27167. * @param {Light} light -The light source.
  27168. * @returns {UniformNode<mat4>} The shadow matrix uniform node.
  27169. */
  27170. function lightShadowMatrix( light ) {
  27171. const data = getLightData( light );
  27172. return data.shadowMatrix || ( data.shadowMatrix = uniform( 'mat4' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => {
  27173. if ( light.castShadow !== true || frame.renderer.shadowMap.enabled === false ) {
  27174. light.shadow.updateMatrices( light );
  27175. }
  27176. return light.shadow.matrix;
  27177. } ) );
  27178. }
  27179. /**
  27180. * TSL function for getting projected uv coordinates for the given light.
  27181. * Relevant when using maps with spot lights.
  27182. *
  27183. * @tsl
  27184. * @function
  27185. * @param {Light} light -The light source.
  27186. * @param {Node<vec3>} [position=positionWorld] -The position to project.
  27187. * @returns {Node<vec3>} The projected uvs.
  27188. */
  27189. function lightProjectionUV( light, position = positionWorld ) {
  27190. const spotLightCoord = lightShadowMatrix( light ).mul( position );
  27191. const projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  27192. return projectionUV;
  27193. }
  27194. /**
  27195. * TSL function for getting the position in world space for the given light.
  27196. *
  27197. * @tsl
  27198. * @function
  27199. * @param {Light} light -The light source.
  27200. * @returns {UniformNode<vec3>} The light's position in world space.
  27201. */
  27202. function lightPosition( light ) {
  27203. const data = getLightData( light );
  27204. return data.position || ( data.position = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.matrixWorld ) ) );
  27205. }
  27206. /**
  27207. * TSL function for getting the light target position in world space for the given light.
  27208. *
  27209. * @tsl
  27210. * @function
  27211. * @param {Light} light -The light source.
  27212. * @returns {UniformNode<vec3>} The light target position in world space.
  27213. */
  27214. function lightTargetPosition( light ) {
  27215. const data = getLightData( light );
  27216. return data.targetPosition || ( data.targetPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.target.matrixWorld ) ) );
  27217. }
  27218. /**
  27219. * TSL function for getting the position in view space for the given light.
  27220. *
  27221. * @tsl
  27222. * @function
  27223. * @param {Light} light - The light source.
  27224. * @returns {UniformNode<vec3>} The light's position in view space.
  27225. */
  27226. function lightViewPosition( light ) {
  27227. const data = getLightData( light );
  27228. return data.viewPosition || ( data.viewPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => {
  27229. self.value = self.value || new Vector3();
  27230. self.value.setFromMatrixPosition( light.matrixWorld );
  27231. self.value.applyMatrix4( camera.matrixWorldInverse );
  27232. } ) );
  27233. }
  27234. /**
  27235. * TSL function for getting the light target direction for the given light.
  27236. *
  27237. * @tsl
  27238. * @function
  27239. * @param {Light} light -The light source.
  27240. * @returns {Node<vec3>} The light's target direction.
  27241. */
  27242. const lightTargetDirection = ( light ) => cameraViewMatrix.transformDirection( lightPosition( light ).sub( lightTargetPosition( light ) ) );
  27243. const sortLights = ( lights ) => {
  27244. return lights.sort( ( a, b ) => a.id - b.id );
  27245. };
  27246. const getLightNodeById = ( id, lightNodes ) => {
  27247. for ( const lightNode of lightNodes ) {
  27248. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  27249. return lightNode;
  27250. }
  27251. }
  27252. return null;
  27253. };
  27254. const _lightsNodeRef = /*@__PURE__*/ new WeakMap();
  27255. const _hashData = [];
  27256. /**
  27257. * This node represents the scene's lighting and manages the lighting model's life cycle
  27258. * for the current build 3D object. It is responsible for computing the total outgoing
  27259. * light in a given lighting context.
  27260. *
  27261. * @augments Node
  27262. */
  27263. class LightsNode extends Node {
  27264. static get type() {
  27265. return 'LightsNode';
  27266. }
  27267. /**
  27268. * Constructs a new lights node.
  27269. */
  27270. constructor() {
  27271. super( 'vec3' );
  27272. /**
  27273. * A node representing the total diffuse light.
  27274. *
  27275. * @type {Node<vec3>}
  27276. */
  27277. this.totalDiffuseNode = property( 'vec3', 'totalDiffuse' );
  27278. /**
  27279. * A node representing the total specular light.
  27280. *
  27281. * @type {Node<vec3>}
  27282. */
  27283. this.totalSpecularNode = property( 'vec3', 'totalSpecular' );
  27284. /**
  27285. * A node representing the outgoing light.
  27286. *
  27287. * @type {Node<vec3>}
  27288. */
  27289. this.outgoingLightNode = property( 'vec3', 'outgoingLight' );
  27290. /**
  27291. * An array representing the lights in the scene.
  27292. *
  27293. * @private
  27294. * @type {Array<Light>}
  27295. */
  27296. this._lights = [];
  27297. /**
  27298. * For each light in the scene, this node will create a
  27299. * corresponding light node.
  27300. *
  27301. * @private
  27302. * @type {?Array<LightingNode>}
  27303. * @default null
  27304. */
  27305. this._lightNodes = null;
  27306. /**
  27307. * A hash for identifying the current light nodes setup.
  27308. *
  27309. * @private
  27310. * @type {?string}
  27311. * @default null
  27312. */
  27313. this._lightNodesHash = null;
  27314. /**
  27315. * `LightsNode` sets this property to `true` by default.
  27316. *
  27317. * @type {boolean}
  27318. * @default true
  27319. */
  27320. this.global = true;
  27321. }
  27322. /**
  27323. * Overwrites the default {@link Node#customCacheKey} implementation by including
  27324. * light data into the cache key.
  27325. *
  27326. * @return {number} The custom cache key.
  27327. */
  27328. customCacheKey() {
  27329. const lights = this._lights;
  27330. for ( let i = 0; i < lights.length; i ++ ) {
  27331. const light = lights[ i ];
  27332. _hashData.push( light.id );
  27333. _hashData.push( light.castShadow ? 1 : 0 );
  27334. if ( light.isSpotLight === true ) {
  27335. const hashMap = ( light.map !== null ) ? light.map.id : -1;
  27336. const hashColorNode = ( light.colorNode ) ? light.colorNode.getCacheKey() : -1;
  27337. _hashData.push( hashMap, hashColorNode );
  27338. }
  27339. }
  27340. const cacheKey = hashArray( _hashData );
  27341. _hashData.length = 0;
  27342. return cacheKey;
  27343. }
  27344. /**
  27345. * Computes a hash value for identifying the current light nodes setup.
  27346. *
  27347. * @param {NodeBuilder} builder - A reference to the current node builder.
  27348. * @return {string} The computed hash.
  27349. */
  27350. getHash( builder ) {
  27351. if ( this._lightNodesHash === null ) {
  27352. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  27353. const hash = [];
  27354. for ( const lightNode of this._lightNodes ) {
  27355. hash.push( lightNode.getSelf().getHash() );
  27356. }
  27357. this._lightNodesHash = 'lights-' + hash.join( ',' );
  27358. }
  27359. return this._lightNodesHash;
  27360. }
  27361. analyze( builder ) {
  27362. const properties = builder.getNodeProperties( this );
  27363. for ( const node of properties.nodes ) {
  27364. node.build( builder );
  27365. }
  27366. properties.outputNode.build( builder );
  27367. }
  27368. /**
  27369. * Creates lighting nodes for each scene light. This makes it possible to further
  27370. * process lights in the node system.
  27371. *
  27372. * @param {NodeBuilder} builder - A reference to the current node builder.
  27373. */
  27374. setupLightsNode( builder ) {
  27375. const lightNodes = [];
  27376. const previousLightNodes = this._lightNodes;
  27377. const lights = sortLights( this._lights );
  27378. const nodeLibrary = builder.renderer.library;
  27379. for ( const light of lights ) {
  27380. if ( light.isNode ) {
  27381. lightNodes.push( nodeObject( light ) );
  27382. } else {
  27383. let lightNode = null;
  27384. if ( previousLightNodes !== null ) {
  27385. lightNode = getLightNodeById( light.id, previousLightNodes ); // reuse existing light node
  27386. }
  27387. if ( lightNode === null ) {
  27388. // find the corresponding node type for a given light
  27389. const lightNodeClass = nodeLibrary.getLightNodeClass( light.constructor );
  27390. if ( lightNodeClass === null ) {
  27391. console.warn( `LightsNode.setupNodeLights: Light node not found for ${ light.constructor.name }` );
  27392. continue;
  27393. }
  27394. let lightNode = null;
  27395. if ( ! _lightsNodeRef.has( light ) ) {
  27396. lightNode = nodeObject( new lightNodeClass( light ) );
  27397. _lightsNodeRef.set( light, lightNode );
  27398. } else {
  27399. lightNode = _lightsNodeRef.get( light );
  27400. }
  27401. lightNodes.push( lightNode );
  27402. }
  27403. }
  27404. }
  27405. this._lightNodes = lightNodes;
  27406. }
  27407. /**
  27408. * Sets up a direct light in the lighting model.
  27409. *
  27410. * @param {Object} builder - The builder object containing the context and stack.
  27411. * @param {Object} lightNode - The light node.
  27412. * @param {Object} lightData - The light object containing color and direction properties.
  27413. */
  27414. setupDirectLight( builder, lightNode, lightData ) {
  27415. const { lightingModel, reflectedLight } = builder.context;
  27416. lightingModel.direct( {
  27417. ...lightData,
  27418. lightNode,
  27419. reflectedLight
  27420. }, builder );
  27421. }
  27422. setupDirectRectAreaLight( builder, lightNode, lightData ) {
  27423. const { lightingModel, reflectedLight } = builder.context;
  27424. lightingModel.directRectArea( {
  27425. ...lightData,
  27426. lightNode,
  27427. reflectedLight
  27428. }, builder );
  27429. }
  27430. /**
  27431. * Setups the internal lights by building all respective
  27432. * light nodes.
  27433. *
  27434. * @param {NodeBuilder} builder - A reference to the current node builder.
  27435. * @param {Array<LightingNode>} lightNodes - An array of lighting nodes.
  27436. */
  27437. setupLights( builder, lightNodes ) {
  27438. for ( const lightNode of lightNodes ) {
  27439. lightNode.build( builder );
  27440. }
  27441. }
  27442. getLightNodes( builder ) {
  27443. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  27444. return this._lightNodes;
  27445. }
  27446. /**
  27447. * The implementation makes sure that for each light in the scene
  27448. * there is a corresponding light node. By building the light nodes
  27449. * and evaluating the lighting model the outgoing light is computed.
  27450. *
  27451. * @param {NodeBuilder} builder - A reference to the current node builder.
  27452. * @return {Node<vec3>} A node representing the outgoing light.
  27453. */
  27454. setup( builder ) {
  27455. const currentLightsNode = builder.lightsNode;
  27456. builder.lightsNode = this;
  27457. //
  27458. let outgoingLightNode = this.outgoingLightNode;
  27459. const context = builder.context;
  27460. const lightingModel = context.lightingModel;
  27461. const properties = builder.getNodeProperties( this );
  27462. if ( lightingModel ) {
  27463. const { totalDiffuseNode, totalSpecularNode } = this;
  27464. context.outgoingLight = outgoingLightNode;
  27465. const stack = builder.addStack();
  27466. //
  27467. properties.nodes = stack.nodes;
  27468. //
  27469. lightingModel.start( builder );
  27470. //
  27471. const { backdrop, backdropAlpha } = context;
  27472. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  27473. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  27474. if ( backdrop !== null ) {
  27475. if ( backdropAlpha !== null ) {
  27476. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  27477. } else {
  27478. totalDiffuse = vec3( backdrop );
  27479. }
  27480. context.material.transparent = true;
  27481. }
  27482. totalDiffuseNode.assign( totalDiffuse );
  27483. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  27484. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  27485. //
  27486. lightingModel.finish( builder );
  27487. //
  27488. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  27489. } else {
  27490. properties.nodes = [];
  27491. }
  27492. //
  27493. builder.lightsNode = currentLightsNode;
  27494. return outgoingLightNode;
  27495. }
  27496. /**
  27497. * Configures this node with an array of lights.
  27498. *
  27499. * @param {Array<Light>} lights - An array of lights.
  27500. * @return {LightsNode} A reference to this node.
  27501. */
  27502. setLights( lights ) {
  27503. this._lights = lights;
  27504. this._lightNodes = null;
  27505. this._lightNodesHash = null;
  27506. return this;
  27507. }
  27508. /**
  27509. * Returns an array of the scene's lights.
  27510. *
  27511. * @return {Array<Light>} The scene's lights.
  27512. */
  27513. getLights() {
  27514. return this._lights;
  27515. }
  27516. /**
  27517. * Whether the scene has lights or not.
  27518. *
  27519. * @type {boolean}
  27520. */
  27521. get hasLights() {
  27522. return this._lights.length > 0;
  27523. }
  27524. }
  27525. /**
  27526. * TSL function for creating an instance of `LightsNode` and configuring
  27527. * it with the given array of lights.
  27528. *
  27529. * @tsl
  27530. * @function
  27531. * @param {Array<Light>} lights - An array of lights.
  27532. * @return {LightsNode} The created lights node.
  27533. */
  27534. const lights = ( lights = [] ) => nodeObject( new LightsNode() ).setLights( lights );
  27535. /**
  27536. * Base class for all shadow nodes.
  27537. *
  27538. * Shadow nodes encapsulate shadow related logic and are always coupled to lighting nodes.
  27539. * Lighting nodes might share the same shadow node type or use specific ones depending on
  27540. * their requirements.
  27541. *
  27542. * @augments Node
  27543. */
  27544. class ShadowBaseNode extends Node {
  27545. static get type() {
  27546. return 'ShadowBaseNode';
  27547. }
  27548. /**
  27549. * Constructs a new shadow base node.
  27550. *
  27551. * @param {Light} light - The shadow casting light.
  27552. */
  27553. constructor( light ) {
  27554. super();
  27555. /**
  27556. * The shadow casting light.
  27557. *
  27558. * @type {Light}
  27559. */
  27560. this.light = light;
  27561. /**
  27562. * Overwritten since shadows are updated by default per render.
  27563. *
  27564. * @type {string}
  27565. * @default 'render'
  27566. */
  27567. this.updateBeforeType = NodeUpdateType.RENDER;
  27568. /**
  27569. * This flag can be used for type testing.
  27570. *
  27571. * @type {boolean}
  27572. * @readonly
  27573. * @default true
  27574. */
  27575. this.isShadowBaseNode = true;
  27576. }
  27577. /**
  27578. * Setups the shadow position node which is by default the predefined TSL node object `shadowPositionWorld`.
  27579. *
  27580. * @param {NodeBuilder} object - A configuration object that must at least hold a material reference.
  27581. */
  27582. setupShadowPosition( { context, material } ) {
  27583. // Use assign inside an Fn()
  27584. shadowPositionWorld.assign( material.receivedShadowPositionNode || context.shadowPositionWorld || positionWorld );
  27585. }
  27586. }
  27587. /**
  27588. * TSL object that represents the vertex position in world space during the shadow pass.
  27589. *
  27590. * @tsl
  27591. * @type {Node<vec3>}
  27592. */
  27593. const shadowPositionWorld = /*@__PURE__*/ property( 'vec3', 'shadowPositionWorld' );
  27594. /**
  27595. * Saves the state of the given renderer and stores it into the given state object.
  27596. *
  27597. * If not state object is provided, the function creates one.
  27598. *
  27599. * @function
  27600. * @param {Renderer} renderer - The renderer.
  27601. * @param {Object} [state={}] - The state.
  27602. * @return {Object} The state.
  27603. */
  27604. function saveRendererState( renderer, state = {} ) {
  27605. state.toneMapping = renderer.toneMapping;
  27606. state.toneMappingExposure = renderer.toneMappingExposure;
  27607. state.outputColorSpace = renderer.outputColorSpace;
  27608. state.renderTarget = renderer.getRenderTarget();
  27609. state.activeCubeFace = renderer.getActiveCubeFace();
  27610. state.activeMipmapLevel = renderer.getActiveMipmapLevel();
  27611. state.renderObjectFunction = renderer.getRenderObjectFunction();
  27612. state.pixelRatio = renderer.getPixelRatio();
  27613. state.mrt = renderer.getMRT();
  27614. state.clearColor = renderer.getClearColor( state.clearColor || new Color() );
  27615. state.clearAlpha = renderer.getClearAlpha();
  27616. state.autoClear = renderer.autoClear;
  27617. state.scissorTest = renderer.getScissorTest();
  27618. return state;
  27619. }
  27620. /**
  27621. * Saves the state of the given renderer and stores it into the given state object.
  27622. * Besides, the function also resets the state of the renderer to its default values.
  27623. *
  27624. * If not state object is provided, the function creates one.
  27625. *
  27626. * @function
  27627. * @param {Renderer} renderer - The renderer.
  27628. * @param {Object} [state={}] - The state.
  27629. * @return {Object} The state.
  27630. */
  27631. function resetRendererState( renderer, state ) {
  27632. state = saveRendererState( renderer, state );
  27633. renderer.setMRT( null );
  27634. renderer.setRenderObjectFunction( null );
  27635. renderer.setClearColor( 0x000000, 1 );
  27636. renderer.autoClear = true;
  27637. return state;
  27638. }
  27639. /**
  27640. * Restores the state of the given renderer from the given state object.
  27641. *
  27642. * @function
  27643. * @param {Renderer} renderer - The renderer.
  27644. * @param {Object} state - The state to restore.
  27645. */
  27646. function restoreRendererState( renderer, state ) {
  27647. renderer.toneMapping = state.toneMapping;
  27648. renderer.toneMappingExposure = state.toneMappingExposure;
  27649. renderer.outputColorSpace = state.outputColorSpace;
  27650. renderer.setRenderTarget( state.renderTarget, state.activeCubeFace, state.activeMipmapLevel );
  27651. renderer.setRenderObjectFunction( state.renderObjectFunction );
  27652. renderer.setPixelRatio( state.pixelRatio );
  27653. renderer.setMRT( state.mrt );
  27654. renderer.setClearColor( state.clearColor, state.clearAlpha );
  27655. renderer.autoClear = state.autoClear;
  27656. renderer.setScissorTest( state.scissorTest );
  27657. }
  27658. /**
  27659. * Saves the state of the given scene and stores it into the given state object.
  27660. *
  27661. * If not state object is provided, the function creates one.
  27662. *
  27663. * @function
  27664. * @param {Scene} scene - The scene.
  27665. * @param {Object} [state={}] - The state.
  27666. * @return {Object} The state.
  27667. */
  27668. function saveSceneState( scene, state = {} ) {
  27669. state.background = scene.background;
  27670. state.backgroundNode = scene.backgroundNode;
  27671. state.overrideMaterial = scene.overrideMaterial;
  27672. return state;
  27673. }
  27674. /**
  27675. * Saves the state of the given scene and stores it into the given state object.
  27676. * Besides, the function also resets the state of the scene to its default values.
  27677. *
  27678. * If not state object is provided, the function creates one.
  27679. *
  27680. * @function
  27681. * @param {Scene} scene - The scene.
  27682. * @param {Object} [state={}] - The state.
  27683. * @return {Object} The state.
  27684. */
  27685. function resetSceneState( scene, state ) {
  27686. state = saveSceneState( scene, state );
  27687. scene.background = null;
  27688. scene.backgroundNode = null;
  27689. scene.overrideMaterial = null;
  27690. return state;
  27691. }
  27692. /**
  27693. * Restores the state of the given scene from the given state object.
  27694. *
  27695. * @function
  27696. * @param {Scene} scene - The scene.
  27697. * @param {Object} state - The state to restore.
  27698. */
  27699. function restoreSceneState( scene, state ) {
  27700. scene.background = state.background;
  27701. scene.backgroundNode = state.backgroundNode;
  27702. scene.overrideMaterial = state.overrideMaterial;
  27703. }
  27704. /**
  27705. * Saves the state of the given renderer and scene and stores it into the given state object.
  27706. *
  27707. * If not state object is provided, the function creates one.
  27708. *
  27709. * @function
  27710. * @param {Renderer} renderer - The renderer.
  27711. * @param {Scene} scene - The scene.
  27712. * @param {Object} [state={}] - The state.
  27713. * @return {Object} The state.
  27714. */
  27715. function saveRendererAndSceneState( renderer, scene, state = {} ) {
  27716. state = saveRendererState( renderer, state );
  27717. state = saveSceneState( scene, state );
  27718. return state;
  27719. }
  27720. /**
  27721. * Saves the state of the given renderer and scene and stores it into the given state object.
  27722. * Besides, the function also resets the state of the renderer and scene to its default values.
  27723. *
  27724. * If not state object is provided, the function creates one.
  27725. *
  27726. * @function
  27727. * @param {Renderer} renderer - The renderer.
  27728. * @param {Scene} scene - The scene.
  27729. * @param {Object} [state={}] - The state.
  27730. * @return {Object} The state.
  27731. */
  27732. function resetRendererAndSceneState( renderer, scene, state ) {
  27733. state = resetRendererState( renderer, state );
  27734. state = resetSceneState( scene, state );
  27735. return state;
  27736. }
  27737. /**
  27738. * Restores the state of the given renderer and scene from the given state object.
  27739. *
  27740. * @function
  27741. * @param {Renderer} renderer - The renderer.
  27742. * @param {Scene} scene - The scene.
  27743. * @param {Object} state - The state to restore.
  27744. */
  27745. function restoreRendererAndSceneState( renderer, scene, state ) {
  27746. restoreRendererState( renderer, state );
  27747. restoreSceneState( scene, state );
  27748. }
  27749. var RendererUtils = /*#__PURE__*/Object.freeze({
  27750. __proto__: null,
  27751. resetRendererAndSceneState: resetRendererAndSceneState,
  27752. resetRendererState: resetRendererState,
  27753. resetSceneState: resetSceneState,
  27754. restoreRendererAndSceneState: restoreRendererAndSceneState,
  27755. restoreRendererState: restoreRendererState,
  27756. restoreSceneState: restoreSceneState,
  27757. saveRendererAndSceneState: saveRendererAndSceneState,
  27758. saveRendererState: saveRendererState,
  27759. saveSceneState: saveSceneState
  27760. });
  27761. const shadowMaterialLib = /*@__PURE__*/ new WeakMap();
  27762. /**
  27763. * A shadow filtering function performing basic filtering. This is in fact an unfiltered version of the shadow map
  27764. * with a binary `[0,1]` result.
  27765. *
  27766. * @method
  27767. * @param {Object} inputs - The input parameter object.
  27768. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  27769. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  27770. * @return {Node<float>} The filtering result.
  27771. */
  27772. const BasicShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, depthLayer } ) => {
  27773. let basic = texture( depthTexture, shadowCoord.xy ).label( 't_basic' );
  27774. if ( depthTexture.isArrayTexture ) {
  27775. basic = basic.depth( depthLayer );
  27776. }
  27777. return basic.compare( shadowCoord.z );
  27778. } );
  27779. /**
  27780. * A shadow filtering function performing PCF filtering.
  27781. *
  27782. * @method
  27783. * @param {Object} inputs - The input parameter object.
  27784. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  27785. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  27786. * @param {LightShadow} inputs.shadow - The light shadow.
  27787. * @return {Node<float>} The filtering result.
  27788. */
  27789. const PCFShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow, depthLayer } ) => {
  27790. const depthCompare = ( uv, compare ) => {
  27791. let depth = texture( depthTexture, uv );
  27792. if ( depthTexture.isArrayTexture ) {
  27793. depth = depth.depth( depthLayer );
  27794. }
  27795. return depth.compare( compare );
  27796. };
  27797. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  27798. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  27799. const texelSize = vec2( 1 ).div( mapSize );
  27800. const dx0 = texelSize.x.negate().mul( radius );
  27801. const dy0 = texelSize.y.negate().mul( radius );
  27802. const dx1 = texelSize.x.mul( radius );
  27803. const dy1 = texelSize.y.mul( radius );
  27804. const dx2 = dx0.div( 2 );
  27805. const dy2 = dy0.div( 2 );
  27806. const dx3 = dx1.div( 2 );
  27807. const dy3 = dy1.div( 2 );
  27808. return add(
  27809. depthCompare( shadowCoord.xy.add( vec2( dx0, dy0 ) ), shadowCoord.z ),
  27810. depthCompare( shadowCoord.xy.add( vec2( 0, dy0 ) ), shadowCoord.z ),
  27811. depthCompare( shadowCoord.xy.add( vec2( dx1, dy0 ) ), shadowCoord.z ),
  27812. depthCompare( shadowCoord.xy.add( vec2( dx2, dy2 ) ), shadowCoord.z ),
  27813. depthCompare( shadowCoord.xy.add( vec2( 0, dy2 ) ), shadowCoord.z ),
  27814. depthCompare( shadowCoord.xy.add( vec2( dx3, dy2 ) ), shadowCoord.z ),
  27815. depthCompare( shadowCoord.xy.add( vec2( dx0, 0 ) ), shadowCoord.z ),
  27816. depthCompare( shadowCoord.xy.add( vec2( dx2, 0 ) ), shadowCoord.z ),
  27817. depthCompare( shadowCoord.xy, shadowCoord.z ),
  27818. depthCompare( shadowCoord.xy.add( vec2( dx3, 0 ) ), shadowCoord.z ),
  27819. depthCompare( shadowCoord.xy.add( vec2( dx1, 0 ) ), shadowCoord.z ),
  27820. depthCompare( shadowCoord.xy.add( vec2( dx2, dy3 ) ), shadowCoord.z ),
  27821. depthCompare( shadowCoord.xy.add( vec2( 0, dy3 ) ), shadowCoord.z ),
  27822. depthCompare( shadowCoord.xy.add( vec2( dx3, dy3 ) ), shadowCoord.z ),
  27823. depthCompare( shadowCoord.xy.add( vec2( dx0, dy1 ) ), shadowCoord.z ),
  27824. depthCompare( shadowCoord.xy.add( vec2( 0, dy1 ) ), shadowCoord.z ),
  27825. depthCompare( shadowCoord.xy.add( vec2( dx1, dy1 ) ), shadowCoord.z )
  27826. ).mul( 1 / 17 );
  27827. } );
  27828. /**
  27829. * A shadow filtering function performing PCF soft filtering.
  27830. *
  27831. * @method
  27832. * @param {Object} inputs - The input parameter object.
  27833. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  27834. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  27835. * @param {LightShadow} inputs.shadow - The light shadow.
  27836. * @return {Node<float>} The filtering result.
  27837. */
  27838. const PCFSoftShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow, depthLayer } ) => {
  27839. const depthCompare = ( uv, compare ) => {
  27840. let depth = texture( depthTexture, uv );
  27841. if ( depthTexture.isArrayTexture ) {
  27842. depth = depth.depth( depthLayer );
  27843. }
  27844. return depth.compare( compare );
  27845. };
  27846. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  27847. const texelSize = vec2( 1 ).div( mapSize );
  27848. const dx = texelSize.x;
  27849. const dy = texelSize.y;
  27850. const uv = shadowCoord.xy;
  27851. const f = fract( uv.mul( mapSize ).add( 0.5 ) );
  27852. uv.subAssign( f.mul( texelSize ) );
  27853. return add(
  27854. depthCompare( uv, shadowCoord.z ),
  27855. depthCompare( uv.add( vec2( dx, 0 ) ), shadowCoord.z ),
  27856. depthCompare( uv.add( vec2( 0, dy ) ), shadowCoord.z ),
  27857. depthCompare( uv.add( texelSize ), shadowCoord.z ),
  27858. mix(
  27859. depthCompare( uv.add( vec2( dx.negate(), 0 ) ), shadowCoord.z ),
  27860. depthCompare( uv.add( vec2( dx.mul( 2 ), 0 ) ), shadowCoord.z ),
  27861. f.x
  27862. ),
  27863. mix(
  27864. depthCompare( uv.add( vec2( dx.negate(), dy ) ), shadowCoord.z ),
  27865. depthCompare( uv.add( vec2( dx.mul( 2 ), dy ) ), shadowCoord.z ),
  27866. f.x
  27867. ),
  27868. mix(
  27869. depthCompare( uv.add( vec2( 0, dy.negate() ) ), shadowCoord.z ),
  27870. depthCompare( uv.add( vec2( 0, dy.mul( 2 ) ) ), shadowCoord.z ),
  27871. f.y
  27872. ),
  27873. mix(
  27874. depthCompare( uv.add( vec2( dx, dy.negate() ) ), shadowCoord.z ),
  27875. depthCompare( uv.add( vec2( dx, dy.mul( 2 ) ) ), shadowCoord.z ),
  27876. f.y
  27877. ),
  27878. mix(
  27879. mix(
  27880. depthCompare( uv.add( vec2( dx.negate(), dy.negate() ) ), shadowCoord.z ),
  27881. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.negate() ) ), shadowCoord.z ),
  27882. f.x
  27883. ),
  27884. mix(
  27885. depthCompare( uv.add( vec2( dx.negate(), dy.mul( 2 ) ) ), shadowCoord.z ),
  27886. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.mul( 2 ) ) ), shadowCoord.z ),
  27887. f.x
  27888. ),
  27889. f.y
  27890. )
  27891. ).mul( 1 / 9 );
  27892. } );
  27893. /**
  27894. * A shadow filtering function performing VSM filtering.
  27895. *
  27896. * @method
  27897. * @param {Object} inputs - The input parameter object.
  27898. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  27899. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  27900. * @return {Node<float>} The filtering result.
  27901. */
  27902. const VSMShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, depthLayer } ) => {
  27903. const occlusion = float( 1 ).toVar();
  27904. let distribution = texture( depthTexture ).sample( shadowCoord.xy );
  27905. if ( depthTexture.isArrayTexture ) {
  27906. distribution = distribution.depth( depthLayer );
  27907. }
  27908. distribution = distribution.rg;
  27909. const hardShadow = step( shadowCoord.z, distribution.x );
  27910. If( hardShadow.notEqual( float( 1.0 ) ), () => {
  27911. const distance = shadowCoord.z.sub( distribution.x );
  27912. const variance = max$1( 0, distribution.y.mul( distribution.y ) );
  27913. let softnessProbability = variance.div( variance.add( distance.mul( distance ) ) ); // Chebeyshevs inequality
  27914. softnessProbability = clamp( sub( softnessProbability, 0.3 ).div( 0.95 - 0.3 ) );
  27915. occlusion.assign( clamp( max$1( hardShadow, softnessProbability ) ) );
  27916. } );
  27917. return occlusion;
  27918. } );
  27919. //
  27920. const linearDistance = /*@__PURE__*/ Fn( ( [ position, cameraNear, cameraFar ] ) => {
  27921. let dist = positionWorld.sub( position ).length();
  27922. dist = dist.sub( cameraNear ).div( cameraFar.sub( cameraNear ) );
  27923. dist = dist.saturate(); // clamp to [ 0, 1 ]
  27924. return dist;
  27925. } );
  27926. const linearShadowDistance = ( light ) => {
  27927. const camera = light.shadow.camera;
  27928. const nearDistance = reference( 'near', 'float', camera ).setGroup( renderGroup );
  27929. const farDistance = reference( 'far', 'float', camera ).setGroup( renderGroup );
  27930. const referencePosition = objectPosition( light );
  27931. return linearDistance( referencePosition, nearDistance, farDistance );
  27932. };
  27933. /**
  27934. * Retrieves or creates a shadow material for the given light source.
  27935. *
  27936. * This function checks if a shadow material already exists for the provided light.
  27937. * If not, it creates a new `NodeMaterial` configured for shadow rendering and stores it
  27938. * in the `shadowMaterialLib` for future use.
  27939. *
  27940. * @param {Light} light - The light source for which the shadow material is needed.
  27941. * If the light is a point light, a depth node is calculated
  27942. * using the linear shadow distance.
  27943. * @returns {NodeMaterial} The shadow material associated with the given light.
  27944. */
  27945. const getShadowMaterial = ( light ) => {
  27946. let material = shadowMaterialLib.get( light );
  27947. if ( material === undefined ) {
  27948. const depthNode = light.isPointLight ? linearShadowDistance( light ) : null;
  27949. material = new NodeMaterial();
  27950. material.colorNode = vec4( 0, 0, 0, 1 );
  27951. material.depthNode = depthNode;
  27952. material.isShadowPassMaterial = true; // Use to avoid other overrideMaterial override material.colorNode unintentionally when using material.shadowNode
  27953. material.name = 'ShadowMaterial';
  27954. material.fog = false;
  27955. shadowMaterialLib.set( light, material );
  27956. }
  27957. return material;
  27958. };
  27959. //
  27960. const _shadowRenderObjectLibrary = /*@__PURE__*/ new ChainMap();
  27961. const _shadowRenderObjectKeys = [];
  27962. /**
  27963. * Creates a function to render shadow objects in a scene.
  27964. *
  27965. * @param {Renderer} renderer - The renderer.
  27966. * @param {LightShadow} shadow - The light shadow object containing shadow properties.
  27967. * @param {number} shadowType - The type of shadow map (e.g., BasicShadowMap).
  27968. * @param {boolean} useVelocity - Whether to use velocity data for rendering.
  27969. * @return {Function} A function that renders shadow objects.
  27970. *
  27971. * The returned function has the following parameters:
  27972. * @param {Object3D} object - The 3D object to render.
  27973. * @param {Scene} scene - The scene containing the object.
  27974. * @param {Camera} _camera - The camera used for rendering.
  27975. * @param {BufferGeometry} geometry - The geometry of the object.
  27976. * @param {Material} material - The material of the object.
  27977. * @param {Group} group - The group the object belongs to.
  27978. * @param {...any} params - Additional parameters for rendering.
  27979. */
  27980. const getShadowRenderObjectFunction = ( renderer, shadow, shadowType, useVelocity ) => {
  27981. _shadowRenderObjectKeys[ 0 ] = renderer;
  27982. _shadowRenderObjectKeys[ 1 ] = shadow;
  27983. let renderObjectFunction = _shadowRenderObjectLibrary.get( _shadowRenderObjectKeys );
  27984. if ( renderObjectFunction === undefined || ( renderObjectFunction.shadowType !== shadowType || renderObjectFunction.useVelocity !== useVelocity ) ) {
  27985. renderObjectFunction = ( object, scene, _camera, geometry, material, group, ...params ) => {
  27986. if ( object.castShadow === true || ( object.receiveShadow && shadowType === VSMShadowMap ) ) {
  27987. if ( useVelocity ) {
  27988. getDataFromObject( object ).useVelocity = true;
  27989. }
  27990. object.onBeforeShadow( renderer, object, _camera, shadow.camera, geometry, scene.overrideMaterial, group );
  27991. renderer.renderObject( object, scene, _camera, geometry, material, group, ...params );
  27992. object.onAfterShadow( renderer, object, _camera, shadow.camera, geometry, scene.overrideMaterial, group );
  27993. }
  27994. };
  27995. renderObjectFunction.shadowType = shadowType;
  27996. renderObjectFunction.useVelocity = useVelocity;
  27997. _shadowRenderObjectLibrary.set( _shadowRenderObjectKeys, renderObjectFunction );
  27998. }
  27999. _shadowRenderObjectKeys[ 0 ] = null;
  28000. _shadowRenderObjectKeys[ 1 ] = null;
  28001. return renderObjectFunction;
  28002. };
  28003. /**
  28004. * Represents the shader code for the first VSM render pass.
  28005. *
  28006. * @method
  28007. * @param {Object} inputs - The input parameter object.
  28008. * @param {Node<float>} inputs.samples - The number of samples
  28009. * @param {Node<float>} inputs.radius - The radius.
  28010. * @param {Node<float>} inputs.size - The size.
  28011. * @param {TextureNode} inputs.shadowPass - A reference to the render target's depth data.
  28012. * @return {Node<vec2>} The VSM output.
  28013. */
  28014. const VSMPassVertical = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass, depthLayer } ) => {
  28015. const mean = float( 0 ).toVar( 'meanVertical' );
  28016. const squaredMean = float( 0 ).toVar( 'squareMeanVertical' );
  28017. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  28018. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( -1 ) );
  28019. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  28020. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  28021. let depth = shadowPass.sample( add( screenCoordinate.xy, vec2( 0, uvOffset ).mul( radius ) ).div( size ) );
  28022. if ( shadowPass.value.isArrayTexture ) {
  28023. depth = depth.depth( depthLayer );
  28024. }
  28025. depth = depth.x;
  28026. mean.addAssign( depth );
  28027. squaredMean.addAssign( depth.mul( depth ) );
  28028. } );
  28029. mean.divAssign( samples );
  28030. squaredMean.divAssign( samples );
  28031. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  28032. return vec2( mean, std_dev );
  28033. } );
  28034. /**
  28035. * Represents the shader code for the second VSM render pass.
  28036. *
  28037. * @method
  28038. * @param {Object} inputs - The input parameter object.
  28039. * @param {Node<float>} inputs.samples - The number of samples
  28040. * @param {Node<float>} inputs.radius - The radius.
  28041. * @param {Node<float>} inputs.size - The size.
  28042. * @param {TextureNode} inputs.shadowPass - The result of the first VSM render pass.
  28043. * @return {Node<vec2>} The VSM output.
  28044. */
  28045. const VSMPassHorizontal = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass, depthLayer } ) => {
  28046. const mean = float( 0 ).toVar( 'meanHorizontal' );
  28047. const squaredMean = float( 0 ).toVar( 'squareMeanHorizontal' );
  28048. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  28049. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( -1 ) );
  28050. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  28051. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  28052. let distribution = shadowPass.sample( add( screenCoordinate.xy, vec2( uvOffset, 0 ).mul( radius ) ).div( size ) );
  28053. if ( shadowPass.value.isArrayTexture ) {
  28054. distribution = distribution.depth( depthLayer );
  28055. }
  28056. mean.addAssign( distribution.x );
  28057. squaredMean.addAssign( add( distribution.y.mul( distribution.y ), distribution.x.mul( distribution.x ) ) );
  28058. } );
  28059. mean.divAssign( samples );
  28060. squaredMean.divAssign( samples );
  28061. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  28062. return vec2( mean, std_dev );
  28063. } );
  28064. const _shadowFilterLib = [ BasicShadowFilter, PCFShadowFilter, PCFSoftShadowFilter, VSMShadowFilter ];
  28065. //
  28066. let _rendererState;
  28067. const _quadMesh = /*@__PURE__*/ new QuadMesh();
  28068. /**
  28069. * Represents the default shadow implementation for lighting nodes.
  28070. *
  28071. * @augments ShadowBaseNode
  28072. */
  28073. class ShadowNode extends ShadowBaseNode {
  28074. static get type() {
  28075. return 'ShadowNode';
  28076. }
  28077. /**
  28078. * Constructs a new shadow node.
  28079. *
  28080. * @param {Light} light - The shadow casting light.
  28081. * @param {?LightShadow} [shadow=null] - An optional light shadow.
  28082. */
  28083. constructor( light, shadow = null ) {
  28084. super( light );
  28085. /**
  28086. * The light shadow which defines the properties light's
  28087. * shadow.
  28088. *
  28089. * @type {?LightShadow}
  28090. * @default null
  28091. */
  28092. this.shadow = shadow || light.shadow;
  28093. /**
  28094. * A reference to the shadow map which is a render target.
  28095. *
  28096. * @type {?RenderTarget}
  28097. * @default null
  28098. */
  28099. this.shadowMap = null;
  28100. /**
  28101. * Only relevant for VSM shadows. Render target for the
  28102. * first VSM render pass.
  28103. *
  28104. * @type {?RenderTarget}
  28105. * @default null
  28106. */
  28107. this.vsmShadowMapVertical = null;
  28108. /**
  28109. * Only relevant for VSM shadows. Render target for the
  28110. * second VSM render pass.
  28111. *
  28112. * @type {?RenderTarget}
  28113. * @default null
  28114. */
  28115. this.vsmShadowMapHorizontal = null;
  28116. /**
  28117. * Only relevant for VSM shadows. Node material which
  28118. * is used to render the first VSM pass.
  28119. *
  28120. * @type {?NodeMaterial}
  28121. * @default null
  28122. */
  28123. this.vsmMaterialVertical = null;
  28124. /**
  28125. * Only relevant for VSM shadows. Node material which
  28126. * is used to render the second VSM pass.
  28127. *
  28128. * @type {?NodeMaterial}
  28129. * @default null
  28130. */
  28131. this.vsmMaterialHorizontal = null;
  28132. /**
  28133. * A reference to the output node which defines the
  28134. * final result of this shadow node.
  28135. *
  28136. * @type {?Node}
  28137. * @private
  28138. * @default null
  28139. */
  28140. this._node = null;
  28141. this._cameraFrameId = new WeakMap();
  28142. /**
  28143. * This flag can be used for type testing.
  28144. *
  28145. * @type {boolean}
  28146. * @readonly
  28147. * @default true
  28148. */
  28149. this.isShadowNode = true;
  28150. /**
  28151. * This index can be used when overriding setupRenderTarget with a RenderTarget Array to specify the depth layer.
  28152. *
  28153. * @type {number}
  28154. * @readonly
  28155. * @default true
  28156. */
  28157. this.depthLayer = 0;
  28158. }
  28159. /**
  28160. * Setups the shadow filtering.
  28161. *
  28162. * @param {NodeBuilder} builder - A reference to the current node builder.
  28163. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  28164. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  28165. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  28166. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  28167. * @param {LightShadow} inputs.shadow - The light shadow.
  28168. * @return {Node<float>} The result node of the shadow filtering.
  28169. */
  28170. setupShadowFilter( builder, { filterFn, depthTexture, shadowCoord, shadow, depthLayer } ) {
  28171. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  28172. .and( shadowCoord.x.lessThanEqual( 1 ) )
  28173. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  28174. .and( shadowCoord.y.lessThanEqual( 1 ) )
  28175. .and( shadowCoord.z.lessThanEqual( 1 ) );
  28176. const shadowNode = filterFn( { depthTexture, shadowCoord, shadow, depthLayer } );
  28177. return frustumTest.select( shadowNode, float( 1 ) );
  28178. }
  28179. /**
  28180. * Setups the shadow coordinates.
  28181. *
  28182. * @param {NodeBuilder} builder - A reference to the current node builder.
  28183. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  28184. * @return {Node<vec3>} The shadow coordinates.
  28185. */
  28186. setupShadowCoord( builder, shadowPosition ) {
  28187. const { shadow } = this;
  28188. const { renderer } = builder;
  28189. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  28190. let shadowCoord = shadowPosition;
  28191. let coordZ;
  28192. if ( shadow.camera.isOrthographicCamera || renderer.logarithmicDepthBuffer !== true ) {
  28193. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  28194. coordZ = shadowCoord.z;
  28195. if ( renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  28196. coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Conversion [ 0, 1 ] to [ - 1, 1 ]
  28197. }
  28198. } else {
  28199. const w = shadowCoord.w;
  28200. shadowCoord = shadowCoord.xy.div( w ); // <-- Only divide X/Y coords since we don't need Z
  28201. // The normally available "cameraNear" and "cameraFar" nodes cannot be used here because they do not get
  28202. // updated to use the shadow camera. So, we have to declare our own "local" ones here.
  28203. // TODO: How do we get the cameraNear/cameraFar nodes to use the shadow camera so we don't have to declare local ones here?
  28204. const cameraNearLocal = reference( 'near', 'float', shadow.camera ).setGroup( renderGroup );
  28205. const cameraFarLocal = reference( 'far', 'float', shadow.camera ).setGroup( renderGroup );
  28206. coordZ = viewZToLogarithmicDepth( w.negate(), cameraNearLocal, cameraFarLocal );
  28207. }
  28208. shadowCoord = vec3(
  28209. shadowCoord.x,
  28210. shadowCoord.y.oneMinus(), // follow webgpu standards
  28211. coordZ.add( bias )
  28212. );
  28213. return shadowCoord;
  28214. }
  28215. /**
  28216. * Returns the shadow filtering function for the given shadow type.
  28217. *
  28218. * @param {number} type - The shadow type.
  28219. * @return {Function} The filtering function.
  28220. */
  28221. getShadowFilterFn( type ) {
  28222. return _shadowFilterLib[ type ];
  28223. }
  28224. setupRenderTarget( shadow, builder ) {
  28225. const depthTexture = new DepthTexture( shadow.mapSize.width, shadow.mapSize.height );
  28226. depthTexture.name = 'ShadowDepthTexture';
  28227. depthTexture.compareFunction = LessCompare;
  28228. const shadowMap = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  28229. shadowMap.texture.name = 'ShadowMap';
  28230. shadowMap.texture.type = shadow.mapType;
  28231. shadowMap.depthTexture = depthTexture;
  28232. return { shadowMap, depthTexture };
  28233. }
  28234. /**
  28235. * Setups the shadow output node.
  28236. *
  28237. * @param {NodeBuilder} builder - A reference to the current node builder.
  28238. * @return {Node<vec3>} The shadow output node.
  28239. */
  28240. setupShadow( builder ) {
  28241. const { renderer } = builder;
  28242. const { light, shadow } = this;
  28243. const shadowMapType = renderer.shadowMap.type;
  28244. const { depthTexture, shadowMap } = this.setupRenderTarget( shadow, builder );
  28245. shadow.camera.updateProjectionMatrix();
  28246. // VSM
  28247. if ( shadowMapType === VSMShadowMap && shadow.isPointLightShadow !== true ) {
  28248. depthTexture.compareFunction = null; // VSM does not use textureSampleCompare()/texture2DCompare()
  28249. if ( shadowMap.depth > 1 ) {
  28250. if ( ! shadowMap._vsmShadowMapVertical ) {
  28251. shadowMap._vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depth: shadowMap.depth, depthBuffer: false } );
  28252. shadowMap._vsmShadowMapVertical.texture.name = 'VSMVertical';
  28253. }
  28254. this.vsmShadowMapVertical = shadowMap._vsmShadowMapVertical;
  28255. if ( ! shadowMap._vsmShadowMapHorizontal ) {
  28256. shadowMap._vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depth: shadowMap.depth, depthBuffer: false } );
  28257. shadowMap._vsmShadowMapHorizontal.texture.name = 'VSMHorizontal';
  28258. }
  28259. this.vsmShadowMapHorizontal = shadowMap._vsmShadowMapHorizontal;
  28260. } else {
  28261. this.vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depthBuffer: false } );
  28262. this.vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depthBuffer: false } );
  28263. }
  28264. let shadowPassVertical = texture( depthTexture );
  28265. if ( depthTexture.isArrayTexture ) {
  28266. shadowPassVertical = shadowPassVertical.depth( this.depthLayer );
  28267. }
  28268. let shadowPassHorizontal = texture( this.vsmShadowMapVertical.texture );
  28269. if ( depthTexture.isArrayTexture ) {
  28270. shadowPassHorizontal = shadowPassHorizontal.depth( this.depthLayer );
  28271. }
  28272. const samples = reference( 'blurSamples', 'float', shadow ).setGroup( renderGroup );
  28273. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  28274. const size = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  28275. let material = this.vsmMaterialVertical || ( this.vsmMaterialVertical = new NodeMaterial() );
  28276. material.fragmentNode = VSMPassVertical( { samples, radius, size, shadowPass: shadowPassVertical, depthLayer: this.depthLayer } ).context( builder.getSharedContext() );
  28277. material.name = 'VSMVertical';
  28278. material = this.vsmMaterialHorizontal || ( this.vsmMaterialHorizontal = new NodeMaterial() );
  28279. material.fragmentNode = VSMPassHorizontal( { samples, radius, size, shadowPass: shadowPassHorizontal, depthLayer: this.depthLayer } ).context( builder.getSharedContext() );
  28280. material.name = 'VSMHorizontal';
  28281. }
  28282. //
  28283. const shadowIntensity = reference( 'intensity', 'float', shadow ).setGroup( renderGroup );
  28284. const normalBias = reference( 'normalBias', 'float', shadow ).setGroup( renderGroup );
  28285. const shadowPosition = lightShadowMatrix( light ).mul( shadowPositionWorld.add( normalWorld.mul( normalBias ) ) );
  28286. const shadowCoord = this.setupShadowCoord( builder, shadowPosition );
  28287. //
  28288. const filterFn = shadow.filterNode || this.getShadowFilterFn( renderer.shadowMap.type ) || null;
  28289. if ( filterFn === null ) {
  28290. throw new Error( 'THREE.WebGPURenderer: Shadow map type not supported yet.' );
  28291. }
  28292. const shadowDepthTexture = ( shadowMapType === VSMShadowMap && shadow.isPointLightShadow !== true ) ? this.vsmShadowMapHorizontal.texture : depthTexture;
  28293. const shadowNode = this.setupShadowFilter( builder, { filterFn, shadowTexture: shadowMap.texture, depthTexture: shadowDepthTexture, shadowCoord, shadow, depthLayer: this.depthLayer } );
  28294. let shadowColor = texture( shadowMap.texture, shadowCoord );
  28295. if ( depthTexture.isArrayTexture ) {
  28296. shadowColor = shadowColor.depth( this.depthLayer );
  28297. }
  28298. const shadowOutput = mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) ).toVar();
  28299. this.shadowMap = shadowMap;
  28300. this.shadow.map = shadowMap;
  28301. return shadowOutput;
  28302. }
  28303. /**
  28304. * The implementation performs the setup of the output node. An output is only
  28305. * produces if shadow mapping is globally enabled in the renderer.
  28306. *
  28307. * @param {NodeBuilder} builder - A reference to the current node builder.
  28308. * @return {ShaderCallNodeInternal} The output node.
  28309. */
  28310. setup( builder ) {
  28311. if ( builder.renderer.shadowMap.enabled === false ) return;
  28312. return Fn( () => {
  28313. let node = this._node;
  28314. this.setupShadowPosition( builder );
  28315. if ( node === null ) {
  28316. this._node = node = this.setupShadow( builder );
  28317. }
  28318. if ( builder.material.shadowNode ) { // @deprecated, r171
  28319. console.warn( 'THREE.NodeMaterial: ".shadowNode" is deprecated. Use ".castShadowNode" instead.' );
  28320. }
  28321. if ( builder.material.receivedShadowNode ) {
  28322. node = builder.material.receivedShadowNode( node );
  28323. }
  28324. return node;
  28325. } )();
  28326. }
  28327. /**
  28328. * Renders the shadow. The logic of this function could be included
  28329. * into {@link ShadowNode#updateShadow} however more specialized shadow
  28330. * nodes might require a custom shadow map rendering. By having a
  28331. * dedicated method, it's easier to overwrite the default behavior.
  28332. *
  28333. * @param {NodeFrame} frame - A reference to the current node frame.
  28334. */
  28335. renderShadow( frame ) {
  28336. const { shadow, shadowMap, light } = this;
  28337. const { renderer, scene } = frame;
  28338. shadow.updateMatrices( light );
  28339. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.height, shadowMap.depth );
  28340. renderer.render( scene, shadow.camera );
  28341. }
  28342. /**
  28343. * Updates the shadow.
  28344. *
  28345. * @param {NodeFrame} frame - A reference to the current node frame.
  28346. */
  28347. updateShadow( frame ) {
  28348. const { shadowMap, light, shadow } = this;
  28349. const { renderer, scene, camera } = frame;
  28350. const shadowType = renderer.shadowMap.type;
  28351. const depthVersion = shadowMap.depthTexture.version;
  28352. this._depthVersionCached = depthVersion;
  28353. const _shadowCameraLayer = shadow.camera.layers.mask;
  28354. if ( ( shadow.camera.layers.mask & 0xFFFFFFFE ) === 0 ) {
  28355. shadow.camera.layers.mask = camera.layers.mask;
  28356. }
  28357. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  28358. const currentMRT = renderer.getMRT();
  28359. const useVelocity = currentMRT ? currentMRT.has( 'velocity' ) : false;
  28360. _rendererState = resetRendererAndSceneState( renderer, scene, _rendererState );
  28361. scene.overrideMaterial = getShadowMaterial( light );
  28362. renderer.setRenderObjectFunction( getShadowRenderObjectFunction( renderer, shadow, shadowType, useVelocity ) );
  28363. renderer.setClearColor( 0x000000, 0 );
  28364. renderer.setRenderTarget( shadowMap );
  28365. this.renderShadow( frame );
  28366. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  28367. // vsm blur pass
  28368. if ( shadowType === VSMShadowMap && shadow.isPointLightShadow !== true ) {
  28369. this.vsmPass( renderer );
  28370. }
  28371. shadow.camera.layers.mask = _shadowCameraLayer;
  28372. restoreRendererAndSceneState( renderer, scene, _rendererState );
  28373. }
  28374. /**
  28375. * For VSM additional render passes are required.
  28376. *
  28377. * @param {Renderer} renderer - A reference to the current renderer.
  28378. */
  28379. vsmPass( renderer ) {
  28380. const { shadow } = this;
  28381. const depth = this.shadowMap.depth;
  28382. this.vsmShadowMapVertical.setSize( shadow.mapSize.width, shadow.mapSize.height, depth );
  28383. this.vsmShadowMapHorizontal.setSize( shadow.mapSize.width, shadow.mapSize.height, depth );
  28384. renderer.setRenderTarget( this.vsmShadowMapVertical );
  28385. _quadMesh.material = this.vsmMaterialVertical;
  28386. _quadMesh.render( renderer );
  28387. renderer.setRenderTarget( this.vsmShadowMapHorizontal );
  28388. _quadMesh.material = this.vsmMaterialHorizontal;
  28389. _quadMesh.render( renderer );
  28390. }
  28391. /**
  28392. * Frees the internal resources of this shadow node.
  28393. */
  28394. dispose() {
  28395. this.shadowMap.dispose();
  28396. this.shadowMap = null;
  28397. if ( this.vsmShadowMapVertical !== null ) {
  28398. this.vsmShadowMapVertical.dispose();
  28399. this.vsmShadowMapVertical = null;
  28400. this.vsmMaterialVertical.dispose();
  28401. this.vsmMaterialVertical = null;
  28402. }
  28403. if ( this.vsmShadowMapHorizontal !== null ) {
  28404. this.vsmShadowMapHorizontal.dispose();
  28405. this.vsmShadowMapHorizontal = null;
  28406. this.vsmMaterialHorizontal.dispose();
  28407. this.vsmMaterialHorizontal = null;
  28408. }
  28409. super.dispose();
  28410. }
  28411. /**
  28412. * The implementation performs the update of the shadow map if necessary.
  28413. *
  28414. * @param {NodeFrame} frame - A reference to the current node frame.
  28415. */
  28416. updateBefore( frame ) {
  28417. const { shadow } = this;
  28418. let needsUpdate = shadow.needsUpdate || shadow.autoUpdate;
  28419. if ( needsUpdate ) {
  28420. if ( this._cameraFrameId[ frame.camera ] === frame.frameId ) {
  28421. needsUpdate = false;
  28422. }
  28423. this._cameraFrameId[ frame.camera ] = frame.frameId;
  28424. }
  28425. if ( needsUpdate ) {
  28426. this.updateShadow( frame );
  28427. if ( this.shadowMap.depthTexture.version === this._depthVersionCached ) {
  28428. shadow.needsUpdate = false;
  28429. }
  28430. }
  28431. }
  28432. }
  28433. /**
  28434. * TSL function for creating an instance of `ShadowNode`.
  28435. *
  28436. * @tsl
  28437. * @function
  28438. * @param {Light} light - The shadow casting light.
  28439. * @param {?LightShadow} [shadow] - The light shadow.
  28440. * @return {ShadowNode} The created shadow node.
  28441. */
  28442. const shadow = ( light, shadow ) => nodeObject( new ShadowNode( light, shadow ) );
  28443. const _clearColor$1 = /*@__PURE__*/ new Color();
  28444. // cubeToUV() maps a 3D direction vector suitable for cube texture mapping to a 2D
  28445. // vector suitable for 2D texture mapping. This code uses the following layout for the
  28446. // 2D texture:
  28447. //
  28448. // xzXZ
  28449. // y Y
  28450. //
  28451. // Y - Positive y direction
  28452. // y - Negative y direction
  28453. // X - Positive x direction
  28454. // x - Negative x direction
  28455. // Z - Positive z direction
  28456. // z - Negative z direction
  28457. //
  28458. // Source and test bed:
  28459. // https://gist.github.com/tschw/da10c43c467ce8afd0c4
  28460. const cubeToUV = /*@__PURE__*/ Fn( ( [ pos, texelSizeY ] ) => {
  28461. const v = pos.toVar();
  28462. // Number of texels to avoid at the edge of each square
  28463. const absV = abs( v );
  28464. // Intersect unit cube
  28465. const scaleToCube = div( 1.0, max$1( absV.x, max$1( absV.y, absV.z ) ) );
  28466. absV.mulAssign( scaleToCube );
  28467. // Apply scale to avoid seams
  28468. // two texels less per square (one texel will do for NEAREST)
  28469. v.mulAssign( scaleToCube.mul( texelSizeY.mul( 2 ).oneMinus() ) );
  28470. // Unwrap
  28471. // space: -1 ... 1 range for each square
  28472. //
  28473. // #X## dim := ( 4 , 2 )
  28474. // # # center := ( 1 , 1 )
  28475. const planar = vec2( v.xy ).toVar();
  28476. const almostATexel = texelSizeY.mul( 1.5 );
  28477. const almostOne = almostATexel.oneMinus();
  28478. If( absV.z.greaterThanEqual( almostOne ), () => {
  28479. If( v.z.greaterThan( 0.0 ), () => {
  28480. planar.x.assign( sub( 4.0, v.x ) );
  28481. } );
  28482. } ).ElseIf( absV.x.greaterThanEqual( almostOne ), () => {
  28483. const signX = sign( v.x );
  28484. planar.x.assign( v.z.mul( signX ).add( signX.mul( 2.0 ) ) );
  28485. } ).ElseIf( absV.y.greaterThanEqual( almostOne ), () => {
  28486. const signY = sign( v.y );
  28487. planar.x.assign( v.x.add( signY.mul( 2.0 ) ).add( 2.0 ) );
  28488. planar.y.assign( v.z.mul( signY ).sub( 2.0 ) );
  28489. } );
  28490. // Transform to UV space
  28491. // scale := 0.5 / dim
  28492. // translate := ( center + 0.5 ) / dim
  28493. return vec2( 0.125, 0.25 ).mul( planar ).add( vec2( 0.375, 0.75 ) ).flipY();
  28494. } ).setLayout( {
  28495. name: 'cubeToUV',
  28496. type: 'vec2',
  28497. inputs: [
  28498. { name: 'pos', type: 'vec3' },
  28499. { name: 'texelSizeY', type: 'float' }
  28500. ]
  28501. } );
  28502. const BasicPointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize } ) => {
  28503. return texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp );
  28504. } );
  28505. const PointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize, shadow } ) => {
  28506. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  28507. const offset = vec2( -1, 1.0 ).mul( radius ).mul( texelSize.y );
  28508. return texture( depthTexture, cubeToUV( bd3D.add( offset.xyy ), texelSize.y ) ).compare( dp )
  28509. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyy ), texelSize.y ) ).compare( dp ) )
  28510. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xyx ), texelSize.y ) ).compare( dp ) )
  28511. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyx ), texelSize.y ) ).compare( dp ) )
  28512. .add( texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp ) )
  28513. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxy ), texelSize.y ) ).compare( dp ) )
  28514. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxy ), texelSize.y ) ).compare( dp ) )
  28515. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxx ), texelSize.y ) ).compare( dp ) )
  28516. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxx ), texelSize.y ) ).compare( dp ) )
  28517. .mul( 1.0 / 9.0 );
  28518. } );
  28519. const pointShadowFilter = /*@__PURE__*/ Fn( ( { filterFn, depthTexture, shadowCoord, shadow } ) => {
  28520. // for point lights, the uniform @vShadowCoord is re-purposed to hold
  28521. // the vector from the light to the world-space position of the fragment.
  28522. const lightToPosition = shadowCoord.xyz.toVar();
  28523. const lightToPositionLength = lightToPosition.length();
  28524. const cameraNearLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.near );
  28525. const cameraFarLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.far );
  28526. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  28527. const mapSize = uniform( shadow.mapSize ).setGroup( renderGroup );
  28528. const result = float( 1.0 ).toVar();
  28529. If( lightToPositionLength.sub( cameraFarLocal ).lessThanEqual( 0.0 ).and( lightToPositionLength.sub( cameraNearLocal ).greaterThanEqual( 0.0 ) ), () => {
  28530. // dp = normalized distance from light to fragment position
  28531. const dp = lightToPositionLength.sub( cameraNearLocal ).div( cameraFarLocal.sub( cameraNearLocal ) ).toVar(); // need to clamp?
  28532. dp.addAssign( bias );
  28533. // bd3D = base direction 3D
  28534. const bd3D = lightToPosition.normalize();
  28535. const texelSize = vec2( 1.0 ).div( mapSize.mul( vec2( 4.0, 2.0 ) ) );
  28536. // percentage-closer filtering
  28537. result.assign( filterFn( { depthTexture, bd3D, dp, texelSize, shadow } ) );
  28538. } );
  28539. return result;
  28540. } );
  28541. const _viewport = /*@__PURE__*/ new Vector4();
  28542. const _viewportSize = /*@__PURE__*/ new Vector2();
  28543. const _shadowMapSize = /*@__PURE__*/ new Vector2();
  28544. /**
  28545. * Represents the shadow implementation for point light nodes.
  28546. *
  28547. * @augments ShadowNode
  28548. */
  28549. class PointShadowNode extends ShadowNode {
  28550. static get type() {
  28551. return 'PointShadowNode';
  28552. }
  28553. /**
  28554. * Constructs a new point shadow node.
  28555. *
  28556. * @param {PointLight} light - The shadow casting point light.
  28557. * @param {?PointLightShadow} [shadow=null] - An optional point light shadow.
  28558. */
  28559. constructor( light, shadow = null ) {
  28560. super( light, shadow );
  28561. }
  28562. /**
  28563. * Overwrites the default implementation to return point light shadow specific
  28564. * filtering functions.
  28565. *
  28566. * @param {number} type - The shadow type.
  28567. * @return {Function} The filtering function.
  28568. */
  28569. getShadowFilterFn( type ) {
  28570. return type === BasicShadowMap ? BasicPointShadowFilter : PointShadowFilter;
  28571. }
  28572. /**
  28573. * Overwrites the default implementation so the unaltered shadow position is used.
  28574. *
  28575. * @param {NodeBuilder} builder - A reference to the current node builder.
  28576. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  28577. * @return {Node<vec3>} The shadow coordinates.
  28578. */
  28579. setupShadowCoord( builder, shadowPosition ) {
  28580. return shadowPosition;
  28581. }
  28582. /**
  28583. * Overwrites the default implementation to only use point light specific
  28584. * shadow filter functions.
  28585. *
  28586. * @param {NodeBuilder} builder - A reference to the current node builder.
  28587. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  28588. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  28589. * @param {Texture} inputs.shadowTexture - A reference to the shadow map's texture.
  28590. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  28591. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  28592. * @param {LightShadow} inputs.shadow - The light shadow.
  28593. * @return {Node<float>} The result node of the shadow filtering.
  28594. */
  28595. setupShadowFilter( builder, { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } ) {
  28596. return pointShadowFilter( { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } );
  28597. }
  28598. /**
  28599. * Overwrites the default implementation with point light specific
  28600. * rendering code.
  28601. *
  28602. * @param {NodeFrame} frame - A reference to the current node frame.
  28603. */
  28604. renderShadow( frame ) {
  28605. const { shadow, shadowMap, light } = this;
  28606. const { renderer, scene } = frame;
  28607. const shadowFrameExtents = shadow.getFrameExtents();
  28608. _shadowMapSize.copy( shadow.mapSize );
  28609. _shadowMapSize.multiply( shadowFrameExtents );
  28610. shadowMap.setSize( _shadowMapSize.width, _shadowMapSize.height );
  28611. _viewportSize.copy( shadow.mapSize );
  28612. //
  28613. const previousAutoClear = renderer.autoClear;
  28614. const previousClearColor = renderer.getClearColor( _clearColor$1 );
  28615. const previousClearAlpha = renderer.getClearAlpha();
  28616. renderer.autoClear = false;
  28617. renderer.setClearColor( shadow.clearColor, shadow.clearAlpha );
  28618. renderer.clear();
  28619. const viewportCount = shadow.getViewportCount();
  28620. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  28621. const viewport = shadow.getViewport( vp );
  28622. const x = _viewportSize.x * viewport.x;
  28623. const y = _shadowMapSize.y - _viewportSize.y - ( _viewportSize.y * viewport.y );
  28624. _viewport.set(
  28625. x,
  28626. y,
  28627. _viewportSize.x * viewport.z,
  28628. _viewportSize.y * viewport.w
  28629. );
  28630. shadowMap.viewport.copy( _viewport );
  28631. shadow.updateMatrices( light, vp );
  28632. renderer.render( scene, shadow.camera );
  28633. }
  28634. //
  28635. renderer.autoClear = previousAutoClear;
  28636. renderer.setClearColor( previousClearColor, previousClearAlpha );
  28637. }
  28638. }
  28639. /**
  28640. * TSL function for creating an instance of `PointShadowNode`.
  28641. *
  28642. * @tsl
  28643. * @function
  28644. * @param {PointLight} light - The shadow casting point light.
  28645. * @param {?PointLightShadow} [shadow=null] - An optional point light shadow.
  28646. * @return {PointShadowNode} The created point shadow node.
  28647. */
  28648. const pointShadow = ( light, shadow ) => nodeObject( new PointShadowNode( light, shadow ) );
  28649. /**
  28650. * Base class for analytic light nodes.
  28651. *
  28652. * @augments LightingNode
  28653. */
  28654. class AnalyticLightNode extends LightingNode {
  28655. static get type() {
  28656. return 'AnalyticLightNode';
  28657. }
  28658. /**
  28659. * Constructs a new analytic light node.
  28660. *
  28661. * @param {?Light} [light=null] - The light source.
  28662. */
  28663. constructor( light = null ) {
  28664. super();
  28665. /**
  28666. * The light source.
  28667. *
  28668. * @type {?Light}
  28669. * @default null
  28670. */
  28671. this.light = light;
  28672. /**
  28673. * The light's color value.
  28674. *
  28675. * @type {Color}
  28676. */
  28677. this.color = new Color();
  28678. /**
  28679. * The light's color node. Points to `colorNode` of the light source, if set. Otherwise
  28680. * it creates a uniform node based on {@link AnalyticLightNode#color}.
  28681. *
  28682. * @type {Node}
  28683. */
  28684. this.colorNode = ( light && light.colorNode ) || uniform( this.color ).setGroup( renderGroup );
  28685. /**
  28686. * This property is used to retain a reference to the original value of {@link AnalyticLightNode#colorNode}.
  28687. * The final color node is represented by a different node when using shadows.
  28688. *
  28689. * @type {?Node}
  28690. * @default null
  28691. */
  28692. this.baseColorNode = null;
  28693. /**
  28694. * Represents the light's shadow.
  28695. *
  28696. * @type {?ShadowNode}
  28697. * @default null
  28698. */
  28699. this.shadowNode = null;
  28700. /**
  28701. * Represents the light's shadow color.
  28702. *
  28703. * @type {?Node}
  28704. * @default null
  28705. */
  28706. this.shadowColorNode = null;
  28707. /**
  28708. * This flag can be used for type testing.
  28709. *
  28710. * @type {boolean}
  28711. * @readonly
  28712. * @default true
  28713. */
  28714. this.isAnalyticLightNode = true;
  28715. /**
  28716. * Overwritten since analytic light nodes are updated
  28717. * once per frame.
  28718. *
  28719. * @type {string}
  28720. * @default 'frame'
  28721. */
  28722. this.updateType = NodeUpdateType.FRAME;
  28723. }
  28724. getHash() {
  28725. return this.light.uuid;
  28726. }
  28727. /**
  28728. * Returns a node representing a direction vector which points from the current
  28729. * position in view space to the light's position in view space.
  28730. *
  28731. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  28732. * @return {Node<vec3>} The light vector node.
  28733. */
  28734. getLightVector( builder ) {
  28735. return lightViewPosition( this.light ).sub( builder.context.positionView || positionView );
  28736. }
  28737. /**
  28738. * Sets up the direct lighting for the analytic light node.
  28739. *
  28740. * @abstract
  28741. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  28742. * @return {Object|undefined} The direct light data (color and direction).
  28743. */
  28744. setupDirect( /*builder*/ ) { }
  28745. /**
  28746. * Sets up the direct rect area lighting for the analytic light node.
  28747. *
  28748. * @abstract
  28749. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  28750. * @return {Object|undefined} The direct rect area light data.
  28751. */
  28752. setupDirectRectArea( /*builder*/ ) { }
  28753. /**
  28754. * Setups the shadow node for this light. The method exists so concrete light classes
  28755. * can setup different types of shadow nodes.
  28756. *
  28757. * @return {ShadowNode} The created shadow node.
  28758. */
  28759. setupShadowNode() {
  28760. return shadow( this.light );
  28761. }
  28762. /**
  28763. * Setups the shadow for this light. This method is only executed if the light
  28764. * cast shadows and the current build object receives shadows. It incorporates
  28765. * shadows into the lighting computation.
  28766. *
  28767. * @param {NodeBuilder} builder - The current node builder.
  28768. */
  28769. setupShadow( builder ) {
  28770. const { renderer } = builder;
  28771. if ( renderer.shadowMap.enabled === false ) return;
  28772. let shadowColorNode = this.shadowColorNode;
  28773. if ( shadowColorNode === null ) {
  28774. const customShadowNode = this.light.shadow.shadowNode;
  28775. let shadowNode;
  28776. if ( customShadowNode !== undefined ) {
  28777. shadowNode = nodeObject( customShadowNode );
  28778. } else {
  28779. shadowNode = this.setupShadowNode();
  28780. }
  28781. this.shadowNode = shadowNode;
  28782. this.shadowColorNode = shadowColorNode = this.colorNode.mul( shadowNode );
  28783. this.baseColorNode = this.colorNode;
  28784. }
  28785. //
  28786. this.colorNode = shadowColorNode;
  28787. }
  28788. /**
  28789. * Unlike most other nodes, lighting nodes do not return a output node in {@link Node#setup}.
  28790. * The main purpose of lighting nodes is to configure the current {@link LightingModel} and/or
  28791. * invocate the respective interface methods.
  28792. *
  28793. * @param {NodeBuilder} builder - The current node builder.
  28794. */
  28795. setup( builder ) {
  28796. this.colorNode = this.baseColorNode || this.colorNode;
  28797. if ( this.light.castShadow ) {
  28798. if ( builder.object.receiveShadow ) {
  28799. this.setupShadow( builder );
  28800. }
  28801. } else if ( this.shadowNode !== null ) {
  28802. this.shadowNode.dispose();
  28803. this.shadowNode = null;
  28804. this.shadowColorNode = null;
  28805. }
  28806. const directLightData = this.setupDirect( builder );
  28807. const directRectAreaLightData = this.setupDirectRectArea( builder );
  28808. if ( directLightData ) {
  28809. builder.lightsNode.setupDirectLight( builder, this, directLightData );
  28810. }
  28811. if ( directRectAreaLightData ) {
  28812. builder.lightsNode.setupDirectRectAreaLight( builder, this, directRectAreaLightData );
  28813. }
  28814. }
  28815. /**
  28816. * The update method is used to update light uniforms per frame.
  28817. * Potentially overwritten in concrete light nodes to update light
  28818. * specific uniforms.
  28819. *
  28820. * @param {NodeFrame} frame - A reference to the current node frame.
  28821. */
  28822. update( /*frame*/ ) {
  28823. const { light } = this;
  28824. this.color.copy( light.color ).multiplyScalar( light.intensity );
  28825. }
  28826. }
  28827. /**
  28828. * Represents a `discard` shader operation in TSL.
  28829. *
  28830. * @method
  28831. * @param {Object} inputs - The input parameter object.
  28832. * @param {Node<float>} inputs.lightDistance - The distance of the light's position to the current fragment position.
  28833. * @param {Node<float>} inputs.cutoffDistance - The light's cutoff distance.
  28834. * @param {Node<float>} inputs.decayExponent - The light's decay exponent.
  28835. * @return {Node<float>} The distance falloff.
  28836. */
  28837. const getDistanceAttenuation = /*@__PURE__*/ Fn( ( { lightDistance, cutoffDistance, decayExponent } ) => {
  28838. // based upon Frostbite 3 Moving to Physically-based Rendering
  28839. // page 32, equation 26: E[window1]
  28840. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  28841. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  28842. return cutoffDistance.greaterThan( 0 ).select(
  28843. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  28844. distanceFalloff
  28845. );
  28846. } ); // validated
  28847. const directPointLight = ( { color, lightVector, cutoffDistance, decayExponent } ) => {
  28848. const lightDirection = lightVector.normalize();
  28849. const lightDistance = lightVector.length();
  28850. const attenuation = getDistanceAttenuation( {
  28851. lightDistance,
  28852. cutoffDistance,
  28853. decayExponent
  28854. } );
  28855. const lightColor = color.mul( attenuation );
  28856. return { lightDirection, lightColor };
  28857. };
  28858. /**
  28859. * Module for representing point lights as nodes.
  28860. *
  28861. * @augments AnalyticLightNode
  28862. */
  28863. class PointLightNode extends AnalyticLightNode {
  28864. static get type() {
  28865. return 'PointLightNode';
  28866. }
  28867. /**
  28868. * Constructs a new point light node.
  28869. *
  28870. * @param {?PointLight} [light=null] - The point light source.
  28871. */
  28872. constructor( light = null ) {
  28873. super( light );
  28874. /**
  28875. * Uniform node representing the cutoff distance.
  28876. *
  28877. * @type {UniformNode<float>}
  28878. */
  28879. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  28880. /**
  28881. * Uniform node representing the decay exponent.
  28882. *
  28883. * @type {UniformNode<float>}
  28884. */
  28885. this.decayExponentNode = uniform( 2 ).setGroup( renderGroup );
  28886. }
  28887. /**
  28888. * Overwritten to updated point light specific uniforms.
  28889. *
  28890. * @param {NodeFrame} frame - A reference to the current node frame.
  28891. */
  28892. update( frame ) {
  28893. const { light } = this;
  28894. super.update( frame );
  28895. this.cutoffDistanceNode.value = light.distance;
  28896. this.decayExponentNode.value = light.decay;
  28897. }
  28898. /**
  28899. * Overwritten to setup point light specific shadow.
  28900. *
  28901. * @return {PointShadowNode}
  28902. */
  28903. setupShadowNode() {
  28904. return pointShadow( this.light );
  28905. }
  28906. setupDirect( builder ) {
  28907. return directPointLight( {
  28908. color: this.colorNode,
  28909. lightVector: this.getLightVector( builder ),
  28910. cutoffDistance: this.cutoffDistanceNode,
  28911. decayExponent: this.decayExponentNode
  28912. } );
  28913. }
  28914. }
  28915. /**
  28916. * Creates a 2x2 checkerboard pattern that can be used as procedural texture data.
  28917. *
  28918. * @tsl
  28919. * @function
  28920. * @param {Node<vec2>} coord - The uv coordinates.
  28921. * @return {Node<float>} The result data.
  28922. */
  28923. const checker = /*@__PURE__*/ Fn( ( [ coord = uv$1() ] ) => {
  28924. const uv = coord.mul( 2.0 );
  28925. const cx = uv.x.floor();
  28926. const cy = uv.y.floor();
  28927. const result = cx.add( cy ).mod( 2.0 );
  28928. return result.sign();
  28929. } );
  28930. /**
  28931. * Generates a circle based on the uv coordinates.
  28932. *
  28933. * @tsl
  28934. * @function
  28935. * @param {Node<vec2>} coord - The uv to generate the circle.
  28936. * @return {Node<float>} The circle shape.
  28937. */
  28938. const shapeCircle = Fn( ( [ coord = uv$1() ], { renderer, material } ) => {
  28939. const len2 = lengthSq( coord.mul( 2 ).sub( 1 ) );
  28940. let alpha;
  28941. if ( material.alphaToCoverage && renderer.samples > 1 ) {
  28942. const dlen = float( len2.fwidth() ).toVar();
  28943. alpha = smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus();
  28944. } else {
  28945. alpha = select( len2.greaterThan( 1.0 ), 0, 1 );
  28946. }
  28947. return alpha;
  28948. } );
  28949. // Three.js Transpiler
  28950. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  28951. const mx_select = /*@__PURE__*/ Fn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  28952. const f = float( f_immutable ).toVar();
  28953. const t = float( t_immutable ).toVar();
  28954. const b = bool( b_immutable ).toVar();
  28955. return select( b, t, f );
  28956. } ).setLayout( {
  28957. name: 'mx_select',
  28958. type: 'float',
  28959. inputs: [
  28960. { name: 'b', type: 'bool' },
  28961. { name: 't', type: 'float' },
  28962. { name: 'f', type: 'float' }
  28963. ]
  28964. } );
  28965. const mx_negate_if = /*@__PURE__*/ Fn( ( [ val_immutable, b_immutable ] ) => {
  28966. const b = bool( b_immutable ).toVar();
  28967. const val = float( val_immutable ).toVar();
  28968. return select( b, val.negate(), val );
  28969. } ).setLayout( {
  28970. name: 'mx_negate_if',
  28971. type: 'float',
  28972. inputs: [
  28973. { name: 'val', type: 'float' },
  28974. { name: 'b', type: 'bool' }
  28975. ]
  28976. } );
  28977. const mx_floor = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  28978. const x = float( x_immutable ).toVar();
  28979. return int( floor( x ) );
  28980. } ).setLayout( {
  28981. name: 'mx_floor',
  28982. type: 'int',
  28983. inputs: [
  28984. { name: 'x', type: 'float' }
  28985. ]
  28986. } );
  28987. const mx_floorfrac = /*@__PURE__*/ Fn( ( [ x_immutable, i ] ) => {
  28988. const x = float( x_immutable ).toVar();
  28989. i.assign( mx_floor( x ) );
  28990. return x.sub( float( i ) );
  28991. } );
  28992. const mx_bilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  28993. const t = float( t_immutable ).toVar();
  28994. const s = float( s_immutable ).toVar();
  28995. const v3 = float( v3_immutable ).toVar();
  28996. const v2 = float( v2_immutable ).toVar();
  28997. const v1 = float( v1_immutable ).toVar();
  28998. const v0 = float( v0_immutable ).toVar();
  28999. const s1 = float( sub( 1.0, s ) ).toVar();
  29000. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  29001. } ).setLayout( {
  29002. name: 'mx_bilerp_0',
  29003. type: 'float',
  29004. inputs: [
  29005. { name: 'v0', type: 'float' },
  29006. { name: 'v1', type: 'float' },
  29007. { name: 'v2', type: 'float' },
  29008. { name: 'v3', type: 'float' },
  29009. { name: 's', type: 'float' },
  29010. { name: 't', type: 'float' }
  29011. ]
  29012. } );
  29013. const mx_bilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  29014. const t = float( t_immutable ).toVar();
  29015. const s = float( s_immutable ).toVar();
  29016. const v3 = vec3( v3_immutable ).toVar();
  29017. const v2 = vec3( v2_immutable ).toVar();
  29018. const v1 = vec3( v1_immutable ).toVar();
  29019. const v0 = vec3( v0_immutable ).toVar();
  29020. const s1 = float( sub( 1.0, s ) ).toVar();
  29021. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  29022. } ).setLayout( {
  29023. name: 'mx_bilerp_1',
  29024. type: 'vec3',
  29025. inputs: [
  29026. { name: 'v0', type: 'vec3' },
  29027. { name: 'v1', type: 'vec3' },
  29028. { name: 'v2', type: 'vec3' },
  29029. { name: 'v3', type: 'vec3' },
  29030. { name: 's', type: 'float' },
  29031. { name: 't', type: 'float' }
  29032. ]
  29033. } );
  29034. const mx_bilerp = /*@__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  29035. 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 ] ) => {
  29036. const r = float( r_immutable ).toVar();
  29037. const t = float( t_immutable ).toVar();
  29038. const s = float( s_immutable ).toVar();
  29039. const v7 = float( v7_immutable ).toVar();
  29040. const v6 = float( v6_immutable ).toVar();
  29041. const v5 = float( v5_immutable ).toVar();
  29042. const v4 = float( v4_immutable ).toVar();
  29043. const v3 = float( v3_immutable ).toVar();
  29044. const v2 = float( v2_immutable ).toVar();
  29045. const v1 = float( v1_immutable ).toVar();
  29046. const v0 = float( v0_immutable ).toVar();
  29047. const s1 = float( sub( 1.0, s ) ).toVar();
  29048. const t1 = float( sub( 1.0, t ) ).toVar();
  29049. const r1 = float( sub( 1.0, r ) ).toVar();
  29050. 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 ) ) ) ) ) );
  29051. } ).setLayout( {
  29052. name: 'mx_trilerp_0',
  29053. type: 'float',
  29054. inputs: [
  29055. { name: 'v0', type: 'float' },
  29056. { name: 'v1', type: 'float' },
  29057. { name: 'v2', type: 'float' },
  29058. { name: 'v3', type: 'float' },
  29059. { name: 'v4', type: 'float' },
  29060. { name: 'v5', type: 'float' },
  29061. { name: 'v6', type: 'float' },
  29062. { name: 'v7', type: 'float' },
  29063. { name: 's', type: 'float' },
  29064. { name: 't', type: 'float' },
  29065. { name: 'r', type: 'float' }
  29066. ]
  29067. } );
  29068. 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 ] ) => {
  29069. const r = float( r_immutable ).toVar();
  29070. const t = float( t_immutable ).toVar();
  29071. const s = float( s_immutable ).toVar();
  29072. const v7 = vec3( v7_immutable ).toVar();
  29073. const v6 = vec3( v6_immutable ).toVar();
  29074. const v5 = vec3( v5_immutable ).toVar();
  29075. const v4 = vec3( v4_immutable ).toVar();
  29076. const v3 = vec3( v3_immutable ).toVar();
  29077. const v2 = vec3( v2_immutable ).toVar();
  29078. const v1 = vec3( v1_immutable ).toVar();
  29079. const v0 = vec3( v0_immutable ).toVar();
  29080. const s1 = float( sub( 1.0, s ) ).toVar();
  29081. const t1 = float( sub( 1.0, t ) ).toVar();
  29082. const r1 = float( sub( 1.0, r ) ).toVar();
  29083. 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 ) ) ) ) ) );
  29084. } ).setLayout( {
  29085. name: 'mx_trilerp_1',
  29086. type: 'vec3',
  29087. inputs: [
  29088. { name: 'v0', type: 'vec3' },
  29089. { name: 'v1', type: 'vec3' },
  29090. { name: 'v2', type: 'vec3' },
  29091. { name: 'v3', type: 'vec3' },
  29092. { name: 'v4', type: 'vec3' },
  29093. { name: 'v5', type: 'vec3' },
  29094. { name: 'v6', type: 'vec3' },
  29095. { name: 'v7', type: 'vec3' },
  29096. { name: 's', type: 'float' },
  29097. { name: 't', type: 'float' },
  29098. { name: 'r', type: 'float' }
  29099. ]
  29100. } );
  29101. const mx_trilerp = /*@__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  29102. const mx_gradient_float_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  29103. const y = float( y_immutable ).toVar();
  29104. const x = float( x_immutable ).toVar();
  29105. const hash = uint( hash_immutable ).toVar();
  29106. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  29107. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  29108. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  29109. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  29110. } ).setLayout( {
  29111. name: 'mx_gradient_float_0',
  29112. type: 'float',
  29113. inputs: [
  29114. { name: 'hash', type: 'uint' },
  29115. { name: 'x', type: 'float' },
  29116. { name: 'y', type: 'float' }
  29117. ]
  29118. } );
  29119. const mx_gradient_float_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  29120. const z = float( z_immutable ).toVar();
  29121. const y = float( y_immutable ).toVar();
  29122. const x = float( x_immutable ).toVar();
  29123. const hash = uint( hash_immutable ).toVar();
  29124. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  29125. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  29126. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  29127. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  29128. } ).setLayout( {
  29129. name: 'mx_gradient_float_1',
  29130. type: 'float',
  29131. inputs: [
  29132. { name: 'hash', type: 'uint' },
  29133. { name: 'x', type: 'float' },
  29134. { name: 'y', type: 'float' },
  29135. { name: 'z', type: 'float' }
  29136. ]
  29137. } );
  29138. const mx_gradient_float = /*@__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  29139. const mx_gradient_vec3_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  29140. const y = float( y_immutable ).toVar();
  29141. const x = float( x_immutable ).toVar();
  29142. const hash = uvec3( hash_immutable ).toVar();
  29143. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  29144. } ).setLayout( {
  29145. name: 'mx_gradient_vec3_0',
  29146. type: 'vec3',
  29147. inputs: [
  29148. { name: 'hash', type: 'uvec3' },
  29149. { name: 'x', type: 'float' },
  29150. { name: 'y', type: 'float' }
  29151. ]
  29152. } );
  29153. const mx_gradient_vec3_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  29154. const z = float( z_immutable ).toVar();
  29155. const y = float( y_immutable ).toVar();
  29156. const x = float( x_immutable ).toVar();
  29157. const hash = uvec3( hash_immutable ).toVar();
  29158. 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 ) );
  29159. } ).setLayout( {
  29160. name: 'mx_gradient_vec3_1',
  29161. type: 'vec3',
  29162. inputs: [
  29163. { name: 'hash', type: 'uvec3' },
  29164. { name: 'x', type: 'float' },
  29165. { name: 'y', type: 'float' },
  29166. { name: 'z', type: 'float' }
  29167. ]
  29168. } );
  29169. const mx_gradient_vec3 = /*@__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  29170. const mx_gradient_scale2d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  29171. const v = float( v_immutable ).toVar();
  29172. return mul( 0.6616, v );
  29173. } ).setLayout( {
  29174. name: 'mx_gradient_scale2d_0',
  29175. type: 'float',
  29176. inputs: [
  29177. { name: 'v', type: 'float' }
  29178. ]
  29179. } );
  29180. const mx_gradient_scale3d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  29181. const v = float( v_immutable ).toVar();
  29182. return mul( 0.9820, v );
  29183. } ).setLayout( {
  29184. name: 'mx_gradient_scale3d_0',
  29185. type: 'float',
  29186. inputs: [
  29187. { name: 'v', type: 'float' }
  29188. ]
  29189. } );
  29190. const mx_gradient_scale2d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  29191. const v = vec3( v_immutable ).toVar();
  29192. return mul( 0.6616, v );
  29193. } ).setLayout( {
  29194. name: 'mx_gradient_scale2d_1',
  29195. type: 'vec3',
  29196. inputs: [
  29197. { name: 'v', type: 'vec3' }
  29198. ]
  29199. } );
  29200. const mx_gradient_scale2d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  29201. const mx_gradient_scale3d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  29202. const v = vec3( v_immutable ).toVar();
  29203. return mul( 0.9820, v );
  29204. } ).setLayout( {
  29205. name: 'mx_gradient_scale3d_1',
  29206. type: 'vec3',
  29207. inputs: [
  29208. { name: 'v', type: 'vec3' }
  29209. ]
  29210. } );
  29211. const mx_gradient_scale3d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  29212. const mx_rotl32 = /*@__PURE__*/ Fn( ( [ x_immutable, k_immutable ] ) => {
  29213. const k = int( k_immutable ).toVar();
  29214. const x = uint( x_immutable ).toVar();
  29215. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  29216. } ).setLayout( {
  29217. name: 'mx_rotl32',
  29218. type: 'uint',
  29219. inputs: [
  29220. { name: 'x', type: 'uint' },
  29221. { name: 'k', type: 'int' }
  29222. ]
  29223. } );
  29224. const mx_bjmix = /*@__PURE__*/ Fn( ( [ a, b, c ] ) => {
  29225. a.subAssign( c );
  29226. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  29227. c.addAssign( b );
  29228. b.subAssign( a );
  29229. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  29230. a.addAssign( c );
  29231. c.subAssign( b );
  29232. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  29233. b.addAssign( a );
  29234. a.subAssign( c );
  29235. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  29236. c.addAssign( b );
  29237. b.subAssign( a );
  29238. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  29239. a.addAssign( c );
  29240. c.subAssign( b );
  29241. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  29242. b.addAssign( a );
  29243. } );
  29244. const mx_bjfinal = /*@__PURE__*/ Fn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  29245. const c = uint( c_immutable ).toVar();
  29246. const b = uint( b_immutable ).toVar();
  29247. const a = uint( a_immutable ).toVar();
  29248. c.bitXorAssign( b );
  29249. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  29250. a.bitXorAssign( c );
  29251. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  29252. b.bitXorAssign( a );
  29253. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  29254. c.bitXorAssign( b );
  29255. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  29256. a.bitXorAssign( c );
  29257. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  29258. b.bitXorAssign( a );
  29259. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  29260. c.bitXorAssign( b );
  29261. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  29262. return c;
  29263. } ).setLayout( {
  29264. name: 'mx_bjfinal',
  29265. type: 'uint',
  29266. inputs: [
  29267. { name: 'a', type: 'uint' },
  29268. { name: 'b', type: 'uint' },
  29269. { name: 'c', type: 'uint' }
  29270. ]
  29271. } );
  29272. const mx_bits_to_01 = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  29273. const bits = uint( bits_immutable ).toVar();
  29274. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  29275. } ).setLayout( {
  29276. name: 'mx_bits_to_01',
  29277. type: 'float',
  29278. inputs: [
  29279. { name: 'bits', type: 'uint' }
  29280. ]
  29281. } );
  29282. const mx_fade = /*@__PURE__*/ Fn( ( [ t_immutable ] ) => {
  29283. const t = float( t_immutable ).toVar();
  29284. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  29285. } ).setLayout( {
  29286. name: 'mx_fade',
  29287. type: 'float',
  29288. inputs: [
  29289. { name: 't', type: 'float' }
  29290. ]
  29291. } );
  29292. const mx_hash_int_0 = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  29293. const x = int( x_immutable ).toVar();
  29294. const len = uint( uint( 1 ) ).toVar();
  29295. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  29296. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  29297. } ).setLayout( {
  29298. name: 'mx_hash_int_0',
  29299. type: 'uint',
  29300. inputs: [
  29301. { name: 'x', type: 'int' }
  29302. ]
  29303. } );
  29304. const mx_hash_int_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  29305. const y = int( y_immutable ).toVar();
  29306. const x = int( x_immutable ).toVar();
  29307. const len = uint( uint( 2 ) ).toVar();
  29308. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  29309. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  29310. a.addAssign( uint( x ) );
  29311. b.addAssign( uint( y ) );
  29312. return mx_bjfinal( a, b, c );
  29313. } ).setLayout( {
  29314. name: 'mx_hash_int_1',
  29315. type: 'uint',
  29316. inputs: [
  29317. { name: 'x', type: 'int' },
  29318. { name: 'y', type: 'int' }
  29319. ]
  29320. } );
  29321. const mx_hash_int_2 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  29322. const z = int( z_immutable ).toVar();
  29323. const y = int( y_immutable ).toVar();
  29324. const x = int( x_immutable ).toVar();
  29325. const len = uint( uint( 3 ) ).toVar();
  29326. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  29327. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  29328. a.addAssign( uint( x ) );
  29329. b.addAssign( uint( y ) );
  29330. c.addAssign( uint( z ) );
  29331. return mx_bjfinal( a, b, c );
  29332. } ).setLayout( {
  29333. name: 'mx_hash_int_2',
  29334. type: 'uint',
  29335. inputs: [
  29336. { name: 'x', type: 'int' },
  29337. { name: 'y', type: 'int' },
  29338. { name: 'z', type: 'int' }
  29339. ]
  29340. } );
  29341. const mx_hash_int_3 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  29342. const xx = int( xx_immutable ).toVar();
  29343. const z = int( z_immutable ).toVar();
  29344. const y = int( y_immutable ).toVar();
  29345. const x = int( x_immutable ).toVar();
  29346. const len = uint( uint( 4 ) ).toVar();
  29347. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  29348. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  29349. a.addAssign( uint( x ) );
  29350. b.addAssign( uint( y ) );
  29351. c.addAssign( uint( z ) );
  29352. mx_bjmix( a, b, c );
  29353. a.addAssign( uint( xx ) );
  29354. return mx_bjfinal( a, b, c );
  29355. } ).setLayout( {
  29356. name: 'mx_hash_int_3',
  29357. type: 'uint',
  29358. inputs: [
  29359. { name: 'x', type: 'int' },
  29360. { name: 'y', type: 'int' },
  29361. { name: 'z', type: 'int' },
  29362. { name: 'xx', type: 'int' }
  29363. ]
  29364. } );
  29365. const mx_hash_int_4 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  29366. const yy = int( yy_immutable ).toVar();
  29367. const xx = int( xx_immutable ).toVar();
  29368. const z = int( z_immutable ).toVar();
  29369. const y = int( y_immutable ).toVar();
  29370. const x = int( x_immutable ).toVar();
  29371. const len = uint( uint( 5 ) ).toVar();
  29372. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  29373. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  29374. a.addAssign( uint( x ) );
  29375. b.addAssign( uint( y ) );
  29376. c.addAssign( uint( z ) );
  29377. mx_bjmix( a, b, c );
  29378. a.addAssign( uint( xx ) );
  29379. b.addAssign( uint( yy ) );
  29380. return mx_bjfinal( a, b, c );
  29381. } ).setLayout( {
  29382. name: 'mx_hash_int_4',
  29383. type: 'uint',
  29384. inputs: [
  29385. { name: 'x', type: 'int' },
  29386. { name: 'y', type: 'int' },
  29387. { name: 'z', type: 'int' },
  29388. { name: 'xx', type: 'int' },
  29389. { name: 'yy', type: 'int' }
  29390. ]
  29391. } );
  29392. 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 ] );
  29393. const mx_hash_vec3_0 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  29394. const y = int( y_immutable ).toVar();
  29395. const x = int( x_immutable ).toVar();
  29396. const h = uint( mx_hash_int( x, y ) ).toVar();
  29397. const result = uvec3().toVar();
  29398. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  29399. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  29400. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  29401. return result;
  29402. } ).setLayout( {
  29403. name: 'mx_hash_vec3_0',
  29404. type: 'uvec3',
  29405. inputs: [
  29406. { name: 'x', type: 'int' },
  29407. { name: 'y', type: 'int' }
  29408. ]
  29409. } );
  29410. const mx_hash_vec3_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  29411. const z = int( z_immutable ).toVar();
  29412. const y = int( y_immutable ).toVar();
  29413. const x = int( x_immutable ).toVar();
  29414. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  29415. const result = uvec3().toVar();
  29416. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  29417. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  29418. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  29419. return result;
  29420. } ).setLayout( {
  29421. name: 'mx_hash_vec3_1',
  29422. type: 'uvec3',
  29423. inputs: [
  29424. { name: 'x', type: 'int' },
  29425. { name: 'y', type: 'int' },
  29426. { name: 'z', type: 'int' }
  29427. ]
  29428. } );
  29429. const mx_hash_vec3 = /*@__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  29430. const mx_perlin_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29431. const p = vec2( p_immutable ).toVar();
  29432. const X = int().toVar(), Y = int().toVar();
  29433. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  29434. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  29435. const u = float( mx_fade( fx ) ).toVar();
  29436. const v = float( mx_fade( fy ) ).toVar();
  29437. 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();
  29438. return mx_gradient_scale2d( result );
  29439. } ).setLayout( {
  29440. name: 'mx_perlin_noise_float_0',
  29441. type: 'float',
  29442. inputs: [
  29443. { name: 'p', type: 'vec2' }
  29444. ]
  29445. } );
  29446. const mx_perlin_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29447. const p = vec3( p_immutable ).toVar();
  29448. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  29449. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  29450. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  29451. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  29452. const u = float( mx_fade( fx ) ).toVar();
  29453. const v = float( mx_fade( fy ) ).toVar();
  29454. const w = float( mx_fade( fz ) ).toVar();
  29455. 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();
  29456. return mx_gradient_scale3d( result );
  29457. } ).setLayout( {
  29458. name: 'mx_perlin_noise_float_1',
  29459. type: 'float',
  29460. inputs: [
  29461. { name: 'p', type: 'vec3' }
  29462. ]
  29463. } );
  29464. const mx_perlin_noise_float = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  29465. const mx_perlin_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29466. const p = vec2( p_immutable ).toVar();
  29467. const X = int().toVar(), Y = int().toVar();
  29468. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  29469. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  29470. const u = float( mx_fade( fx ) ).toVar();
  29471. const v = float( mx_fade( fy ) ).toVar();
  29472. 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();
  29473. return mx_gradient_scale2d( result );
  29474. } ).setLayout( {
  29475. name: 'mx_perlin_noise_vec3_0',
  29476. type: 'vec3',
  29477. inputs: [
  29478. { name: 'p', type: 'vec2' }
  29479. ]
  29480. } );
  29481. const mx_perlin_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29482. const p = vec3( p_immutable ).toVar();
  29483. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  29484. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  29485. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  29486. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  29487. const u = float( mx_fade( fx ) ).toVar();
  29488. const v = float( mx_fade( fy ) ).toVar();
  29489. const w = float( mx_fade( fz ) ).toVar();
  29490. 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();
  29491. return mx_gradient_scale3d( result );
  29492. } ).setLayout( {
  29493. name: 'mx_perlin_noise_vec3_1',
  29494. type: 'vec3',
  29495. inputs: [
  29496. { name: 'p', type: 'vec3' }
  29497. ]
  29498. } );
  29499. const mx_perlin_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  29500. const mx_cell_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29501. const p = float( p_immutable ).toVar();
  29502. const ix = int( mx_floor( p ) ).toVar();
  29503. return mx_bits_to_01( mx_hash_int( ix ) );
  29504. } ).setLayout( {
  29505. name: 'mx_cell_noise_float_0',
  29506. type: 'float',
  29507. inputs: [
  29508. { name: 'p', type: 'float' }
  29509. ]
  29510. } );
  29511. const mx_cell_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29512. const p = vec2( p_immutable ).toVar();
  29513. const ix = int( mx_floor( p.x ) ).toVar();
  29514. const iy = int( mx_floor( p.y ) ).toVar();
  29515. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  29516. } ).setLayout( {
  29517. name: 'mx_cell_noise_float_1',
  29518. type: 'float',
  29519. inputs: [
  29520. { name: 'p', type: 'vec2' }
  29521. ]
  29522. } );
  29523. const mx_cell_noise_float_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29524. const p = vec3( p_immutable ).toVar();
  29525. const ix = int( mx_floor( p.x ) ).toVar();
  29526. const iy = int( mx_floor( p.y ) ).toVar();
  29527. const iz = int( mx_floor( p.z ) ).toVar();
  29528. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  29529. } ).setLayout( {
  29530. name: 'mx_cell_noise_float_2',
  29531. type: 'float',
  29532. inputs: [
  29533. { name: 'p', type: 'vec3' }
  29534. ]
  29535. } );
  29536. const mx_cell_noise_float_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29537. const p = vec4( p_immutable ).toVar();
  29538. const ix = int( mx_floor( p.x ) ).toVar();
  29539. const iy = int( mx_floor( p.y ) ).toVar();
  29540. const iz = int( mx_floor( p.z ) ).toVar();
  29541. const iw = int( mx_floor( p.w ) ).toVar();
  29542. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  29543. } ).setLayout( {
  29544. name: 'mx_cell_noise_float_3',
  29545. type: 'float',
  29546. inputs: [
  29547. { name: 'p', type: 'vec4' }
  29548. ]
  29549. } );
  29550. 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 ] );
  29551. const mx_cell_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29552. const p = float( p_immutable ).toVar();
  29553. const ix = int( mx_floor( p ) ).toVar();
  29554. 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 ) ) ) );
  29555. } ).setLayout( {
  29556. name: 'mx_cell_noise_vec3_0',
  29557. type: 'vec3',
  29558. inputs: [
  29559. { name: 'p', type: 'float' }
  29560. ]
  29561. } );
  29562. const mx_cell_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29563. const p = vec2( p_immutable ).toVar();
  29564. const ix = int( mx_floor( p.x ) ).toVar();
  29565. const iy = int( mx_floor( p.y ) ).toVar();
  29566. 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 ) ) ) );
  29567. } ).setLayout( {
  29568. name: 'mx_cell_noise_vec3_1',
  29569. type: 'vec3',
  29570. inputs: [
  29571. { name: 'p', type: 'vec2' }
  29572. ]
  29573. } );
  29574. const mx_cell_noise_vec3_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29575. const p = vec3( p_immutable ).toVar();
  29576. const ix = int( mx_floor( p.x ) ).toVar();
  29577. const iy = int( mx_floor( p.y ) ).toVar();
  29578. const iz = int( mx_floor( p.z ) ).toVar();
  29579. 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 ) ) ) );
  29580. } ).setLayout( {
  29581. name: 'mx_cell_noise_vec3_2',
  29582. type: 'vec3',
  29583. inputs: [
  29584. { name: 'p', type: 'vec3' }
  29585. ]
  29586. } );
  29587. const mx_cell_noise_vec3_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29588. const p = vec4( p_immutable ).toVar();
  29589. const ix = int( mx_floor( p.x ) ).toVar();
  29590. const iy = int( mx_floor( p.y ) ).toVar();
  29591. const iz = int( mx_floor( p.z ) ).toVar();
  29592. const iw = int( mx_floor( p.w ) ).toVar();
  29593. 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 ) ) ) );
  29594. } ).setLayout( {
  29595. name: 'mx_cell_noise_vec3_3',
  29596. type: 'vec3',
  29597. inputs: [
  29598. { name: 'p', type: 'vec4' }
  29599. ]
  29600. } );
  29601. 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 ] );
  29602. const mx_fractal_noise_float$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  29603. const diminish = float( diminish_immutable ).toVar();
  29604. const lacunarity = float( lacunarity_immutable ).toVar();
  29605. const octaves = int( octaves_immutable ).toVar();
  29606. const p = vec3( p_immutable ).toVar();
  29607. const result = float( 0.0 ).toVar();
  29608. const amplitude = float( 1.0 ).toVar();
  29609. Loop( octaves, () => {
  29610. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  29611. amplitude.mulAssign( diminish );
  29612. p.mulAssign( lacunarity );
  29613. } );
  29614. return result;
  29615. } ).setLayout( {
  29616. name: 'mx_fractal_noise_float',
  29617. type: 'float',
  29618. inputs: [
  29619. { name: 'p', type: 'vec3' },
  29620. { name: 'octaves', type: 'int' },
  29621. { name: 'lacunarity', type: 'float' },
  29622. { name: 'diminish', type: 'float' }
  29623. ]
  29624. } );
  29625. const mx_fractal_noise_vec3$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  29626. const diminish = float( diminish_immutable ).toVar();
  29627. const lacunarity = float( lacunarity_immutable ).toVar();
  29628. const octaves = int( octaves_immutable ).toVar();
  29629. const p = vec3( p_immutable ).toVar();
  29630. const result = vec3( 0.0 ).toVar();
  29631. const amplitude = float( 1.0 ).toVar();
  29632. Loop( octaves, () => {
  29633. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  29634. amplitude.mulAssign( diminish );
  29635. p.mulAssign( lacunarity );
  29636. } );
  29637. return result;
  29638. } ).setLayout( {
  29639. name: 'mx_fractal_noise_vec3',
  29640. type: 'vec3',
  29641. inputs: [
  29642. { name: 'p', type: 'vec3' },
  29643. { name: 'octaves', type: 'int' },
  29644. { name: 'lacunarity', type: 'float' },
  29645. { name: 'diminish', type: 'float' }
  29646. ]
  29647. } );
  29648. const mx_fractal_noise_vec2$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  29649. const diminish = float( diminish_immutable ).toVar();
  29650. const lacunarity = float( lacunarity_immutable ).toVar();
  29651. const octaves = int( octaves_immutable ).toVar();
  29652. const p = vec3( p_immutable ).toVar();
  29653. 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 ) );
  29654. } ).setLayout( {
  29655. name: 'mx_fractal_noise_vec2',
  29656. type: 'vec2',
  29657. inputs: [
  29658. { name: 'p', type: 'vec3' },
  29659. { name: 'octaves', type: 'int' },
  29660. { name: 'lacunarity', type: 'float' },
  29661. { name: 'diminish', type: 'float' }
  29662. ]
  29663. } );
  29664. const mx_fractal_noise_vec4$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  29665. const diminish = float( diminish_immutable ).toVar();
  29666. const lacunarity = float( lacunarity_immutable ).toVar();
  29667. const octaves = int( octaves_immutable ).toVar();
  29668. const p = vec3( p_immutable ).toVar();
  29669. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  29670. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  29671. return vec4( c, f );
  29672. } ).setLayout( {
  29673. name: 'mx_fractal_noise_vec4',
  29674. type: 'vec4',
  29675. inputs: [
  29676. { name: 'p', type: 'vec3' },
  29677. { name: 'octaves', type: 'int' },
  29678. { name: 'lacunarity', type: 'float' },
  29679. { name: 'diminish', type: 'float' }
  29680. ]
  29681. } );
  29682. const mx_worley_distance_0 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  29683. const metric = int( metric_immutable ).toVar();
  29684. const jitter = float( jitter_immutable ).toVar();
  29685. const yoff = int( yoff_immutable ).toVar();
  29686. const xoff = int( xoff_immutable ).toVar();
  29687. const y = int( y_immutable ).toVar();
  29688. const x = int( x_immutable ).toVar();
  29689. const p = vec2( p_immutable ).toVar();
  29690. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  29691. const off = vec2( tmp.x, tmp.y ).toVar();
  29692. off.subAssign( 0.5 );
  29693. off.mulAssign( jitter );
  29694. off.addAssign( 0.5 );
  29695. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  29696. const diff = vec2( cellpos.sub( p ) ).toVar();
  29697. If( metric.equal( int( 2 ) ), () => {
  29698. return abs( diff.x ).add( abs( diff.y ) );
  29699. } );
  29700. If( metric.equal( int( 3 ) ), () => {
  29701. return max$1( abs( diff.x ), abs( diff.y ) );
  29702. } );
  29703. return dot( diff, diff );
  29704. } ).setLayout( {
  29705. name: 'mx_worley_distance_0',
  29706. type: 'float',
  29707. inputs: [
  29708. { name: 'p', type: 'vec2' },
  29709. { name: 'x', type: 'int' },
  29710. { name: 'y', type: 'int' },
  29711. { name: 'xoff', type: 'int' },
  29712. { name: 'yoff', type: 'int' },
  29713. { name: 'jitter', type: 'float' },
  29714. { name: 'metric', type: 'int' }
  29715. ]
  29716. } );
  29717. 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 ] ) => {
  29718. const metric = int( metric_immutable ).toVar();
  29719. const jitter = float( jitter_immutable ).toVar();
  29720. const zoff = int( zoff_immutable ).toVar();
  29721. const yoff = int( yoff_immutable ).toVar();
  29722. const xoff = int( xoff_immutable ).toVar();
  29723. const z = int( z_immutable ).toVar();
  29724. const y = int( y_immutable ).toVar();
  29725. const x = int( x_immutable ).toVar();
  29726. const p = vec3( p_immutable ).toVar();
  29727. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  29728. off.subAssign( 0.5 );
  29729. off.mulAssign( jitter );
  29730. off.addAssign( 0.5 );
  29731. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  29732. const diff = vec3( cellpos.sub( p ) ).toVar();
  29733. If( metric.equal( int( 2 ) ), () => {
  29734. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  29735. } );
  29736. If( metric.equal( int( 3 ) ), () => {
  29737. return max$1( abs( diff.x ), abs( diff.y ), abs( diff.z ) );
  29738. } );
  29739. return dot( diff, diff );
  29740. } ).setLayout( {
  29741. name: 'mx_worley_distance_1',
  29742. type: 'float',
  29743. inputs: [
  29744. { name: 'p', type: 'vec3' },
  29745. { name: 'x', type: 'int' },
  29746. { name: 'y', type: 'int' },
  29747. { name: 'z', type: 'int' },
  29748. { name: 'xoff', type: 'int' },
  29749. { name: 'yoff', type: 'int' },
  29750. { name: 'zoff', type: 'int' },
  29751. { name: 'jitter', type: 'float' },
  29752. { name: 'metric', type: 'int' }
  29753. ]
  29754. } );
  29755. const mx_worley_distance = /*@__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  29756. const mx_worley_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  29757. const metric = int( metric_immutable ).toVar();
  29758. const jitter = float( jitter_immutable ).toVar();
  29759. const p = vec2( p_immutable ).toVar();
  29760. const X = int().toVar(), Y = int().toVar();
  29761. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  29762. const sqdist = float( 1e6 ).toVar();
  29763. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  29764. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  29765. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  29766. sqdist.assign( min$1( sqdist, dist ) );
  29767. } );
  29768. } );
  29769. If( metric.equal( int( 0 ) ), () => {
  29770. sqdist.assign( sqrt( sqdist ) );
  29771. } );
  29772. return sqdist;
  29773. } ).setLayout( {
  29774. name: 'mx_worley_noise_float_0',
  29775. type: 'float',
  29776. inputs: [
  29777. { name: 'p', type: 'vec2' },
  29778. { name: 'jitter', type: 'float' },
  29779. { name: 'metric', type: 'int' }
  29780. ]
  29781. } );
  29782. const mx_worley_noise_vec2_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  29783. const metric = int( metric_immutable ).toVar();
  29784. const jitter = float( jitter_immutable ).toVar();
  29785. const p = vec2( p_immutable ).toVar();
  29786. const X = int().toVar(), Y = int().toVar();
  29787. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  29788. const sqdist = vec2( 1e6, 1e6 ).toVar();
  29789. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  29790. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  29791. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  29792. If( dist.lessThan( sqdist.x ), () => {
  29793. sqdist.y.assign( sqdist.x );
  29794. sqdist.x.assign( dist );
  29795. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  29796. sqdist.y.assign( dist );
  29797. } );
  29798. } );
  29799. } );
  29800. If( metric.equal( int( 0 ) ), () => {
  29801. sqdist.assign( sqrt( sqdist ) );
  29802. } );
  29803. return sqdist;
  29804. } ).setLayout( {
  29805. name: 'mx_worley_noise_vec2_0',
  29806. type: 'vec2',
  29807. inputs: [
  29808. { name: 'p', type: 'vec2' },
  29809. { name: 'jitter', type: 'float' },
  29810. { name: 'metric', type: 'int' }
  29811. ]
  29812. } );
  29813. const mx_worley_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  29814. const metric = int( metric_immutable ).toVar();
  29815. const jitter = float( jitter_immutable ).toVar();
  29816. const p = vec2( p_immutable ).toVar();
  29817. const X = int().toVar(), Y = int().toVar();
  29818. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  29819. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  29820. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  29821. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  29822. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  29823. If( dist.lessThan( sqdist.x ), () => {
  29824. sqdist.z.assign( sqdist.y );
  29825. sqdist.y.assign( sqdist.x );
  29826. sqdist.x.assign( dist );
  29827. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  29828. sqdist.z.assign( sqdist.y );
  29829. sqdist.y.assign( dist );
  29830. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  29831. sqdist.z.assign( dist );
  29832. } );
  29833. } );
  29834. } );
  29835. If( metric.equal( int( 0 ) ), () => {
  29836. sqdist.assign( sqrt( sqdist ) );
  29837. } );
  29838. return sqdist;
  29839. } ).setLayout( {
  29840. name: 'mx_worley_noise_vec3_0',
  29841. type: 'vec3',
  29842. inputs: [
  29843. { name: 'p', type: 'vec2' },
  29844. { name: 'jitter', type: 'float' },
  29845. { name: 'metric', type: 'int' }
  29846. ]
  29847. } );
  29848. const mx_worley_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  29849. const metric = int( metric_immutable ).toVar();
  29850. const jitter = float( jitter_immutable ).toVar();
  29851. const p = vec3( p_immutable ).toVar();
  29852. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  29853. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  29854. const sqdist = float( 1e6 ).toVar();
  29855. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  29856. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  29857. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  29858. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  29859. sqdist.assign( min$1( sqdist, dist ) );
  29860. } );
  29861. } );
  29862. } );
  29863. If( metric.equal( int( 0 ) ), () => {
  29864. sqdist.assign( sqrt( sqdist ) );
  29865. } );
  29866. return sqdist;
  29867. } ).setLayout( {
  29868. name: 'mx_worley_noise_float_1',
  29869. type: 'float',
  29870. inputs: [
  29871. { name: 'p', type: 'vec3' },
  29872. { name: 'jitter', type: 'float' },
  29873. { name: 'metric', type: 'int' }
  29874. ]
  29875. } );
  29876. const mx_worley_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  29877. const mx_worley_noise_vec2_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  29878. const metric = int( metric_immutable ).toVar();
  29879. const jitter = float( jitter_immutable ).toVar();
  29880. const p = vec3( p_immutable ).toVar();
  29881. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  29882. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  29883. const sqdist = vec2( 1e6, 1e6 ).toVar();
  29884. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  29885. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  29886. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  29887. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  29888. If( dist.lessThan( sqdist.x ), () => {
  29889. sqdist.y.assign( sqdist.x );
  29890. sqdist.x.assign( dist );
  29891. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  29892. sqdist.y.assign( dist );
  29893. } );
  29894. } );
  29895. } );
  29896. } );
  29897. If( metric.equal( int( 0 ) ), () => {
  29898. sqdist.assign( sqrt( sqdist ) );
  29899. } );
  29900. return sqdist;
  29901. } ).setLayout( {
  29902. name: 'mx_worley_noise_vec2_1',
  29903. type: 'vec2',
  29904. inputs: [
  29905. { name: 'p', type: 'vec3' },
  29906. { name: 'jitter', type: 'float' },
  29907. { name: 'metric', type: 'int' }
  29908. ]
  29909. } );
  29910. const mx_worley_noise_vec2$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  29911. const mx_worley_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  29912. const metric = int( metric_immutable ).toVar();
  29913. const jitter = float( jitter_immutable ).toVar();
  29914. const p = vec3( p_immutable ).toVar();
  29915. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  29916. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  29917. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  29918. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  29919. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  29920. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  29921. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  29922. If( dist.lessThan( sqdist.x ), () => {
  29923. sqdist.z.assign( sqdist.y );
  29924. sqdist.y.assign( sqdist.x );
  29925. sqdist.x.assign( dist );
  29926. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  29927. sqdist.z.assign( sqdist.y );
  29928. sqdist.y.assign( dist );
  29929. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  29930. sqdist.z.assign( dist );
  29931. } );
  29932. } );
  29933. } );
  29934. } );
  29935. If( metric.equal( int( 0 ) ), () => {
  29936. sqdist.assign( sqrt( sqdist ) );
  29937. } );
  29938. return sqdist;
  29939. } ).setLayout( {
  29940. name: 'mx_worley_noise_vec3_1',
  29941. type: 'vec3',
  29942. inputs: [
  29943. { name: 'p', type: 'vec3' },
  29944. { name: 'jitter', type: 'float' },
  29945. { name: 'metric', type: 'int' }
  29946. ]
  29947. } );
  29948. const mx_worley_noise_vec3$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  29949. // Three.js Transpiler
  29950. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  29951. const mx_hsvtorgb = /*@__PURE__*/ Fn( ( [ hsv ] ) => {
  29952. const s = hsv.y;
  29953. const v = hsv.z;
  29954. const result = vec3().toVar();
  29955. If( s.lessThan( 0.0001 ), () => {
  29956. result.assign( vec3( v, v, v ) );
  29957. } ).Else( () => {
  29958. let h = hsv.x;
  29959. h = h.sub( floor( h ) ).mul( 6.0 ).toVar(); // TODO: check what .toVar() is needed in node system cache
  29960. const hi = int( trunc( h ) );
  29961. const f = h.sub( float( hi ) );
  29962. const p = v.mul( s.oneMinus() );
  29963. const q = v.mul( s.mul( f ).oneMinus() );
  29964. const t = v.mul( s.mul( f.oneMinus() ).oneMinus() );
  29965. If( hi.equal( int( 0 ) ), () => {
  29966. result.assign( vec3( v, t, p ) );
  29967. } ).ElseIf( hi.equal( int( 1 ) ), () => {
  29968. result.assign( vec3( q, v, p ) );
  29969. } ).ElseIf( hi.equal( int( 2 ) ), () => {
  29970. result.assign( vec3( p, v, t ) );
  29971. } ).ElseIf( hi.equal( int( 3 ) ), () => {
  29972. result.assign( vec3( p, q, v ) );
  29973. } ).ElseIf( hi.equal( int( 4 ) ), () => {
  29974. result.assign( vec3( t, p, v ) );
  29975. } ).Else( () => {
  29976. result.assign( vec3( v, p, q ) );
  29977. } );
  29978. } );
  29979. return result;
  29980. } ).setLayout( {
  29981. name: 'mx_hsvtorgb',
  29982. type: 'vec3',
  29983. inputs: [
  29984. { name: 'hsv', type: 'vec3' }
  29985. ]
  29986. } );
  29987. const mx_rgbtohsv = /*@__PURE__*/ Fn( ( [ c_immutable ] ) => {
  29988. const c = vec3( c_immutable ).toVar();
  29989. const r = float( c.x ).toVar();
  29990. const g = float( c.y ).toVar();
  29991. const b = float( c.z ).toVar();
  29992. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  29993. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  29994. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  29995. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  29996. v.assign( maxcomp );
  29997. If( maxcomp.greaterThan( 0.0 ), () => {
  29998. s.assign( delta.div( maxcomp ) );
  29999. } ).Else( () => {
  30000. s.assign( 0.0 );
  30001. } );
  30002. If( s.lessThanEqual( 0.0 ), () => {
  30003. h.assign( 0.0 );
  30004. } ).Else( () => {
  30005. If( r.greaterThanEqual( maxcomp ), () => {
  30006. h.assign( g.sub( b ).div( delta ) );
  30007. } ).ElseIf( g.greaterThanEqual( maxcomp ), () => {
  30008. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  30009. } ).Else( () => {
  30010. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  30011. } );
  30012. h.mulAssign( 1.0 / 6.0 );
  30013. If( h.lessThan( 0.0 ), () => {
  30014. h.addAssign( 1.0 );
  30015. } );
  30016. } );
  30017. return vec3( h, s, v );
  30018. } ).setLayout( {
  30019. name: 'mx_rgbtohsv',
  30020. type: 'vec3',
  30021. inputs: [
  30022. { name: 'c', type: 'vec3' }
  30023. ]
  30024. } );
  30025. // Three.js Transpiler
  30026. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  30027. const mx_srgb_texture_to_lin_rec709 = /*@__PURE__*/ Fn( ( [ color_immutable ] ) => {
  30028. const color = vec3( color_immutable ).toVar();
  30029. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  30030. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  30031. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  30032. return mix( linSeg, powSeg, isAbove );
  30033. } ).setLayout( {
  30034. name: 'mx_srgb_texture_to_lin_rec709',
  30035. type: 'vec3',
  30036. inputs: [
  30037. { name: 'color', type: 'vec3' }
  30038. ]
  30039. } );
  30040. const mx_aastep = ( threshold, value ) => {
  30041. threshold = float( threshold );
  30042. value = float( value );
  30043. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  30044. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  30045. };
  30046. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  30047. const mx_ramplr = ( valuel, valuer, texcoord = uv$1() ) => _ramp( valuel, valuer, texcoord, 'x' );
  30048. const mx_ramptb = ( valuet, valueb, texcoord = uv$1() ) => _ramp( valuet, valueb, texcoord, 'y' );
  30049. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  30050. const mx_splitlr = ( valuel, valuer, center, texcoord = uv$1() ) => _split( valuel, valuer, center, texcoord, 'x' );
  30051. const mx_splittb = ( valuet, valueb, center, texcoord = uv$1() ) => _split( valuet, valueb, center, texcoord, 'y' );
  30052. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv$1() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  30053. const mx_safepower = ( in1, in2 = 1 ) => {
  30054. in1 = float( in1 );
  30055. return in1.abs().pow( in2 ).mul( in1.sign() );
  30056. };
  30057. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  30058. const mx_noise_float = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  30059. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  30060. const mx_noise_vec3 = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  30061. const mx_noise_vec4 = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => {
  30062. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  30063. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  30064. return noise_vec4.mul( amplitude ).add( pivot );
  30065. };
  30066. const mx_worley_noise_float = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  30067. const mx_worley_noise_vec2 = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  30068. const mx_worley_noise_vec3 = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  30069. const mx_cell_noise_float = ( texcoord = uv$1() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  30070. const mx_fractal_noise_float = ( position = uv$1(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_float$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude );
  30071. const mx_fractal_noise_vec2 = ( position = uv$1(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec2$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude );
  30072. const mx_fractal_noise_vec3 = ( position = uv$1(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec3$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude );
  30073. const mx_fractal_noise_vec4 = ( position = uv$1(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec4$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude );
  30074. /**
  30075. * This computes a parallax corrected normal which is used for box-projected cube mapping (BPCEM).
  30076. *
  30077. * Reference: {@link https://devlog-martinsh.blogspot.com/2011/09/box-projected-cube-environment-mapping.html}
  30078. *
  30079. * ```js
  30080. * const uvNode = getParallaxCorrectNormal( reflectVector, vec3( 200, 100, 100 ), vec3( 0, - 50, 0 ) );
  30081. * material.envNode = pmremTexture( renderTarget.texture, uvNode );
  30082. * ```
  30083. *
  30084. * @tsl
  30085. * @function
  30086. * @param {Node<vec3>} normal - The normal to correct.
  30087. * @param {Node<vec3>} cubeSize - The cube size should reflect the size of the environment (BPCEM is usually applied in closed environments like rooms).
  30088. * @param {Node<vec3>} cubePos - The cube position.
  30089. * @return {Node<vec3>} The parallax corrected normal.
  30090. */
  30091. const getParallaxCorrectNormal = /*@__PURE__*/ Fn( ( [ normal, cubeSize, cubePos ] ) => {
  30092. const nDir = normalize( normal ).toVar();
  30093. const rbmax = sub( float( 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar();
  30094. const rbmin = sub( float( -0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar();
  30095. const rbminmax = vec3().toVar();
  30096. rbminmax.x = nDir.x.greaterThan( float( 0 ) ).select( rbmax.x, rbmin.x );
  30097. rbminmax.y = nDir.y.greaterThan( float( 0 ) ).select( rbmax.y, rbmin.y );
  30098. rbminmax.z = nDir.z.greaterThan( float( 0 ) ).select( rbmax.z, rbmin.z );
  30099. const correction = min$1( rbminmax.x, rbminmax.y, rbminmax.z ).toVar();
  30100. const boxIntersection = positionWorld.add( nDir.mul( correction ) ).toVar();
  30101. return boxIntersection.sub( cubePos );
  30102. } );
  30103. const getShIrradianceAt = /*@__PURE__*/ Fn( ( [ normal, shCoefficients ] ) => {
  30104. // normal is assumed to have unit length
  30105. const x = normal.x, y = normal.y, z = normal.z;
  30106. // band 0
  30107. let result = shCoefficients.element( 0 ).mul( 0.886227 );
  30108. // band 1
  30109. result = result.add( shCoefficients.element( 1 ).mul( 2.0 * 0.511664 ).mul( y ) );
  30110. result = result.add( shCoefficients.element( 2 ).mul( 2.0 * 0.511664 ).mul( z ) );
  30111. result = result.add( shCoefficients.element( 3 ).mul( 2.0 * 0.511664 ).mul( x ) );
  30112. // band 2
  30113. result = result.add( shCoefficients.element( 4 ).mul( 2.0 * 0.429043 ).mul( x ).mul( y ) );
  30114. result = result.add( shCoefficients.element( 5 ).mul( 2.0 * 0.429043 ).mul( y ).mul( z ) );
  30115. result = result.add( shCoefficients.element( 6 ).mul( z.mul( z ).mul( 0.743125 ).sub( 0.247708 ) ) );
  30116. result = result.add( shCoefficients.element( 7 ).mul( 2.0 * 0.429043 ).mul( x ).mul( z ) );
  30117. result = result.add( shCoefficients.element( 8 ).mul( 0.429043 ).mul( mul( x, x ).sub( mul( y, y ) ) ) );
  30118. return result;
  30119. } );
  30120. // constants
  30121. var TSL = /*#__PURE__*/Object.freeze({
  30122. __proto__: null,
  30123. BRDF_GGX: BRDF_GGX,
  30124. BRDF_Lambert: BRDF_Lambert,
  30125. BasicPointShadowFilter: BasicPointShadowFilter,
  30126. BasicShadowFilter: BasicShadowFilter,
  30127. Break: Break,
  30128. Const: Const,
  30129. Continue: Continue,
  30130. DFGApprox: DFGApprox,
  30131. D_GGX: D_GGX,
  30132. Discard: Discard,
  30133. EPSILON: EPSILON,
  30134. F_Schlick: F_Schlick,
  30135. Fn: Fn,
  30136. INFINITY: INFINITY,
  30137. If: If,
  30138. Loop: Loop,
  30139. NodeAccess: NodeAccess,
  30140. NodeShaderStage: NodeShaderStage,
  30141. NodeType: NodeType,
  30142. NodeUpdateType: NodeUpdateType,
  30143. PCFShadowFilter: PCFShadowFilter,
  30144. PCFSoftShadowFilter: PCFSoftShadowFilter,
  30145. PI: PI,
  30146. PI2: PI2,
  30147. PointShadowFilter: PointShadowFilter,
  30148. Return: Return,
  30149. Schlick_to_F0: Schlick_to_F0,
  30150. ScriptableNodeResources: ScriptableNodeResources,
  30151. ShaderNode: ShaderNode,
  30152. Stack: Stack,
  30153. Switch: Switch,
  30154. TBNViewMatrix: TBNViewMatrix,
  30155. VSMShadowFilter: VSMShadowFilter,
  30156. V_GGX_SmithCorrelated: V_GGX_SmithCorrelated,
  30157. Var: Var,
  30158. abs: abs,
  30159. acesFilmicToneMapping: acesFilmicToneMapping,
  30160. acos: acos,
  30161. add: add,
  30162. addMethodChaining: addMethodChaining,
  30163. addNodeElement: addNodeElement,
  30164. agxToneMapping: agxToneMapping,
  30165. all: all,
  30166. alphaT: alphaT,
  30167. and: and,
  30168. anisotropy: anisotropy,
  30169. anisotropyB: anisotropyB,
  30170. anisotropyT: anisotropyT,
  30171. any: any,
  30172. append: append,
  30173. array: array,
  30174. arrayBuffer: arrayBuffer,
  30175. asin: asin,
  30176. assign: assign,
  30177. atan: atan,
  30178. atan2: atan2,
  30179. atomicAdd: atomicAdd,
  30180. atomicAnd: atomicAnd,
  30181. atomicFunc: atomicFunc,
  30182. atomicLoad: atomicLoad,
  30183. atomicMax: atomicMax,
  30184. atomicMin: atomicMin,
  30185. atomicOr: atomicOr,
  30186. atomicStore: atomicStore,
  30187. atomicSub: atomicSub,
  30188. atomicXor: atomicXor,
  30189. attenuationColor: attenuationColor,
  30190. attenuationDistance: attenuationDistance,
  30191. attribute: attribute,
  30192. attributeArray: attributeArray,
  30193. backgroundBlurriness: backgroundBlurriness,
  30194. backgroundIntensity: backgroundIntensity,
  30195. backgroundRotation: backgroundRotation,
  30196. batch: batch,
  30197. bentNormalView: bentNormalView,
  30198. billboarding: billboarding,
  30199. bitAnd: bitAnd,
  30200. bitNot: bitNot,
  30201. bitOr: bitOr,
  30202. bitXor: bitXor,
  30203. bitangentGeometry: bitangentGeometry,
  30204. bitangentLocal: bitangentLocal,
  30205. bitangentView: bitangentView,
  30206. bitangentWorld: bitangentWorld,
  30207. bitcast: bitcast,
  30208. blendBurn: blendBurn,
  30209. blendColor: blendColor,
  30210. blendDodge: blendDodge,
  30211. blendOverlay: blendOverlay,
  30212. blendScreen: blendScreen,
  30213. blur: blur,
  30214. bool: bool,
  30215. buffer: buffer,
  30216. bufferAttribute: bufferAttribute,
  30217. bumpMap: bumpMap,
  30218. burn: burn,
  30219. bvec2: bvec2,
  30220. bvec3: bvec3,
  30221. bvec4: bvec4,
  30222. bypass: bypass,
  30223. cache: cache,
  30224. call: call,
  30225. cameraFar: cameraFar,
  30226. cameraIndex: cameraIndex,
  30227. cameraNear: cameraNear,
  30228. cameraNormalMatrix: cameraNormalMatrix,
  30229. cameraPosition: cameraPosition,
  30230. cameraProjectionMatrix: cameraProjectionMatrix,
  30231. cameraProjectionMatrixInverse: cameraProjectionMatrixInverse,
  30232. cameraViewMatrix: cameraViewMatrix,
  30233. cameraWorldMatrix: cameraWorldMatrix,
  30234. cbrt: cbrt,
  30235. cdl: cdl,
  30236. ceil: ceil,
  30237. checker: checker,
  30238. cineonToneMapping: cineonToneMapping,
  30239. clamp: clamp,
  30240. clearcoat: clearcoat,
  30241. clearcoatNormalView: clearcoatNormalView,
  30242. clearcoatRoughness: clearcoatRoughness,
  30243. code: code,
  30244. color: color,
  30245. colorSpaceToWorking: colorSpaceToWorking,
  30246. colorToDirection: colorToDirection,
  30247. compute: compute,
  30248. computeKernel: computeKernel,
  30249. computeSkinning: computeSkinning,
  30250. context: context,
  30251. convert: convert,
  30252. convertColorSpace: convertColorSpace,
  30253. convertToTexture: convertToTexture,
  30254. cos: cos,
  30255. cross: cross,
  30256. cubeTexture: cubeTexture,
  30257. cubeTextureBase: cubeTextureBase,
  30258. cubeToUV: cubeToUV,
  30259. dFdx: dFdx,
  30260. dFdy: dFdy,
  30261. dashSize: dashSize,
  30262. debug: debug,
  30263. decrement: decrement,
  30264. decrementBefore: decrementBefore,
  30265. defaultBuildStages: defaultBuildStages,
  30266. defaultShaderStages: defaultShaderStages,
  30267. defined: defined,
  30268. degrees: degrees,
  30269. deltaTime: deltaTime,
  30270. densityFog: densityFog,
  30271. densityFogFactor: densityFogFactor,
  30272. depth: depth,
  30273. depthPass: depthPass,
  30274. difference: difference,
  30275. diffuseColor: diffuseColor,
  30276. directPointLight: directPointLight,
  30277. directionToColor: directionToColor,
  30278. directionToFaceDirection: directionToFaceDirection,
  30279. dispersion: dispersion,
  30280. distance: distance,
  30281. div: div,
  30282. dodge: dodge,
  30283. dot: dot,
  30284. drawIndex: drawIndex,
  30285. dynamicBufferAttribute: dynamicBufferAttribute,
  30286. element: element,
  30287. emissive: emissive,
  30288. equal: equal,
  30289. equals: equals,
  30290. equirectUV: equirectUV,
  30291. exp: exp,
  30292. exp2: exp2,
  30293. expression: expression,
  30294. faceDirection: faceDirection,
  30295. faceForward: faceForward,
  30296. faceforward: faceforward,
  30297. float: float,
  30298. floor: floor,
  30299. fog: fog,
  30300. fract: fract,
  30301. frameGroup: frameGroup,
  30302. frameId: frameId,
  30303. frontFacing: frontFacing,
  30304. fwidth: fwidth,
  30305. gain: gain,
  30306. gapSize: gapSize,
  30307. getConstNodeType: getConstNodeType,
  30308. getCurrentStack: getCurrentStack,
  30309. getDirection: getDirection,
  30310. getDistanceAttenuation: getDistanceAttenuation,
  30311. getGeometryRoughness: getGeometryRoughness,
  30312. getNormalFromDepth: getNormalFromDepth,
  30313. getParallaxCorrectNormal: getParallaxCorrectNormal,
  30314. getRoughness: getRoughness,
  30315. getScreenPosition: getScreenPosition,
  30316. getShIrradianceAt: getShIrradianceAt,
  30317. getShadowMaterial: getShadowMaterial,
  30318. getShadowRenderObjectFunction: getShadowRenderObjectFunction,
  30319. getTextureIndex: getTextureIndex,
  30320. getViewPosition: getViewPosition,
  30321. globalId: globalId,
  30322. glsl: glsl,
  30323. glslFn: glslFn,
  30324. grayscale: grayscale,
  30325. greaterThan: greaterThan,
  30326. greaterThanEqual: greaterThanEqual,
  30327. hash: hash,
  30328. highpModelNormalViewMatrix: highpModelNormalViewMatrix,
  30329. highpModelViewMatrix: highpModelViewMatrix,
  30330. hue: hue,
  30331. increment: increment,
  30332. incrementBefore: incrementBefore,
  30333. instance: instance,
  30334. instanceIndex: instanceIndex,
  30335. instancedArray: instancedArray,
  30336. instancedBufferAttribute: instancedBufferAttribute,
  30337. instancedDynamicBufferAttribute: instancedDynamicBufferAttribute,
  30338. instancedMesh: instancedMesh,
  30339. int: int,
  30340. inverseSqrt: inverseSqrt,
  30341. inversesqrt: inversesqrt,
  30342. invocationLocalIndex: invocationLocalIndex,
  30343. invocationSubgroupIndex: invocationSubgroupIndex,
  30344. ior: ior,
  30345. iridescence: iridescence,
  30346. iridescenceIOR: iridescenceIOR,
  30347. iridescenceThickness: iridescenceThickness,
  30348. ivec2: ivec2,
  30349. ivec3: ivec3,
  30350. ivec4: ivec4,
  30351. js: js,
  30352. label: label,
  30353. length: length,
  30354. lengthSq: lengthSq,
  30355. lessThan: lessThan,
  30356. lessThanEqual: lessThanEqual,
  30357. lightPosition: lightPosition,
  30358. lightProjectionUV: lightProjectionUV,
  30359. lightShadowMatrix: lightShadowMatrix,
  30360. lightTargetDirection: lightTargetDirection,
  30361. lightTargetPosition: lightTargetPosition,
  30362. lightViewPosition: lightViewPosition,
  30363. lightingContext: lightingContext,
  30364. lights: lights,
  30365. linearDepth: linearDepth,
  30366. linearToneMapping: linearToneMapping,
  30367. localId: localId,
  30368. log: log,
  30369. log2: log2,
  30370. logarithmicDepthToViewZ: logarithmicDepthToViewZ,
  30371. luminance: luminance,
  30372. mat2: mat2,
  30373. mat3: mat3,
  30374. mat4: mat4,
  30375. matcapUV: matcapUV,
  30376. materialAO: materialAO,
  30377. materialAlphaTest: materialAlphaTest,
  30378. materialAnisotropy: materialAnisotropy,
  30379. materialAnisotropyVector: materialAnisotropyVector,
  30380. materialAttenuationColor: materialAttenuationColor,
  30381. materialAttenuationDistance: materialAttenuationDistance,
  30382. materialClearcoat: materialClearcoat,
  30383. materialClearcoatNormal: materialClearcoatNormal,
  30384. materialClearcoatRoughness: materialClearcoatRoughness,
  30385. materialColor: materialColor,
  30386. materialDispersion: materialDispersion,
  30387. materialEmissive: materialEmissive,
  30388. materialEnvIntensity: materialEnvIntensity,
  30389. materialEnvRotation: materialEnvRotation,
  30390. materialIOR: materialIOR,
  30391. materialIridescence: materialIridescence,
  30392. materialIridescenceIOR: materialIridescenceIOR,
  30393. materialIridescenceThickness: materialIridescenceThickness,
  30394. materialLightMap: materialLightMap,
  30395. materialLineDashOffset: materialLineDashOffset,
  30396. materialLineDashSize: materialLineDashSize,
  30397. materialLineGapSize: materialLineGapSize,
  30398. materialLineScale: materialLineScale,
  30399. materialLineWidth: materialLineWidth,
  30400. materialMetalness: materialMetalness,
  30401. materialNormal: materialNormal,
  30402. materialOpacity: materialOpacity,
  30403. materialPointSize: materialPointSize,
  30404. materialReference: materialReference,
  30405. materialReflectivity: materialReflectivity,
  30406. materialRefractionRatio: materialRefractionRatio,
  30407. materialRotation: materialRotation,
  30408. materialRoughness: materialRoughness,
  30409. materialSheen: materialSheen,
  30410. materialSheenRoughness: materialSheenRoughness,
  30411. materialShininess: materialShininess,
  30412. materialSpecular: materialSpecular,
  30413. materialSpecularColor: materialSpecularColor,
  30414. materialSpecularIntensity: materialSpecularIntensity,
  30415. materialSpecularStrength: materialSpecularStrength,
  30416. materialThickness: materialThickness,
  30417. materialTransmission: materialTransmission,
  30418. max: max$1,
  30419. maxMipLevel: maxMipLevel,
  30420. mediumpModelViewMatrix: mediumpModelViewMatrix,
  30421. metalness: metalness,
  30422. min: min$1,
  30423. mix: mix,
  30424. mixElement: mixElement,
  30425. mod: mod,
  30426. modInt: modInt,
  30427. modelDirection: modelDirection,
  30428. modelNormalMatrix: modelNormalMatrix,
  30429. modelPosition: modelPosition,
  30430. modelRadius: modelRadius,
  30431. modelScale: modelScale,
  30432. modelViewMatrix: modelViewMatrix,
  30433. modelViewPosition: modelViewPosition,
  30434. modelViewProjection: modelViewProjection,
  30435. modelWorldMatrix: modelWorldMatrix,
  30436. modelWorldMatrixInverse: modelWorldMatrixInverse,
  30437. morphReference: morphReference,
  30438. mrt: mrt,
  30439. mul: mul,
  30440. mx_aastep: mx_aastep,
  30441. mx_cell_noise_float: mx_cell_noise_float,
  30442. mx_contrast: mx_contrast,
  30443. mx_fractal_noise_float: mx_fractal_noise_float,
  30444. mx_fractal_noise_vec2: mx_fractal_noise_vec2,
  30445. mx_fractal_noise_vec3: mx_fractal_noise_vec3,
  30446. mx_fractal_noise_vec4: mx_fractal_noise_vec4,
  30447. mx_hsvtorgb: mx_hsvtorgb,
  30448. mx_noise_float: mx_noise_float,
  30449. mx_noise_vec3: mx_noise_vec3,
  30450. mx_noise_vec4: mx_noise_vec4,
  30451. mx_ramplr: mx_ramplr,
  30452. mx_ramptb: mx_ramptb,
  30453. mx_rgbtohsv: mx_rgbtohsv,
  30454. mx_safepower: mx_safepower,
  30455. mx_splitlr: mx_splitlr,
  30456. mx_splittb: mx_splittb,
  30457. mx_srgb_texture_to_lin_rec709: mx_srgb_texture_to_lin_rec709,
  30458. mx_transform_uv: mx_transform_uv,
  30459. mx_worley_noise_float: mx_worley_noise_float,
  30460. mx_worley_noise_vec2: mx_worley_noise_vec2,
  30461. mx_worley_noise_vec3: mx_worley_noise_vec3,
  30462. negate: negate,
  30463. neutralToneMapping: neutralToneMapping,
  30464. nodeArray: nodeArray,
  30465. nodeImmutable: nodeImmutable,
  30466. nodeObject: nodeObject,
  30467. nodeObjects: nodeObjects,
  30468. nodeProxy: nodeProxy,
  30469. normalFlat: normalFlat,
  30470. normalGeometry: normalGeometry,
  30471. normalLocal: normalLocal,
  30472. normalMap: normalMap,
  30473. normalView: normalView,
  30474. normalViewGeometry: normalViewGeometry,
  30475. normalWorld: normalWorld,
  30476. normalWorldGeometry: normalWorldGeometry,
  30477. normalize: normalize,
  30478. not: not,
  30479. notEqual: notEqual,
  30480. numWorkgroups: numWorkgroups,
  30481. objectDirection: objectDirection,
  30482. objectGroup: objectGroup,
  30483. objectPosition: objectPosition,
  30484. objectRadius: objectRadius,
  30485. objectScale: objectScale,
  30486. objectViewPosition: objectViewPosition,
  30487. objectWorldMatrix: objectWorldMatrix,
  30488. oneMinus: oneMinus,
  30489. or: or,
  30490. orthographicDepthToViewZ: orthographicDepthToViewZ,
  30491. oscSawtooth: oscSawtooth,
  30492. oscSine: oscSine,
  30493. oscSquare: oscSquare,
  30494. oscTriangle: oscTriangle,
  30495. output: output,
  30496. outputStruct: outputStruct,
  30497. overlay: overlay,
  30498. overloadingFn: overloadingFn,
  30499. parabola: parabola,
  30500. parallaxDirection: parallaxDirection,
  30501. parallaxUV: parallaxUV,
  30502. parameter: parameter,
  30503. pass: pass,
  30504. passTexture: passTexture,
  30505. pcurve: pcurve,
  30506. perspectiveDepthToViewZ: perspectiveDepthToViewZ,
  30507. pmremTexture: pmremTexture,
  30508. pointShadow: pointShadow,
  30509. pointUV: pointUV,
  30510. pointWidth: pointWidth,
  30511. positionGeometry: positionGeometry,
  30512. positionLocal: positionLocal,
  30513. positionPrevious: positionPrevious,
  30514. positionView: positionView,
  30515. positionViewDirection: positionViewDirection,
  30516. positionWorld: positionWorld,
  30517. positionWorldDirection: positionWorldDirection,
  30518. posterize: posterize,
  30519. pow: pow,
  30520. pow2: pow2,
  30521. pow3: pow3,
  30522. pow4: pow4,
  30523. premultiplyAlpha: premultiplyAlpha,
  30524. property: property,
  30525. radians: radians,
  30526. rand: rand,
  30527. range: range,
  30528. rangeFog: rangeFog,
  30529. rangeFogFactor: rangeFogFactor,
  30530. reciprocal: reciprocal,
  30531. reference: reference,
  30532. referenceBuffer: referenceBuffer,
  30533. reflect: reflect,
  30534. reflectVector: reflectVector,
  30535. reflectView: reflectView,
  30536. reflector: reflector,
  30537. refract: refract,
  30538. refractVector: refractVector,
  30539. refractView: refractView,
  30540. reinhardToneMapping: reinhardToneMapping,
  30541. remap: remap,
  30542. remapClamp: remapClamp,
  30543. renderGroup: renderGroup,
  30544. renderOutput: renderOutput,
  30545. rendererReference: rendererReference,
  30546. rotate: rotate,
  30547. rotateUV: rotateUV,
  30548. roughness: roughness,
  30549. round: round,
  30550. rtt: rtt,
  30551. sRGBTransferEOTF: sRGBTransferEOTF,
  30552. sRGBTransferOETF: sRGBTransferOETF,
  30553. sample: sample,
  30554. sampler: sampler,
  30555. samplerComparison: samplerComparison,
  30556. saturate: saturate,
  30557. saturation: saturation,
  30558. screen: screen,
  30559. screenCoordinate: screenCoordinate,
  30560. screenSize: screenSize,
  30561. screenUV: screenUV,
  30562. scriptable: scriptable,
  30563. scriptableValue: scriptableValue,
  30564. select: select,
  30565. setCurrentStack: setCurrentStack,
  30566. shaderStages: shaderStages,
  30567. shadow: shadow,
  30568. shadowPositionWorld: shadowPositionWorld,
  30569. shapeCircle: shapeCircle,
  30570. sharedUniformGroup: sharedUniformGroup,
  30571. sheen: sheen,
  30572. sheenRoughness: sheenRoughness,
  30573. shiftLeft: shiftLeft,
  30574. shiftRight: shiftRight,
  30575. shininess: shininess,
  30576. sign: sign,
  30577. sin: sin,
  30578. sinc: sinc,
  30579. skinning: skinning,
  30580. smoothstep: smoothstep,
  30581. smoothstepElement: smoothstepElement,
  30582. specularColor: specularColor,
  30583. specularF90: specularF90,
  30584. spherizeUV: spherizeUV,
  30585. split: split,
  30586. spritesheetUV: spritesheetUV,
  30587. sqrt: sqrt,
  30588. stack: stack,
  30589. step: step,
  30590. stepElement: stepElement,
  30591. storage: storage,
  30592. storageBarrier: storageBarrier,
  30593. storageObject: storageObject,
  30594. storageTexture: storageTexture,
  30595. string: string,
  30596. struct: struct,
  30597. sub: sub,
  30598. subBuild: subBuild,
  30599. subgroupIndex: subgroupIndex,
  30600. subgroupSize: subgroupSize,
  30601. tan: tan,
  30602. tangentGeometry: tangentGeometry,
  30603. tangentLocal: tangentLocal,
  30604. tangentView: tangentView,
  30605. tangentWorld: tangentWorld,
  30606. temp: temp,
  30607. texture: texture,
  30608. texture3D: texture3D,
  30609. textureBarrier: textureBarrier,
  30610. textureBicubic: textureBicubic,
  30611. textureBicubicLevel: textureBicubicLevel,
  30612. textureCubeUV: textureCubeUV,
  30613. textureLoad: textureLoad,
  30614. textureSize: textureSize,
  30615. textureStore: textureStore,
  30616. thickness: thickness,
  30617. time: time,
  30618. timerDelta: timerDelta,
  30619. timerGlobal: timerGlobal,
  30620. timerLocal: timerLocal,
  30621. toneMapping: toneMapping,
  30622. toneMappingExposure: toneMappingExposure,
  30623. toonOutlinePass: toonOutlinePass,
  30624. transformDirection: transformDirection,
  30625. transformNormal: transformNormal,
  30626. transformNormalToView: transformNormalToView,
  30627. transformedClearcoatNormalView: transformedClearcoatNormalView,
  30628. transformedNormalView: transformedNormalView,
  30629. transformedNormalWorld: transformedNormalWorld,
  30630. transmission: transmission,
  30631. transpose: transpose,
  30632. triNoise3D: triNoise3D,
  30633. triplanarTexture: triplanarTexture,
  30634. triplanarTextures: triplanarTextures,
  30635. trunc: trunc,
  30636. uint: uint,
  30637. uniform: uniform,
  30638. uniformArray: uniformArray,
  30639. uniformCubeTexture: uniformCubeTexture,
  30640. uniformGroup: uniformGroup,
  30641. uniformTexture: uniformTexture,
  30642. unpremultiplyAlpha: unpremultiplyAlpha,
  30643. userData: userData,
  30644. uv: uv$1,
  30645. uvec2: uvec2,
  30646. uvec3: uvec3,
  30647. uvec4: uvec4,
  30648. varying: varying,
  30649. varyingProperty: varyingProperty,
  30650. vec2: vec2,
  30651. vec3: vec3,
  30652. vec4: vec4,
  30653. vectorComponents: vectorComponents,
  30654. velocity: velocity,
  30655. vertexColor: vertexColor,
  30656. vertexIndex: vertexIndex,
  30657. vertexStage: vertexStage,
  30658. vibrance: vibrance,
  30659. viewZToLogarithmicDepth: viewZToLogarithmicDepth,
  30660. viewZToOrthographicDepth: viewZToOrthographicDepth,
  30661. viewZToPerspectiveDepth: viewZToPerspectiveDepth,
  30662. viewport: viewport,
  30663. viewportCoordinate: viewportCoordinate,
  30664. viewportDepthTexture: viewportDepthTexture,
  30665. viewportLinearDepth: viewportLinearDepth,
  30666. viewportMipTexture: viewportMipTexture,
  30667. viewportResolution: viewportResolution,
  30668. viewportSafeUV: viewportSafeUV,
  30669. viewportSharedTexture: viewportSharedTexture,
  30670. viewportSize: viewportSize,
  30671. viewportTexture: viewportTexture,
  30672. viewportUV: viewportUV,
  30673. wgsl: wgsl,
  30674. wgslFn: wgslFn,
  30675. workgroupArray: workgroupArray,
  30676. workgroupBarrier: workgroupBarrier,
  30677. workgroupId: workgroupId,
  30678. workingToColorSpace: workingToColorSpace,
  30679. xor: xor
  30680. });
  30681. const _clearColor = /*@__PURE__*/ new Color4();
  30682. /**
  30683. * This renderer module manages the background.
  30684. *
  30685. * @private
  30686. * @augments DataMap
  30687. */
  30688. class Background extends DataMap {
  30689. /**
  30690. * Constructs a new background management component.
  30691. *
  30692. * @param {Renderer} renderer - The renderer.
  30693. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  30694. */
  30695. constructor( renderer, nodes ) {
  30696. super();
  30697. /**
  30698. * The renderer.
  30699. *
  30700. * @type {Renderer}
  30701. */
  30702. this.renderer = renderer;
  30703. /**
  30704. * Renderer component for managing nodes related logic.
  30705. *
  30706. * @type {Nodes}
  30707. */
  30708. this.nodes = nodes;
  30709. }
  30710. /**
  30711. * Updates the background for the given scene. Depending on how `Scene.background`
  30712. * or `Scene.backgroundNode` are configured, this method might configure a simple clear
  30713. * or add a mesh to the render list for rendering the background as a textured plane
  30714. * or skybox.
  30715. *
  30716. * @param {Scene} scene - The scene.
  30717. * @param {RenderList} renderList - The current render list.
  30718. * @param {RenderContext} renderContext - The current render context.
  30719. */
  30720. update( scene, renderList, renderContext ) {
  30721. const renderer = this.renderer;
  30722. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  30723. let forceClear = false;
  30724. if ( background === null ) {
  30725. // no background settings, use clear color configuration from the renderer
  30726. renderer._clearColor.getRGB( _clearColor );
  30727. _clearColor.a = renderer._clearColor.a;
  30728. } else if ( background.isColor === true ) {
  30729. // background is an opaque color
  30730. background.getRGB( _clearColor );
  30731. _clearColor.a = 1;
  30732. forceClear = true;
  30733. } else if ( background.isNode === true ) {
  30734. const sceneData = this.get( scene );
  30735. const backgroundNode = background;
  30736. _clearColor.copy( renderer._clearColor );
  30737. let backgroundMesh = sceneData.backgroundMesh;
  30738. if ( backgroundMesh === undefined ) {
  30739. const backgroundMeshNode = context( vec4( backgroundNode ).mul( backgroundIntensity ), {
  30740. // @TODO: Add Texture2D support using node context
  30741. getUV: () => backgroundRotation.mul( normalWorldGeometry ),
  30742. getTextureLevel: () => backgroundBlurriness
  30743. } );
  30744. let viewProj = modelViewProjection;
  30745. viewProj = viewProj.setZ( viewProj.w );
  30746. const nodeMaterial = new NodeMaterial();
  30747. nodeMaterial.name = 'Background.material';
  30748. nodeMaterial.side = BackSide;
  30749. nodeMaterial.depthTest = false;
  30750. nodeMaterial.depthWrite = false;
  30751. nodeMaterial.allowOverride = false;
  30752. nodeMaterial.fog = false;
  30753. nodeMaterial.lights = false;
  30754. nodeMaterial.vertexNode = viewProj;
  30755. nodeMaterial.colorNode = backgroundMeshNode;
  30756. sceneData.backgroundMeshNode = backgroundMeshNode;
  30757. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  30758. backgroundMesh.frustumCulled = false;
  30759. backgroundMesh.name = 'Background.mesh';
  30760. backgroundMesh.onBeforeRender = function ( renderer, scene, camera ) {
  30761. this.matrixWorld.copyPosition( camera.matrixWorld );
  30762. };
  30763. function onBackgroundDispose() {
  30764. background.removeEventListener( 'dispose', onBackgroundDispose );
  30765. backgroundMesh.material.dispose();
  30766. backgroundMesh.geometry.dispose();
  30767. }
  30768. background.addEventListener( 'dispose', onBackgroundDispose );
  30769. }
  30770. const backgroundCacheKey = backgroundNode.getCacheKey();
  30771. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  30772. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  30773. sceneData.backgroundMeshNode.needsUpdate = true;
  30774. backgroundMesh.material.needsUpdate = true;
  30775. sceneData.backgroundCacheKey = backgroundCacheKey;
  30776. }
  30777. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null, null );
  30778. } else {
  30779. console.error( 'THREE.Renderer: Unsupported background configuration.', background );
  30780. }
  30781. //
  30782. const environmentBlendMode = renderer.xr.getEnvironmentBlendMode();
  30783. if ( environmentBlendMode === 'additive' ) {
  30784. _clearColor.set( 0, 0, 0, 1 );
  30785. } else if ( environmentBlendMode === 'alpha-blend' ) {
  30786. _clearColor.set( 0, 0, 0, 0 );
  30787. }
  30788. //
  30789. if ( renderer.autoClear === true || forceClear === true ) {
  30790. const clearColorValue = renderContext.clearColorValue;
  30791. clearColorValue.r = _clearColor.r;
  30792. clearColorValue.g = _clearColor.g;
  30793. clearColorValue.b = _clearColor.b;
  30794. clearColorValue.a = _clearColor.a;
  30795. // premultiply alpha
  30796. if ( renderer.backend.isWebGLBackend === true || renderer.alpha === true ) {
  30797. clearColorValue.r *= clearColorValue.a;
  30798. clearColorValue.g *= clearColorValue.a;
  30799. clearColorValue.b *= clearColorValue.a;
  30800. }
  30801. //
  30802. renderContext.depthClearValue = renderer._clearDepth;
  30803. renderContext.stencilClearValue = renderer._clearStencil;
  30804. renderContext.clearColor = renderer.autoClearColor === true;
  30805. renderContext.clearDepth = renderer.autoClearDepth === true;
  30806. renderContext.clearStencil = renderer.autoClearStencil === true;
  30807. } else {
  30808. renderContext.clearColor = false;
  30809. renderContext.clearDepth = false;
  30810. renderContext.clearStencil = false;
  30811. }
  30812. }
  30813. }
  30814. let _id$6 = 0;
  30815. /**
  30816. * A bind group represents a collection of bindings and thus a collection
  30817. * or resources. Bind groups are assigned to pipelines to provide them
  30818. * with the required resources (like uniform buffers or textures).
  30819. *
  30820. * @private
  30821. */
  30822. class BindGroup {
  30823. /**
  30824. * Constructs a new bind group.
  30825. *
  30826. * @param {string} name - The bind group's name.
  30827. * @param {Array<Binding>} bindings - An array of bindings.
  30828. * @param {number} index - The group index.
  30829. * @param {Array<Binding>} bindingsReference - An array of reference bindings.
  30830. */
  30831. constructor( name = '', bindings = [], index = 0, bindingsReference = [] ) {
  30832. /**
  30833. * The bind group's name.
  30834. *
  30835. * @type {string}
  30836. */
  30837. this.name = name;
  30838. /**
  30839. * An array of bindings.
  30840. *
  30841. * @type {Array<Binding>}
  30842. */
  30843. this.bindings = bindings;
  30844. /**
  30845. * The group index.
  30846. *
  30847. * @type {number}
  30848. */
  30849. this.index = index;
  30850. /**
  30851. * An array of reference bindings.
  30852. *
  30853. * @type {Array<Binding>}
  30854. */
  30855. this.bindingsReference = bindingsReference;
  30856. /**
  30857. * The group's ID.
  30858. *
  30859. * @type {number}
  30860. */
  30861. this.id = _id$6 ++;
  30862. }
  30863. }
  30864. /**
  30865. * This module represents the state of a node builder after it was
  30866. * used to build the nodes for a render object. The state holds the
  30867. * results of the build for further processing in the renderer.
  30868. *
  30869. * Render objects with identical cache keys share the same node builder state.
  30870. *
  30871. * @private
  30872. */
  30873. class NodeBuilderState {
  30874. /**
  30875. * Constructs a new node builder state.
  30876. *
  30877. * @param {string} vertexShader - The native vertex shader code.
  30878. * @param {string} fragmentShader - The native fragment shader code.
  30879. * @param {string} computeShader - The native compute shader code.
  30880. * @param {Array<NodeAttribute>} nodeAttributes - An array of node attributes.
  30881. * @param {Array<BindGroup>} bindings - An array of bind groups.
  30882. * @param {Array<Node>} updateNodes - An array of nodes that implement their `update()` method.
  30883. * @param {Array<Node>} updateBeforeNodes - An array of nodes that implement their `updateBefore()` method.
  30884. * @param {Array<Node>} updateAfterNodes - An array of nodes that implement their `updateAfter()` method.
  30885. * @param {NodeMaterialObserver} observer - A node material observer.
  30886. * @param {Array<Object>} transforms - An array with transform attribute objects. Only relevant when using compute shaders with WebGL 2.
  30887. */
  30888. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, observer, transforms = [] ) {
  30889. /**
  30890. * The native vertex shader code.
  30891. *
  30892. * @type {string}
  30893. */
  30894. this.vertexShader = vertexShader;
  30895. /**
  30896. * The native fragment shader code.
  30897. *
  30898. * @type {string}
  30899. */
  30900. this.fragmentShader = fragmentShader;
  30901. /**
  30902. * The native compute shader code.
  30903. *
  30904. * @type {string}
  30905. */
  30906. this.computeShader = computeShader;
  30907. /**
  30908. * An array with transform attribute objects.
  30909. * Only relevant when using compute shaders with WebGL 2.
  30910. *
  30911. * @type {Array<Object>}
  30912. */
  30913. this.transforms = transforms;
  30914. /**
  30915. * An array of node attributes representing
  30916. * the attributes of the shaders.
  30917. *
  30918. * @type {Array<NodeAttribute>}
  30919. */
  30920. this.nodeAttributes = nodeAttributes;
  30921. /**
  30922. * An array of bind groups representing the uniform or storage
  30923. * buffers, texture or samplers of the shader.
  30924. *
  30925. * @type {Array<BindGroup>}
  30926. */
  30927. this.bindings = bindings;
  30928. /**
  30929. * An array of nodes that implement their `update()` method.
  30930. *
  30931. * @type {Array<Node>}
  30932. */
  30933. this.updateNodes = updateNodes;
  30934. /**
  30935. * An array of nodes that implement their `updateBefore()` method.
  30936. *
  30937. * @type {Array<Node>}
  30938. */
  30939. this.updateBeforeNodes = updateBeforeNodes;
  30940. /**
  30941. * An array of nodes that implement their `updateAfter()` method.
  30942. *
  30943. * @type {Array<Node>}
  30944. */
  30945. this.updateAfterNodes = updateAfterNodes;
  30946. /**
  30947. * A node material observer.
  30948. *
  30949. * @type {NodeMaterialObserver}
  30950. */
  30951. this.observer = observer;
  30952. /**
  30953. * How often this state is used by render objects.
  30954. *
  30955. * @type {number}
  30956. */
  30957. this.usedTimes = 0;
  30958. }
  30959. /**
  30960. * This method is used to create a array of bind groups based
  30961. * on the existing bind groups of this state. Shared groups are
  30962. * not cloned.
  30963. *
  30964. * @return {Array<BindGroup>} A array of bind groups.
  30965. */
  30966. createBindings() {
  30967. const bindings = [];
  30968. for ( const instanceGroup of this.bindings ) {
  30969. const shared = instanceGroup.bindings[ 0 ].groupNode.shared; // All bindings in the group must have the same groupNode.
  30970. if ( shared !== true ) {
  30971. const bindingsGroup = new BindGroup( instanceGroup.name, [], instanceGroup.index, instanceGroup );
  30972. bindings.push( bindingsGroup );
  30973. for ( const instanceBinding of instanceGroup.bindings ) {
  30974. bindingsGroup.bindings.push( instanceBinding.clone() );
  30975. }
  30976. } else {
  30977. bindings.push( instanceGroup );
  30978. }
  30979. }
  30980. return bindings;
  30981. }
  30982. }
  30983. /**
  30984. * {@link NodeBuilder} is going to create instances of this class during the build process
  30985. * of nodes. They represent the final shader attributes that are going to be generated
  30986. * by the builder. Arrays of node attributes is maintained in {@link NodeBuilder#attributes}
  30987. * and {@link NodeBuilder#bufferAttributes} for this purpose.
  30988. */
  30989. class NodeAttribute {
  30990. /**
  30991. * Constructs a new node attribute.
  30992. *
  30993. * @param {string} name - The name of the attribute.
  30994. * @param {string} type - The type of the attribute.
  30995. * @param {?Node} node - An optional reference to the node.
  30996. */
  30997. constructor( name, type, node = null ) {
  30998. /**
  30999. * This flag can be used for type testing.
  31000. *
  31001. * @type {boolean}
  31002. * @readonly
  31003. * @default true
  31004. */
  31005. this.isNodeAttribute = true;
  31006. /**
  31007. * The name of the attribute.
  31008. *
  31009. * @type {string}
  31010. */
  31011. this.name = name;
  31012. /**
  31013. * The type of the attribute.
  31014. *
  31015. * @type {string}
  31016. */
  31017. this.type = type;
  31018. /**
  31019. * An optional reference to the node.
  31020. *
  31021. * @type {?Node}
  31022. * @default null
  31023. */
  31024. this.node = node;
  31025. }
  31026. }
  31027. /**
  31028. * {@link NodeBuilder} is going to create instances of this class during the build process
  31029. * of nodes. They represent the final shader uniforms that are going to be generated
  31030. * by the builder. A dictionary of node uniforms is maintained in {@link NodeBuilder#uniforms}
  31031. * for this purpose.
  31032. */
  31033. class NodeUniform {
  31034. /**
  31035. * Constructs a new node uniform.
  31036. *
  31037. * @param {string} name - The name of the uniform.
  31038. * @param {string} type - The type of the uniform.
  31039. * @param {UniformNode} node - An reference to the node.
  31040. */
  31041. constructor( name, type, node ) {
  31042. /**
  31043. * This flag can be used for type testing.
  31044. *
  31045. * @type {boolean}
  31046. * @readonly
  31047. * @default true
  31048. */
  31049. this.isNodeUniform = true;
  31050. /**
  31051. * The name of the uniform.
  31052. *
  31053. * @type {string}
  31054. */
  31055. this.name = name;
  31056. /**
  31057. * The type of the uniform.
  31058. *
  31059. * @type {string}
  31060. */
  31061. this.type = type;
  31062. /**
  31063. * An reference to the node.
  31064. *
  31065. * @type {UniformNode}
  31066. */
  31067. this.node = node.getSelf();
  31068. }
  31069. /**
  31070. * The value of the uniform node.
  31071. *
  31072. * @type {any}
  31073. */
  31074. get value() {
  31075. return this.node.value;
  31076. }
  31077. set value( val ) {
  31078. this.node.value = val;
  31079. }
  31080. /**
  31081. * The id of the uniform node.
  31082. *
  31083. * @type {number}
  31084. */
  31085. get id() {
  31086. return this.node.id;
  31087. }
  31088. /**
  31089. * The uniform node's group.
  31090. *
  31091. * @type {UniformGroupNode}
  31092. */
  31093. get groupNode() {
  31094. return this.node.groupNode;
  31095. }
  31096. }
  31097. /**
  31098. * {@link NodeBuilder} is going to create instances of this class during the build process
  31099. * of nodes. They represent the final shader variables that are going to be generated
  31100. * by the builder. A dictionary of node variables is maintained in {@link NodeBuilder#vars} for
  31101. * this purpose.
  31102. */
  31103. class NodeVar {
  31104. /**
  31105. * Constructs a new node variable.
  31106. *
  31107. * @param {string} name - The name of the variable.
  31108. * @param {string} type - The type of the variable.
  31109. * @param {boolean} [readOnly=false] - The read-only flag.
  31110. * @param {?number} [count=null] - The size.
  31111. */
  31112. constructor( name, type, readOnly = false, count = null ) {
  31113. /**
  31114. * This flag can be used for type testing.
  31115. *
  31116. * @type {boolean}
  31117. * @readonly
  31118. * @default true
  31119. */
  31120. this.isNodeVar = true;
  31121. /**
  31122. * The name of the variable.
  31123. *
  31124. * @type {string}
  31125. */
  31126. this.name = name;
  31127. /**
  31128. * The type of the variable.
  31129. *
  31130. * @type {string}
  31131. */
  31132. this.type = type;
  31133. /**
  31134. * The read-only flag.
  31135. *
  31136. * @type {boolean}
  31137. */
  31138. this.readOnly = readOnly;
  31139. /**
  31140. * The size.
  31141. *
  31142. * @type {?number}
  31143. */
  31144. this.count = count;
  31145. }
  31146. }
  31147. /**
  31148. * {@link NodeBuilder} is going to create instances of this class during the build process
  31149. * of nodes. They represent the final shader varyings that are going to be generated
  31150. * by the builder. An array of node varyings is maintained in {@link NodeBuilder#varyings} for
  31151. * this purpose.
  31152. *
  31153. * @augments NodeVar
  31154. */
  31155. class NodeVarying extends NodeVar {
  31156. /**
  31157. * Constructs a new node varying.
  31158. *
  31159. * @param {string} name - The name of the varying.
  31160. * @param {string} type - The type of the varying.
  31161. * @param {?string} interpolationType - The interpolation type of the varying.
  31162. * @param {?string} interpolationSampling - The interpolation sampling type of the varying.
  31163. */
  31164. constructor( name, type, interpolationType = null, interpolationSampling = null ) {
  31165. super( name, type );
  31166. /**
  31167. * Whether this varying requires interpolation or not. This property can be used
  31168. * to check if the varying can be optimized for a variable.
  31169. *
  31170. * @type {boolean}
  31171. * @default false
  31172. */
  31173. this.needsInterpolation = false;
  31174. /**
  31175. * This flag can be used for type testing.
  31176. *
  31177. * @type {boolean}
  31178. * @readonly
  31179. * @default true
  31180. */
  31181. this.isNodeVarying = true;
  31182. /**
  31183. * The interpolation type of the varying data.
  31184. *
  31185. * @type {?string}
  31186. * @default null
  31187. */
  31188. this.interpolationType = interpolationType;
  31189. /**
  31190. * The interpolation sampling type of varying data.
  31191. *
  31192. * @type {?string}
  31193. * @default null
  31194. */
  31195. this.interpolationSampling = interpolationSampling;
  31196. }
  31197. }
  31198. /**
  31199. * {@link NodeBuilder} is going to create instances of this class during the build process
  31200. * of nodes. They represent user-defined, native shader code portions that are going to be
  31201. * injected by the builder. A dictionary of node codes is maintained in {@link NodeBuilder#codes}
  31202. * for this purpose.
  31203. */
  31204. class NodeCode {
  31205. /**
  31206. * Constructs a new code node.
  31207. *
  31208. * @param {string} name - The name of the code.
  31209. * @param {string} type - The node type.
  31210. * @param {string} [code=''] - The native shader code.
  31211. */
  31212. constructor( name, type, code = '' ) {
  31213. /**
  31214. * The name of the code.
  31215. *
  31216. * @type {string}
  31217. */
  31218. this.name = name;
  31219. /**
  31220. * The node type.
  31221. *
  31222. * @type {string}
  31223. */
  31224. this.type = type;
  31225. /**
  31226. * The native shader code.
  31227. *
  31228. * @type {string}
  31229. * @default ''
  31230. */
  31231. this.code = code;
  31232. Object.defineProperty( this, 'isNodeCode', { value: true } );
  31233. }
  31234. }
  31235. let _id$5 = 0;
  31236. /**
  31237. * This utility class is used in {@link NodeBuilder} as an internal
  31238. * cache data structure for node data.
  31239. */
  31240. class NodeCache {
  31241. /**
  31242. * Constructs a new node cache.
  31243. *
  31244. * @param {?NodeCache} parent - A reference to a parent cache.
  31245. */
  31246. constructor( parent = null ) {
  31247. /**
  31248. * The id of the cache.
  31249. *
  31250. * @type {number}
  31251. * @readonly
  31252. */
  31253. this.id = _id$5 ++;
  31254. /**
  31255. * A weak map for managing node data.
  31256. *
  31257. * @type {WeakMap<Node, Object>}
  31258. */
  31259. this.nodesData = new WeakMap();
  31260. /**
  31261. * Reference to a parent node cache.
  31262. *
  31263. * @type {?NodeCache}
  31264. * @default null
  31265. */
  31266. this.parent = parent;
  31267. }
  31268. /**
  31269. * Returns the data for the given node.
  31270. *
  31271. * @param {Node} node - The node.
  31272. * @return {?Object} The data for the node.
  31273. */
  31274. getData( node ) {
  31275. let data = this.nodesData.get( node );
  31276. if ( data === undefined && this.parent !== null ) {
  31277. data = this.parent.getData( node );
  31278. }
  31279. return data;
  31280. }
  31281. /**
  31282. * Sets the data for a given node.
  31283. *
  31284. * @param {Node} node - The node.
  31285. * @param {Object} data - The data that should be cached.
  31286. */
  31287. setData( node, data ) {
  31288. this.nodesData.set( node, data );
  31289. }
  31290. }
  31291. class StructType {
  31292. constructor( name, members ) {
  31293. this.name = name;
  31294. this.members = members;
  31295. this.output = false;
  31296. }
  31297. }
  31298. /**
  31299. * Abstract base class for uniforms.
  31300. *
  31301. * @abstract
  31302. * @private
  31303. */
  31304. class Uniform {
  31305. /**
  31306. * Constructs a new uniform.
  31307. *
  31308. * @param {string} name - The uniform's name.
  31309. * @param {any} value - The uniform's value.
  31310. */
  31311. constructor( name, value ) {
  31312. /**
  31313. * The uniform's name.
  31314. *
  31315. * @type {string}
  31316. */
  31317. this.name = name;
  31318. /**
  31319. * The uniform's value.
  31320. *
  31321. * @type {any}
  31322. */
  31323. this.value = value;
  31324. /**
  31325. * Used to build the uniform buffer according to the STD140 layout.
  31326. * Derived uniforms will set this property to a data type specific
  31327. * value.
  31328. *
  31329. * @type {number}
  31330. */
  31331. this.boundary = 0;
  31332. /**
  31333. * The item size. Derived uniforms will set this property to a data
  31334. * type specific value.
  31335. *
  31336. * @type {number}
  31337. */
  31338. this.itemSize = 0;
  31339. /**
  31340. * This property is set by {@link UniformsGroup} and marks
  31341. * the start position in the uniform buffer.
  31342. *
  31343. * @type {number}
  31344. */
  31345. this.offset = 0;
  31346. }
  31347. /**
  31348. * Sets the uniform's value.
  31349. *
  31350. * @param {any} value - The value to set.
  31351. */
  31352. setValue( value ) {
  31353. this.value = value;
  31354. }
  31355. /**
  31356. * Returns the uniform's value.
  31357. *
  31358. * @return {any} The value.
  31359. */
  31360. getValue() {
  31361. return this.value;
  31362. }
  31363. }
  31364. /**
  31365. * Represents a Number uniform.
  31366. *
  31367. * @private
  31368. * @augments Uniform
  31369. */
  31370. class NumberUniform extends Uniform {
  31371. /**
  31372. * Constructs a new Number uniform.
  31373. *
  31374. * @param {string} name - The uniform's name.
  31375. * @param {number} value - The uniform's value.
  31376. */
  31377. constructor( name, value = 0 ) {
  31378. super( name, value );
  31379. /**
  31380. * This flag can be used for type testing.
  31381. *
  31382. * @type {boolean}
  31383. * @readonly
  31384. * @default true
  31385. */
  31386. this.isNumberUniform = true;
  31387. this.boundary = 4;
  31388. this.itemSize = 1;
  31389. }
  31390. }
  31391. /**
  31392. * Represents a Vector2 uniform.
  31393. *
  31394. * @private
  31395. * @augments Uniform
  31396. */
  31397. class Vector2Uniform extends Uniform {
  31398. /**
  31399. * Constructs a new Number uniform.
  31400. *
  31401. * @param {string} name - The uniform's name.
  31402. * @param {Vector2} value - The uniform's value.
  31403. */
  31404. constructor( name, value = new Vector2() ) {
  31405. super( name, value );
  31406. /**
  31407. * This flag can be used for type testing.
  31408. *
  31409. * @type {boolean}
  31410. * @readonly
  31411. * @default true
  31412. */
  31413. this.isVector2Uniform = true;
  31414. this.boundary = 8;
  31415. this.itemSize = 2;
  31416. }
  31417. }
  31418. /**
  31419. * Represents a Vector3 uniform.
  31420. *
  31421. * @private
  31422. * @augments Uniform
  31423. */
  31424. class Vector3Uniform extends Uniform {
  31425. /**
  31426. * Constructs a new Number uniform.
  31427. *
  31428. * @param {string} name - The uniform's name.
  31429. * @param {Vector3} value - The uniform's value.
  31430. */
  31431. constructor( name, value = new Vector3() ) {
  31432. super( name, value );
  31433. /**
  31434. * This flag can be used for type testing.
  31435. *
  31436. * @type {boolean}
  31437. * @readonly
  31438. * @default true
  31439. */
  31440. this.isVector3Uniform = true;
  31441. this.boundary = 16;
  31442. this.itemSize = 3;
  31443. }
  31444. }
  31445. /**
  31446. * Represents a Vector4 uniform.
  31447. *
  31448. * @private
  31449. * @augments Uniform
  31450. */
  31451. class Vector4Uniform extends Uniform {
  31452. /**
  31453. * Constructs a new Number uniform.
  31454. *
  31455. * @param {string} name - The uniform's name.
  31456. * @param {Vector4} value - The uniform's value.
  31457. */
  31458. constructor( name, value = new Vector4() ) {
  31459. super( name, value );
  31460. /**
  31461. * This flag can be used for type testing.
  31462. *
  31463. * @type {boolean}
  31464. * @readonly
  31465. * @default true
  31466. */
  31467. this.isVector4Uniform = true;
  31468. this.boundary = 16;
  31469. this.itemSize = 4;
  31470. }
  31471. }
  31472. /**
  31473. * Represents a Color uniform.
  31474. *
  31475. * @private
  31476. * @augments Uniform
  31477. */
  31478. class ColorUniform extends Uniform {
  31479. /**
  31480. * Constructs a new Number uniform.
  31481. *
  31482. * @param {string} name - The uniform's name.
  31483. * @param {Color} value - The uniform's value.
  31484. */
  31485. constructor( name, value = new Color() ) {
  31486. super( name, value );
  31487. /**
  31488. * This flag can be used for type testing.
  31489. *
  31490. * @type {boolean}
  31491. * @readonly
  31492. * @default true
  31493. */
  31494. this.isColorUniform = true;
  31495. this.boundary = 16;
  31496. this.itemSize = 3;
  31497. }
  31498. }
  31499. /**
  31500. * Represents a Matrix2 uniform.
  31501. *
  31502. * @private
  31503. * @augments Uniform
  31504. */
  31505. class Matrix2Uniform extends Uniform {
  31506. /**
  31507. * Constructs a new Number uniform.
  31508. *
  31509. * @param {string} name - The uniform's name.
  31510. * @param {Matrix2} value - The uniform's value.
  31511. */
  31512. constructor( name, value = new Matrix2() ) {
  31513. super( name, value );
  31514. /**
  31515. * This flag can be used for type testing.
  31516. *
  31517. * @type {boolean}
  31518. * @readonly
  31519. * @default true
  31520. */
  31521. this.isMatrix2Uniform = true;
  31522. this.boundary = 8;
  31523. this.itemSize = 4;
  31524. }
  31525. }
  31526. /**
  31527. * Represents a Matrix3 uniform.
  31528. *
  31529. * @private
  31530. * @augments Uniform
  31531. */
  31532. class Matrix3Uniform extends Uniform {
  31533. /**
  31534. * Constructs a new Number uniform.
  31535. *
  31536. * @param {string} name - The uniform's name.
  31537. * @param {Matrix3} value - The uniform's value.
  31538. */
  31539. constructor( name, value = new Matrix3() ) {
  31540. super( name, value );
  31541. /**
  31542. * This flag can be used for type testing.
  31543. *
  31544. * @type {boolean}
  31545. * @readonly
  31546. * @default true
  31547. */
  31548. this.isMatrix3Uniform = true;
  31549. this.boundary = 48;
  31550. this.itemSize = 12;
  31551. }
  31552. }
  31553. /**
  31554. * Represents a Matrix4 uniform.
  31555. *
  31556. * @private
  31557. * @augments Uniform
  31558. */
  31559. class Matrix4Uniform extends Uniform {
  31560. /**
  31561. * Constructs a new Number uniform.
  31562. *
  31563. * @param {string} name - The uniform's name.
  31564. * @param {Matrix4} value - The uniform's value.
  31565. */
  31566. constructor( name, value = new Matrix4() ) {
  31567. super( name, value );
  31568. /**
  31569. * This flag can be used for type testing.
  31570. *
  31571. * @type {boolean}
  31572. * @readonly
  31573. * @default true
  31574. */
  31575. this.isMatrix4Uniform = true;
  31576. this.boundary = 64;
  31577. this.itemSize = 16;
  31578. }
  31579. }
  31580. /**
  31581. * A special form of Number uniform binding type.
  31582. * It's value is managed by a node object.
  31583. *
  31584. * @private
  31585. * @augments NumberUniform
  31586. */
  31587. class NumberNodeUniform extends NumberUniform {
  31588. /**
  31589. * Constructs a new node-based Number uniform.
  31590. *
  31591. * @param {NodeUniform} nodeUniform - The node uniform.
  31592. */
  31593. constructor( nodeUniform ) {
  31594. super( nodeUniform.name, nodeUniform.value );
  31595. /**
  31596. * The node uniform.
  31597. *
  31598. * @type {NodeUniform}
  31599. */
  31600. this.nodeUniform = nodeUniform;
  31601. }
  31602. /**
  31603. * Overwritten to return the value of the node uniform.
  31604. *
  31605. * @return {number} The value.
  31606. */
  31607. getValue() {
  31608. return this.nodeUniform.value;
  31609. }
  31610. /**
  31611. * Returns the node uniform data type.
  31612. *
  31613. * @return {string} The data type.
  31614. */
  31615. getType() {
  31616. return this.nodeUniform.type;
  31617. }
  31618. }
  31619. /**
  31620. * A special form of Vector2 uniform binding type.
  31621. * It's value is managed by a node object.
  31622. *
  31623. * @private
  31624. * @augments Vector2Uniform
  31625. */
  31626. class Vector2NodeUniform extends Vector2Uniform {
  31627. /**
  31628. * Constructs a new node-based Vector2 uniform.
  31629. *
  31630. * @param {NodeUniform} nodeUniform - The node uniform.
  31631. */
  31632. constructor( nodeUniform ) {
  31633. super( nodeUniform.name, nodeUniform.value );
  31634. /**
  31635. * The node uniform.
  31636. *
  31637. * @type {NodeUniform}
  31638. */
  31639. this.nodeUniform = nodeUniform;
  31640. }
  31641. /**
  31642. * Overwritten to return the value of the node uniform.
  31643. *
  31644. * @return {Vector2} The value.
  31645. */
  31646. getValue() {
  31647. return this.nodeUniform.value;
  31648. }
  31649. /**
  31650. * Returns the node uniform data type.
  31651. *
  31652. * @return {string} The data type.
  31653. */
  31654. getType() {
  31655. return this.nodeUniform.type;
  31656. }
  31657. }
  31658. /**
  31659. * A special form of Vector3 uniform binding type.
  31660. * It's value is managed by a node object.
  31661. *
  31662. * @private
  31663. * @augments Vector3Uniform
  31664. */
  31665. class Vector3NodeUniform extends Vector3Uniform {
  31666. /**
  31667. * Constructs a new node-based Vector3 uniform.
  31668. *
  31669. * @param {NodeUniform} nodeUniform - The node uniform.
  31670. */
  31671. constructor( nodeUniform ) {
  31672. super( nodeUniform.name, nodeUniform.value );
  31673. /**
  31674. * The node uniform.
  31675. *
  31676. * @type {NodeUniform}
  31677. */
  31678. this.nodeUniform = nodeUniform;
  31679. }
  31680. /**
  31681. * Overwritten to return the value of the node uniform.
  31682. *
  31683. * @return {Vector3} The value.
  31684. */
  31685. getValue() {
  31686. return this.nodeUniform.value;
  31687. }
  31688. /**
  31689. * Returns the node uniform data type.
  31690. *
  31691. * @return {string} The data type.
  31692. */
  31693. getType() {
  31694. return this.nodeUniform.type;
  31695. }
  31696. }
  31697. /**
  31698. * A special form of Vector4 uniform binding type.
  31699. * It's value is managed by a node object.
  31700. *
  31701. * @private
  31702. * @augments Vector4Uniform
  31703. */
  31704. class Vector4NodeUniform extends Vector4Uniform {
  31705. /**
  31706. * Constructs a new node-based Vector4 uniform.
  31707. *
  31708. * @param {NodeUniform} nodeUniform - The node uniform.
  31709. */
  31710. constructor( nodeUniform ) {
  31711. super( nodeUniform.name, nodeUniform.value );
  31712. /**
  31713. * The node uniform.
  31714. *
  31715. * @type {NodeUniform}
  31716. */
  31717. this.nodeUniform = nodeUniform;
  31718. }
  31719. /**
  31720. * Overwritten to return the value of the node uniform.
  31721. *
  31722. * @return {Vector4} The value.
  31723. */
  31724. getValue() {
  31725. return this.nodeUniform.value;
  31726. }
  31727. /**
  31728. * Returns the node uniform data type.
  31729. *
  31730. * @return {string} The data type.
  31731. */
  31732. getType() {
  31733. return this.nodeUniform.type;
  31734. }
  31735. }
  31736. /**
  31737. * A special form of Color uniform binding type.
  31738. * It's value is managed by a node object.
  31739. *
  31740. * @private
  31741. * @augments ColorUniform
  31742. */
  31743. class ColorNodeUniform extends ColorUniform {
  31744. /**
  31745. * Constructs a new node-based Color uniform.
  31746. *
  31747. * @param {NodeUniform} nodeUniform - The node uniform.
  31748. */
  31749. constructor( nodeUniform ) {
  31750. super( nodeUniform.name, nodeUniform.value );
  31751. /**
  31752. * The node uniform.
  31753. *
  31754. * @type {NodeUniform}
  31755. */
  31756. this.nodeUniform = nodeUniform;
  31757. }
  31758. /**
  31759. * Overwritten to return the value of the node uniform.
  31760. *
  31761. * @return {Color} The value.
  31762. */
  31763. getValue() {
  31764. return this.nodeUniform.value;
  31765. }
  31766. /**
  31767. * Returns the node uniform data type.
  31768. *
  31769. * @return {string} The data type.
  31770. */
  31771. getType() {
  31772. return this.nodeUniform.type;
  31773. }
  31774. }
  31775. /**
  31776. * A special form of Matrix2 uniform binding type.
  31777. * It's value is managed by a node object.
  31778. *
  31779. * @private
  31780. * @augments Matrix2Uniform
  31781. */
  31782. class Matrix2NodeUniform extends Matrix2Uniform {
  31783. /**
  31784. * Constructs a new node-based Matrix2 uniform.
  31785. *
  31786. * @param {NodeUniform} nodeUniform - The node uniform.
  31787. */
  31788. constructor( nodeUniform ) {
  31789. super( nodeUniform.name, nodeUniform.value );
  31790. /**
  31791. * The node uniform.
  31792. *
  31793. * @type {NodeUniform}
  31794. */
  31795. this.nodeUniform = nodeUniform;
  31796. }
  31797. /**
  31798. * Overwritten to return the value of the node uniform.
  31799. *
  31800. * @return {Matrix2} The value.
  31801. */
  31802. getValue() {
  31803. return this.nodeUniform.value;
  31804. }
  31805. /**
  31806. * Returns the node uniform data type.
  31807. *
  31808. * @return {string} The data type.
  31809. */
  31810. getType() {
  31811. return this.nodeUniform.type;
  31812. }
  31813. }
  31814. /**
  31815. * A special form of Matrix3 uniform binding type.
  31816. * It's value is managed by a node object.
  31817. *
  31818. * @private
  31819. * @augments Matrix3Uniform
  31820. */
  31821. class Matrix3NodeUniform extends Matrix3Uniform {
  31822. /**
  31823. * Constructs a new node-based Matrix3 uniform.
  31824. *
  31825. * @param {NodeUniform} nodeUniform - The node uniform.
  31826. */
  31827. constructor( nodeUniform ) {
  31828. super( nodeUniform.name, nodeUniform.value );
  31829. /**
  31830. * The node uniform.
  31831. *
  31832. * @type {NodeUniform}
  31833. */
  31834. this.nodeUniform = nodeUniform;
  31835. }
  31836. /**
  31837. * Overwritten to return the value of the node uniform.
  31838. *
  31839. * @return {Matrix3} The value.
  31840. */
  31841. getValue() {
  31842. return this.nodeUniform.value;
  31843. }
  31844. /**
  31845. * Returns the node uniform data type.
  31846. *
  31847. * @return {string} The data type.
  31848. */
  31849. getType() {
  31850. return this.nodeUniform.type;
  31851. }
  31852. }
  31853. /**
  31854. * A special form of Matrix4 uniform binding type.
  31855. * It's value is managed by a node object.
  31856. *
  31857. * @private
  31858. * @augments Matrix4Uniform
  31859. */
  31860. class Matrix4NodeUniform extends Matrix4Uniform {
  31861. /**
  31862. * Constructs a new node-based Matrix4 uniform.
  31863. *
  31864. * @param {NodeUniform} nodeUniform - The node uniform.
  31865. */
  31866. constructor( nodeUniform ) {
  31867. super( nodeUniform.name, nodeUniform.value );
  31868. /**
  31869. * The node uniform.
  31870. *
  31871. * @type {NodeUniform}
  31872. */
  31873. this.nodeUniform = nodeUniform;
  31874. }
  31875. /**
  31876. * Overwritten to return the value of the node uniform.
  31877. *
  31878. * @return {Matrix4} The value.
  31879. */
  31880. getValue() {
  31881. return this.nodeUniform.value;
  31882. }
  31883. /**
  31884. * Returns the node uniform data type.
  31885. *
  31886. * @return {string} The data type.
  31887. */
  31888. getType() {
  31889. return this.nodeUniform.type;
  31890. }
  31891. }
  31892. const rendererCache = new WeakMap();
  31893. const typeFromArray = new Map( [
  31894. [ Int8Array, 'int' ],
  31895. [ Int16Array, 'int' ],
  31896. [ Int32Array, 'int' ],
  31897. [ Uint8Array, 'uint' ],
  31898. [ Uint16Array, 'uint' ],
  31899. [ Uint32Array, 'uint' ],
  31900. [ Float32Array, 'float' ]
  31901. ] );
  31902. const toFloat = ( value ) => {
  31903. if ( /e/g.test( value ) ) {
  31904. return String( value ).replace( /\+/g, '' );
  31905. } else {
  31906. value = Number( value );
  31907. return value + ( value % 1 ? '' : '.0' );
  31908. }
  31909. };
  31910. /**
  31911. * Base class for builders which generate a shader program based
  31912. * on a 3D object and its node material definition.
  31913. */
  31914. class NodeBuilder {
  31915. /**
  31916. * Constructs a new node builder.
  31917. *
  31918. * @param {Object3D} object - The 3D object.
  31919. * @param {Renderer} renderer - The current renderer.
  31920. * @param {NodeParser} parser - A reference to a node parser.
  31921. */
  31922. constructor( object, renderer, parser ) {
  31923. /**
  31924. * The 3D object.
  31925. *
  31926. * @type {Object3D}
  31927. */
  31928. this.object = object;
  31929. /**
  31930. * The material of the 3D object.
  31931. *
  31932. * @type {?Material}
  31933. */
  31934. this.material = ( object && object.material ) || null;
  31935. /**
  31936. * The geometry of the 3D object.
  31937. *
  31938. * @type {?BufferGeometry}
  31939. */
  31940. this.geometry = ( object && object.geometry ) || null;
  31941. /**
  31942. * The current renderer.
  31943. *
  31944. * @type {Renderer}
  31945. */
  31946. this.renderer = renderer;
  31947. /**
  31948. * A reference to a node parser.
  31949. *
  31950. * @type {NodeParser}
  31951. */
  31952. this.parser = parser;
  31953. /**
  31954. * The scene the 3D object belongs to.
  31955. *
  31956. * @type {?Scene}
  31957. * @default null
  31958. */
  31959. this.scene = null;
  31960. /**
  31961. * The camera the 3D object is rendered with.
  31962. *
  31963. * @type {?Camera}
  31964. * @default null
  31965. */
  31966. this.camera = null;
  31967. /**
  31968. * A list of all nodes the builder is processing
  31969. * for this 3D object.
  31970. *
  31971. * @type {Array<Node>}
  31972. */
  31973. this.nodes = [];
  31974. /**
  31975. * A list of all sequential nodes.
  31976. *
  31977. * @type {Array<Node>}
  31978. */
  31979. this.sequentialNodes = [];
  31980. /**
  31981. * A list of all nodes which {@link Node#update} method should be executed.
  31982. *
  31983. * @type {Array<Node>}
  31984. */
  31985. this.updateNodes = [];
  31986. /**
  31987. * A list of all nodes which {@link Node#updateBefore} method should be executed.
  31988. *
  31989. * @type {Array<Node>}
  31990. */
  31991. this.updateBeforeNodes = [];
  31992. /**
  31993. * A list of all nodes which {@link Node#updateAfter} method should be executed.
  31994. *
  31995. * @type {Array<Node>}
  31996. */
  31997. this.updateAfterNodes = [];
  31998. /**
  31999. * A dictionary that assigns each node to a unique hash.
  32000. *
  32001. * @type {Object<number,Node>}
  32002. */
  32003. this.hashNodes = {};
  32004. /**
  32005. * A reference to a node material observer.
  32006. *
  32007. * @type {?NodeMaterialObserver}
  32008. * @default null
  32009. */
  32010. this.observer = null;
  32011. /**
  32012. * A reference to the current lights node.
  32013. *
  32014. * @type {?LightsNode}
  32015. * @default null
  32016. */
  32017. this.lightsNode = null;
  32018. /**
  32019. * A reference to the current environment node.
  32020. *
  32021. * @type {?Node}
  32022. * @default null
  32023. */
  32024. this.environmentNode = null;
  32025. /**
  32026. * A reference to the current fog node.
  32027. *
  32028. * @type {?Node}
  32029. * @default null
  32030. */
  32031. this.fogNode = null;
  32032. /**
  32033. * The current clipping context.
  32034. *
  32035. * @type {?ClippingContext}
  32036. */
  32037. this.clippingContext = null;
  32038. /**
  32039. * The generated vertex shader.
  32040. *
  32041. * @type {?string}
  32042. */
  32043. this.vertexShader = null;
  32044. /**
  32045. * The generated fragment shader.
  32046. *
  32047. * @type {?string}
  32048. */
  32049. this.fragmentShader = null;
  32050. /**
  32051. * The generated compute shader.
  32052. *
  32053. * @type {?string}
  32054. */
  32055. this.computeShader = null;
  32056. /**
  32057. * Nodes used in the primary flow of code generation.
  32058. *
  32059. * @type {Object<string,Array<Node>>}
  32060. */
  32061. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  32062. /**
  32063. * Nodes code from `.flowNodes`.
  32064. *
  32065. * @type {Object<string,string>}
  32066. */
  32067. this.flowCode = { vertex: '', fragment: '', compute: '' };
  32068. /**
  32069. * This dictionary holds the node uniforms of the builder.
  32070. * The uniforms are maintained in an array for each shader stage.
  32071. *
  32072. * @type {Object}
  32073. */
  32074. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  32075. /**
  32076. * This dictionary holds the output structs of the builder.
  32077. * The structs are maintained in an array for each shader stage.
  32078. *
  32079. * @type {Object}
  32080. */
  32081. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  32082. /**
  32083. * This dictionary holds the bindings for each shader stage.
  32084. *
  32085. * @type {Object}
  32086. */
  32087. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  32088. /**
  32089. * This dictionary maintains the binding indices per bind group.
  32090. *
  32091. * @type {Object}
  32092. */
  32093. this.bindingsIndexes = {};
  32094. /**
  32095. * Reference to the array of bind groups.
  32096. *
  32097. * @type {?Array<BindGroup>}
  32098. */
  32099. this.bindGroups = null;
  32100. /**
  32101. * This array holds the node attributes of this builder
  32102. * created via {@link AttributeNode}.
  32103. *
  32104. * @type {Array<NodeAttribute>}
  32105. */
  32106. this.attributes = [];
  32107. /**
  32108. * This array holds the node attributes of this builder
  32109. * created via {@link BufferAttributeNode}.
  32110. *
  32111. * @type {Array<NodeAttribute>}
  32112. */
  32113. this.bufferAttributes = [];
  32114. /**
  32115. * This array holds the node varyings of this builder.
  32116. *
  32117. * @type {Array<NodeVarying>}
  32118. */
  32119. this.varyings = [];
  32120. /**
  32121. * This dictionary holds the (native) node codes of this builder.
  32122. * The codes are maintained in an array for each shader stage.
  32123. *
  32124. * @type {Object<string,Array<NodeCode>>}
  32125. */
  32126. this.codes = {};
  32127. /**
  32128. * This dictionary holds the node variables of this builder.
  32129. * The variables are maintained in an array for each shader stage.
  32130. * This dictionary is also used to count the number of variables
  32131. * according to their type (const, vars).
  32132. *
  32133. * @type {Object<string,Array<NodeVar>|number>}
  32134. */
  32135. this.vars = {};
  32136. /**
  32137. * This dictionary holds the declarations for each shader stage.
  32138. *
  32139. * @type {Object}
  32140. */
  32141. this.declarations = {};
  32142. /**
  32143. * Current code flow.
  32144. * All code generated in this stack will be stored in `.flow`.
  32145. *
  32146. * @type {{code: string}}
  32147. */
  32148. this.flow = { code: '' };
  32149. /**
  32150. * A chain of nodes.
  32151. * Used to check recursive calls in node-graph.
  32152. *
  32153. * @type {Array<Node>}
  32154. */
  32155. this.chaining = [];
  32156. /**
  32157. * The current stack.
  32158. * This reflects the current process in the code block hierarchy,
  32159. * it is useful to know if the current process is inside a conditional for example.
  32160. *
  32161. * @type {StackNode}
  32162. */
  32163. this.stack = stack();
  32164. /**
  32165. * List of stack nodes.
  32166. * The current stack hierarchy is stored in an array.
  32167. *
  32168. * @type {Array<StackNode>}
  32169. */
  32170. this.stacks = [];
  32171. /**
  32172. * A tab value. Used for shader string generation.
  32173. *
  32174. * @type {string}
  32175. * @default '\t'
  32176. */
  32177. this.tab = '\t';
  32178. /**
  32179. * Reference to the current function node.
  32180. *
  32181. * @type {?FunctionNode}
  32182. * @default null
  32183. */
  32184. this.currentFunctionNode = null;
  32185. /**
  32186. * The builder's context.
  32187. *
  32188. * @type {Object}
  32189. */
  32190. this.context = {
  32191. material: this.material
  32192. };
  32193. /**
  32194. * The builder's cache.
  32195. *
  32196. * @type {NodeCache}
  32197. */
  32198. this.cache = new NodeCache();
  32199. /**
  32200. * Since the {@link NodeBuilder#cache} might be temporarily
  32201. * overwritten by other caches, this member retains the reference
  32202. * to the builder's own cache.
  32203. *
  32204. * @type {NodeCache}
  32205. * @default this.cache
  32206. */
  32207. this.globalCache = this.cache;
  32208. this.flowsData = new WeakMap();
  32209. /**
  32210. * The current shader stage.
  32211. *
  32212. * @type {?('vertex'|'fragment'|'compute'|'any')}
  32213. */
  32214. this.shaderStage = null;
  32215. /**
  32216. * The current build stage.
  32217. *
  32218. * @type {?('setup'|'analyze'|'generate')}
  32219. */
  32220. this.buildStage = null;
  32221. /**
  32222. * The sub-build layers.
  32223. *
  32224. * @type {Array<SubBuildNode>}
  32225. * @default []
  32226. */
  32227. this.subBuildLayers = [];
  32228. /**
  32229. * The current stack of nodes.
  32230. *
  32231. * @type {?StackNode}
  32232. * @default null
  32233. */
  32234. this.currentStack = null;
  32235. /**
  32236. * The current sub-build TSL function(Fn).
  32237. *
  32238. * @type {?string}
  32239. * @default null
  32240. */
  32241. this.subBuildFn = null;
  32242. }
  32243. /**
  32244. * Returns the bind groups of the current renderer.
  32245. *
  32246. * @return {ChainMap} The cache.
  32247. */
  32248. getBindGroupsCache() {
  32249. let bindGroupsCache = rendererCache.get( this.renderer );
  32250. if ( bindGroupsCache === undefined ) {
  32251. bindGroupsCache = new ChainMap();
  32252. rendererCache.set( this.renderer, bindGroupsCache );
  32253. }
  32254. return bindGroupsCache;
  32255. }
  32256. /**
  32257. * Factory method for creating an instance of {@link RenderTarget} with the given
  32258. * dimensions and options.
  32259. *
  32260. * @param {number} width - The width of the render target.
  32261. * @param {number} height - The height of the render target.
  32262. * @param {Object} options - The options of the render target.
  32263. * @return {RenderTarget} The render target.
  32264. */
  32265. createRenderTarget( width, height, options ) {
  32266. return new RenderTarget( width, height, options );
  32267. }
  32268. /**
  32269. * Factory method for creating an instance of {@link CubeRenderTarget} with the given
  32270. * dimensions and options.
  32271. *
  32272. * @param {number} size - The size of the cube render target.
  32273. * @param {Object} options - The options of the cube render target.
  32274. * @return {CubeRenderTarget} The cube render target.
  32275. */
  32276. createCubeRenderTarget( size, options ) {
  32277. return new CubeRenderTarget( size, options );
  32278. }
  32279. /**
  32280. * Whether the given node is included in the internal array of nodes or not.
  32281. *
  32282. * @param {Node} node - The node to test.
  32283. * @return {boolean} Whether the given node is included in the internal array of nodes or not.
  32284. */
  32285. includes( node ) {
  32286. return this.nodes.includes( node );
  32287. }
  32288. /**
  32289. * Returns the output struct name which is required by
  32290. * {@link OutputStructNode}.
  32291. *
  32292. * @abstract
  32293. * @return {string} The name of the output struct.
  32294. */
  32295. getOutputStructName() {}
  32296. /**
  32297. * Returns a bind group for the given group name and binding.
  32298. *
  32299. * @private
  32300. * @param {string} groupName - The group name.
  32301. * @param {Array<NodeUniformsGroup>} bindings - List of bindings.
  32302. * @return {BindGroup} The bind group
  32303. */
  32304. _getBindGroup( groupName, bindings ) {
  32305. const bindGroupsCache = this.getBindGroupsCache();
  32306. //
  32307. const bindingsArray = [];
  32308. let sharedGroup = true;
  32309. for ( const binding of bindings ) {
  32310. bindingsArray.push( binding );
  32311. sharedGroup = sharedGroup && binding.groupNode.shared !== true;
  32312. }
  32313. //
  32314. let bindGroup;
  32315. if ( sharedGroup ) {
  32316. bindGroup = bindGroupsCache.get( bindingsArray );
  32317. if ( bindGroup === undefined ) {
  32318. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  32319. bindGroupsCache.set( bindingsArray, bindGroup );
  32320. }
  32321. } else {
  32322. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  32323. }
  32324. return bindGroup;
  32325. }
  32326. /**
  32327. * Returns an array of node uniform groups for the given group name and shader stage.
  32328. *
  32329. * @param {string} groupName - The group name.
  32330. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  32331. * @return {Array<NodeUniformsGroup>} The array of node uniform groups.
  32332. */
  32333. getBindGroupArray( groupName, shaderStage ) {
  32334. const bindings = this.bindings[ shaderStage ];
  32335. let bindGroup = bindings[ groupName ];
  32336. if ( bindGroup === undefined ) {
  32337. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  32338. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  32339. }
  32340. bindings[ groupName ] = bindGroup = [];
  32341. }
  32342. return bindGroup;
  32343. }
  32344. /**
  32345. * Returns a list bindings of all shader stages separated by groups.
  32346. *
  32347. * @return {Array<BindGroup>} The list of bindings.
  32348. */
  32349. getBindings() {
  32350. let bindingsGroups = this.bindGroups;
  32351. if ( bindingsGroups === null ) {
  32352. const groups = {};
  32353. const bindings = this.bindings;
  32354. for ( const shaderStage of shaderStages ) {
  32355. for ( const groupName in bindings[ shaderStage ] ) {
  32356. const uniforms = bindings[ shaderStage ][ groupName ];
  32357. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  32358. groupUniforms.push( ...uniforms );
  32359. }
  32360. }
  32361. bindingsGroups = [];
  32362. for ( const groupName in groups ) {
  32363. const group = groups[ groupName ];
  32364. const bindingsGroup = this._getBindGroup( groupName, group );
  32365. bindingsGroups.push( bindingsGroup );
  32366. }
  32367. this.bindGroups = bindingsGroups;
  32368. }
  32369. return bindingsGroups;
  32370. }
  32371. /**
  32372. * Sorts the bind groups and updates {@link NodeBuilder#bindingsIndexes}.
  32373. */
  32374. sortBindingGroups() {
  32375. const bindingsGroups = this.getBindings();
  32376. bindingsGroups.sort( ( a, b ) => ( a.bindings[ 0 ].groupNode.order - b.bindings[ 0 ].groupNode.order ) );
  32377. for ( let i = 0; i < bindingsGroups.length; i ++ ) {
  32378. const bindingGroup = bindingsGroups[ i ];
  32379. this.bindingsIndexes[ bindingGroup.name ].group = i;
  32380. bindingGroup.index = i;
  32381. }
  32382. }
  32383. /**
  32384. * The builder maintains each node in a hash-based dictionary.
  32385. * This method sets the given node (value) with the given hash (key) into this dictionary.
  32386. *
  32387. * @param {Node} node - The node to add.
  32388. * @param {number} hash - The hash of the node.
  32389. */
  32390. setHashNode( node, hash ) {
  32391. this.hashNodes[ hash ] = node;
  32392. }
  32393. /**
  32394. * Adds a node to this builder.
  32395. *
  32396. * @param {Node} node - The node to add.
  32397. */
  32398. addNode( node ) {
  32399. if ( this.nodes.includes( node ) === false ) {
  32400. this.nodes.push( node );
  32401. this.setHashNode( node, node.getHash( this ) );
  32402. }
  32403. }
  32404. /**
  32405. * It is used to add Nodes that will be used as FRAME and RENDER events,
  32406. * and need to follow a certain sequence in the calls to work correctly.
  32407. * This function should be called after 'setup()' in the 'build()' process to ensure that the child nodes are processed first.
  32408. *
  32409. * @param {Node} node - The node to add.
  32410. */
  32411. addSequentialNode( node ) {
  32412. if ( this.sequentialNodes.includes( node ) === false ) {
  32413. this.sequentialNodes.push( node );
  32414. }
  32415. }
  32416. /**
  32417. * Checks the update types of nodes
  32418. */
  32419. buildUpdateNodes() {
  32420. for ( const node of this.nodes ) {
  32421. const updateType = node.getUpdateType();
  32422. if ( updateType !== NodeUpdateType.NONE ) {
  32423. this.updateNodes.push( node.getSelf() );
  32424. }
  32425. }
  32426. for ( const node of this.sequentialNodes ) {
  32427. const updateBeforeType = node.getUpdateBeforeType();
  32428. const updateAfterType = node.getUpdateAfterType();
  32429. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  32430. this.updateBeforeNodes.push( node.getSelf() );
  32431. }
  32432. if ( updateAfterType !== NodeUpdateType.NONE ) {
  32433. this.updateAfterNodes.push( node.getSelf() );
  32434. }
  32435. }
  32436. }
  32437. /**
  32438. * A reference the current node which is the
  32439. * last node in the chain of nodes.
  32440. *
  32441. * @type {Node}
  32442. */
  32443. get currentNode() {
  32444. return this.chaining[ this.chaining.length - 1 ];
  32445. }
  32446. /**
  32447. * Whether the given texture is filtered or not.
  32448. *
  32449. * @param {Texture} texture - The texture to check.
  32450. * @return {boolean} Whether the given texture is filtered or not.
  32451. */
  32452. isFilteredTexture( texture ) {
  32453. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  32454. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  32455. }
  32456. /**
  32457. * Adds the given node to the internal node chain.
  32458. * This is used to check recursive calls in node-graph.
  32459. *
  32460. * @param {Node} node - The node to add.
  32461. */
  32462. addChain( node ) {
  32463. /*
  32464. if ( this.chaining.indexOf( node ) !== - 1 ) {
  32465. console.warn( 'Recursive node: ', node );
  32466. }
  32467. */
  32468. this.chaining.push( node );
  32469. }
  32470. /**
  32471. * Removes the given node from the internal node chain.
  32472. *
  32473. * @param {Node} node - The node to remove.
  32474. */
  32475. removeChain( node ) {
  32476. const lastChain = this.chaining.pop();
  32477. if ( lastChain !== node ) {
  32478. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  32479. }
  32480. }
  32481. /**
  32482. * Returns the native shader method name for a given generic name. E.g.
  32483. * the method name `textureDimensions` matches the WGSL name but must be
  32484. * resolved to `textureSize` in GLSL.
  32485. *
  32486. * @abstract
  32487. * @param {string} method - The method name to resolve.
  32488. * @return {string} The resolved method name.
  32489. */
  32490. getMethod( method ) {
  32491. return method;
  32492. }
  32493. /**
  32494. * Returns a node for the given hash, see {@link NodeBuilder#setHashNode}.
  32495. *
  32496. * @param {number} hash - The hash of the node.
  32497. * @return {Node} The found node.
  32498. */
  32499. getNodeFromHash( hash ) {
  32500. return this.hashNodes[ hash ];
  32501. }
  32502. /**
  32503. * Adds the Node to a target flow so that it can generate code in the 'generate' process.
  32504. *
  32505. * @param {('vertex'|'fragment'|'compute')} shaderStage - The shader stage.
  32506. * @param {Node} node - The node to add.
  32507. * @return {Node} The node.
  32508. */
  32509. addFlow( shaderStage, node ) {
  32510. this.flowNodes[ shaderStage ].push( node );
  32511. return node;
  32512. }
  32513. /**
  32514. * Sets builder's context.
  32515. *
  32516. * @param {Object} context - The context to set.
  32517. */
  32518. setContext( context ) {
  32519. this.context = context;
  32520. }
  32521. /**
  32522. * Returns the builder's current context.
  32523. *
  32524. * @return {Object} The builder's current context.
  32525. */
  32526. getContext() {
  32527. return this.context;
  32528. }
  32529. /**
  32530. * Gets a context used in shader construction that can be shared across different materials.
  32531. * This is necessary since the renderer cache can reuse shaders generated in one material and use them in another.
  32532. *
  32533. * @return {Object} The builder's current context without material.
  32534. */
  32535. getSharedContext() {
  32536. ({ ...this.context });
  32537. return this.context;
  32538. }
  32539. /**
  32540. * Sets builder's cache.
  32541. *
  32542. * @param {NodeCache} cache - The cache to set.
  32543. */
  32544. setCache( cache ) {
  32545. this.cache = cache;
  32546. }
  32547. /**
  32548. * Returns the builder's current cache.
  32549. *
  32550. * @return {NodeCache} The builder's current cache.
  32551. */
  32552. getCache() {
  32553. return this.cache;
  32554. }
  32555. /**
  32556. * Returns a cache for the given node.
  32557. *
  32558. * @param {Node} node - The node.
  32559. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  32560. * @return {NodeCache} The cache.
  32561. */
  32562. getCacheFromNode( node, parent = true ) {
  32563. const data = this.getDataFromNode( node );
  32564. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  32565. return data.cache;
  32566. }
  32567. /**
  32568. * Whether the requested feature is available or not.
  32569. *
  32570. * @abstract
  32571. * @param {string} name - The requested feature.
  32572. * @return {boolean} Whether the requested feature is supported or not.
  32573. */
  32574. isAvailable( /*name*/ ) {
  32575. return false;
  32576. }
  32577. /**
  32578. * Returns the vertexIndex input variable as a native shader string.
  32579. *
  32580. * @abstract
  32581. * @return {string} The instanceIndex shader string.
  32582. */
  32583. getVertexIndex() {
  32584. console.warn( 'Abstract function.' );
  32585. }
  32586. /**
  32587. * Returns the instanceIndex input variable as a native shader string.
  32588. *
  32589. * @abstract
  32590. * @return {string} The instanceIndex shader string.
  32591. */
  32592. getInstanceIndex() {
  32593. console.warn( 'Abstract function.' );
  32594. }
  32595. /**
  32596. * Returns the drawIndex input variable as a native shader string.
  32597. * Only relevant for WebGL and its `WEBGL_multi_draw` extension.
  32598. *
  32599. * @abstract
  32600. * @return {?string} The drawIndex shader string.
  32601. */
  32602. getDrawIndex() {
  32603. console.warn( 'Abstract function.' );
  32604. }
  32605. /**
  32606. * Returns the frontFacing input variable as a native shader string.
  32607. *
  32608. * @abstract
  32609. * @return {string} The frontFacing shader string.
  32610. */
  32611. getFrontFacing() {
  32612. console.warn( 'Abstract function.' );
  32613. }
  32614. /**
  32615. * Returns the fragCoord input variable as a native shader string.
  32616. *
  32617. * @abstract
  32618. * @return {string} The fragCoord shader string.
  32619. */
  32620. getFragCoord() {
  32621. console.warn( 'Abstract function.' );
  32622. }
  32623. /**
  32624. * Whether to flip texture data along its vertical axis or not. WebGL needs
  32625. * this method evaluate to `true`, WebGPU to `false`.
  32626. *
  32627. * @abstract
  32628. * @return {boolean} Whether to flip texture data along its vertical axis or not.
  32629. */
  32630. isFlipY() {
  32631. return false;
  32632. }
  32633. /**
  32634. * Calling this method increases the usage count for the given node by one.
  32635. *
  32636. * @param {Node} node - The node to increase the usage count for.
  32637. * @return {number} The updated usage count.
  32638. */
  32639. increaseUsage( node ) {
  32640. const nodeData = this.getDataFromNode( node );
  32641. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  32642. return nodeData.usageCount;
  32643. }
  32644. /**
  32645. * Generates a texture sample shader string for the given texture data.
  32646. *
  32647. * @abstract
  32648. * @param {Texture} texture - The texture.
  32649. * @param {string} textureProperty - The texture property name.
  32650. * @param {string} uvSnippet - Snippet defining the texture coordinates.
  32651. * @return {string} The generated shader string.
  32652. */
  32653. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  32654. console.warn( 'Abstract function.' );
  32655. }
  32656. /**
  32657. * Generates a texture LOD shader string for the given texture data.
  32658. *
  32659. * @abstract
  32660. * @param {Texture} texture - The texture.
  32661. * @param {string} textureProperty - The texture property name.
  32662. * @param {string} uvSnippet - Snippet defining the texture coordinates.
  32663. * @param {?string} depthSnippet - Snippet defining the 0-based texture array index to sample.
  32664. * @param {string} levelSnippet - Snippet defining the mip level.
  32665. * @return {string} The generated shader string.
  32666. */
  32667. generateTextureLod( /* texture, textureProperty, uvSnippet, depthSnippet, levelSnippet */ ) {
  32668. console.warn( 'Abstract function.' );
  32669. }
  32670. /**
  32671. * Generates the array declaration string.
  32672. *
  32673. * @param {string} type - The type.
  32674. * @param {?number} [count] - The count.
  32675. * @return {string} The generated value as a shader string.
  32676. */
  32677. generateArrayDeclaration( type, count ) {
  32678. return this.getType( type ) + '[ ' + count + ' ]';
  32679. }
  32680. /**
  32681. * Generates the array shader string for the given type and value.
  32682. *
  32683. * @param {string} type - The type.
  32684. * @param {?number} [count] - The count.
  32685. * @param {?Array<Node>} [values=null] - The default values.
  32686. * @return {string} The generated value as a shader string.
  32687. */
  32688. generateArray( type, count, values = null ) {
  32689. let snippet = this.generateArrayDeclaration( type, count ) + '( ';
  32690. for ( let i = 0; i < count; i ++ ) {
  32691. const value = values ? values[ i ] : null;
  32692. if ( value !== null ) {
  32693. snippet += value.build( this, type );
  32694. } else {
  32695. snippet += this.generateConst( type );
  32696. }
  32697. if ( i < count - 1 ) snippet += ', ';
  32698. }
  32699. snippet += ' )';
  32700. return snippet;
  32701. }
  32702. /**
  32703. * Generates the struct shader string.
  32704. *
  32705. * @param {string} type - The type.
  32706. * @param {Array<Object>} [membersLayout] - The count.
  32707. * @param {?Array<Node>} [values=null] - The default values.
  32708. * @return {string} The generated value as a shader string.
  32709. */
  32710. generateStruct( type, membersLayout, values = null ) {
  32711. const snippets = [];
  32712. for ( const member of membersLayout ) {
  32713. const { name, type } = member;
  32714. if ( values && values[ name ] && values[ name ].isNode ) {
  32715. snippets.push( values[ name ].build( this, type ) );
  32716. } else {
  32717. snippets.push( this.generateConst( type ) );
  32718. }
  32719. }
  32720. return type + '( ' + snippets.join( ', ' ) + ' )';
  32721. }
  32722. /**
  32723. * Generates the shader string for the given type and value.
  32724. *
  32725. * @param {string} type - The type.
  32726. * @param {?any} [value=null] - The value.
  32727. * @return {string} The generated value as a shader string.
  32728. */
  32729. generateConst( type, value = null ) {
  32730. if ( value === null ) {
  32731. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  32732. else if ( type === 'bool' ) value = false;
  32733. else if ( type === 'color' ) value = new Color();
  32734. else if ( type === 'vec2' ) value = new Vector2();
  32735. else if ( type === 'vec3' ) value = new Vector3();
  32736. else if ( type === 'vec4' ) value = new Vector4();
  32737. }
  32738. if ( type === 'float' ) return toFloat( value );
  32739. if ( type === 'int' ) return `${ Math.round( value ) }`;
  32740. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  32741. if ( type === 'bool' ) return value ? 'true' : 'false';
  32742. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  32743. const typeLength = this.getTypeLength( type );
  32744. const componentType = this.getComponentType( type );
  32745. const generateConst = value => this.generateConst( componentType, value );
  32746. if ( typeLength === 2 ) {
  32747. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  32748. } else if ( typeLength === 3 ) {
  32749. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  32750. } else if ( typeLength === 4 && type !== 'mat2' ) {
  32751. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  32752. } else if ( typeLength >= 4 && value && ( value.isMatrix2 || value.isMatrix3 || value.isMatrix4 ) ) {
  32753. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  32754. } else if ( typeLength > 4 ) {
  32755. return `${ this.getType( type ) }()`;
  32756. }
  32757. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  32758. }
  32759. /**
  32760. * It might be necessary to convert certain data types to different ones
  32761. * so this method can be used to hide the conversion.
  32762. *
  32763. * @param {string} type - The type.
  32764. * @return {string} The updated type.
  32765. */
  32766. getType( type ) {
  32767. if ( type === 'color' ) return 'vec3';
  32768. return type;
  32769. }
  32770. /**
  32771. * Whether the given attribute name is defined in the geometry or not.
  32772. *
  32773. * @param {string} name - The attribute name.
  32774. * @return {boolean} Whether the given attribute name is defined in the geometry.
  32775. */
  32776. hasGeometryAttribute( name ) {
  32777. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  32778. }
  32779. /**
  32780. * Returns a node attribute for the given name and type.
  32781. *
  32782. * @param {string} name - The attribute's name.
  32783. * @param {string} type - The attribute's type.
  32784. * @return {NodeAttribute} The node attribute.
  32785. */
  32786. getAttribute( name, type ) {
  32787. const attributes = this.attributes;
  32788. // find attribute
  32789. for ( const attribute of attributes ) {
  32790. if ( attribute.name === name ) {
  32791. return attribute;
  32792. }
  32793. }
  32794. // create a new if no exist
  32795. const attribute = new NodeAttribute( name, type );
  32796. this.registerDeclaration( attribute );
  32797. attributes.push( attribute );
  32798. return attribute;
  32799. }
  32800. /**
  32801. * Returns for the given node and shader stage the property name for the shader.
  32802. *
  32803. * @param {Node} node - The node.
  32804. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  32805. * @return {string} The property name.
  32806. */
  32807. getPropertyName( node/*, shaderStage*/ ) {
  32808. return node.name;
  32809. }
  32810. /**
  32811. * Whether the given type is a vector type or not.
  32812. *
  32813. * @param {string} type - The type to check.
  32814. * @return {boolean} Whether the given type is a vector type or not.
  32815. */
  32816. isVector( type ) {
  32817. return /vec\d/.test( type );
  32818. }
  32819. /**
  32820. * Whether the given type is a matrix type or not.
  32821. *
  32822. * @param {string} type - The type to check.
  32823. * @return {boolean} Whether the given type is a matrix type or not.
  32824. */
  32825. isMatrix( type ) {
  32826. return /mat\d/.test( type );
  32827. }
  32828. /**
  32829. * Whether the given type is a reference type or not.
  32830. *
  32831. * @param {string} type - The type to check.
  32832. * @return {boolean} Whether the given type is a reference type or not.
  32833. */
  32834. isReference( type ) {
  32835. return type === 'void' || type === 'property' || type === 'sampler' || type === 'samplerComparison' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  32836. }
  32837. /**
  32838. * Checks if the given texture requires a manual conversion to the working color space.
  32839. *
  32840. * @abstract
  32841. * @param {Texture} texture - The texture to check.
  32842. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  32843. */
  32844. needsToWorkingColorSpace( /*texture*/ ) {
  32845. return false;
  32846. }
  32847. /**
  32848. * Returns the component type of a given texture.
  32849. *
  32850. * @param {Texture} texture - The texture.
  32851. * @return {string} The component type.
  32852. */
  32853. getComponentTypeFromTexture( texture ) {
  32854. const type = texture.type;
  32855. if ( texture.isDataTexture ) {
  32856. if ( type === IntType ) return 'int';
  32857. if ( type === UnsignedIntType ) return 'uint';
  32858. }
  32859. return 'float';
  32860. }
  32861. /**
  32862. * Returns the element type for a given type.
  32863. *
  32864. * @param {string} type - The type.
  32865. * @return {string} The element type.
  32866. */
  32867. getElementType( type ) {
  32868. if ( type === 'mat2' ) return 'vec2';
  32869. if ( type === 'mat3' ) return 'vec3';
  32870. if ( type === 'mat4' ) return 'vec4';
  32871. return this.getComponentType( type );
  32872. }
  32873. /**
  32874. * Returns the component type for a given type.
  32875. *
  32876. * @param {string} type - The type.
  32877. * @return {string} The component type.
  32878. */
  32879. getComponentType( type ) {
  32880. type = this.getVectorType( type );
  32881. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  32882. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  32883. if ( componentType === null ) return null;
  32884. if ( componentType[ 1 ] === 'b' ) return 'bool';
  32885. if ( componentType[ 1 ] === 'i' ) return 'int';
  32886. if ( componentType[ 1 ] === 'u' ) return 'uint';
  32887. return 'float';
  32888. }
  32889. /**
  32890. * Returns the vector type for a given type.
  32891. *
  32892. * @param {string} type - The type.
  32893. * @return {string} The vector type.
  32894. */
  32895. getVectorType( type ) {
  32896. if ( type === 'color' ) return 'vec3';
  32897. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  32898. return type;
  32899. }
  32900. /**
  32901. * Returns the data type for the given the length and component type.
  32902. *
  32903. * @param {number} length - The length.
  32904. * @param {string} [componentType='float'] - The component type.
  32905. * @return {string} The type.
  32906. */
  32907. getTypeFromLength( length, componentType = 'float' ) {
  32908. if ( length === 1 ) return componentType;
  32909. let baseType = getTypeFromLength( length );
  32910. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  32911. // fix edge case for mat2x2 being same size as vec4
  32912. if ( /mat2/.test( componentType ) === true ) {
  32913. baseType = baseType.replace( 'vec', 'mat' );
  32914. }
  32915. return prefix + baseType;
  32916. }
  32917. /**
  32918. * Returns the type for a given typed array.
  32919. *
  32920. * @param {TypedArray} array - The typed array.
  32921. * @return {string} The type.
  32922. */
  32923. getTypeFromArray( array ) {
  32924. return typeFromArray.get( array.constructor );
  32925. }
  32926. /**
  32927. * Returns the type is an integer type.
  32928. *
  32929. * @param {string} type - The type.
  32930. * @return {boolean} Whether the type is an integer type or not.
  32931. */
  32932. isInteger( type ) {
  32933. return /int|uint|(i|u)vec/.test( type );
  32934. }
  32935. /**
  32936. * Returns the type for a given buffer attribute.
  32937. *
  32938. * @param {BufferAttribute} attribute - The buffer attribute.
  32939. * @return {string} The type.
  32940. */
  32941. getTypeFromAttribute( attribute ) {
  32942. let dataAttribute = attribute;
  32943. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  32944. const array = dataAttribute.array;
  32945. const itemSize = attribute.itemSize;
  32946. const normalized = attribute.normalized;
  32947. let arrayType;
  32948. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  32949. arrayType = this.getTypeFromArray( array );
  32950. }
  32951. return this.getTypeFromLength( itemSize, arrayType );
  32952. }
  32953. /**
  32954. * Returns the length for the given data type.
  32955. *
  32956. * @param {string} type - The data type.
  32957. * @return {number} The length.
  32958. */
  32959. getTypeLength( type ) {
  32960. const vecType = this.getVectorType( type );
  32961. const vecNum = /vec([2-4])/.exec( vecType );
  32962. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  32963. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  32964. if ( /mat2/.test( type ) === true ) return 4;
  32965. if ( /mat3/.test( type ) === true ) return 9;
  32966. if ( /mat4/.test( type ) === true ) return 16;
  32967. return 0;
  32968. }
  32969. /**
  32970. * Returns the vector type for a given matrix type.
  32971. *
  32972. * @param {string} type - The matrix type.
  32973. * @return {string} The vector type.
  32974. */
  32975. getVectorFromMatrix( type ) {
  32976. return type.replace( 'mat', 'vec' );
  32977. }
  32978. /**
  32979. * For a given type this method changes the component type to the
  32980. * given value. E.g. `vec4` should be changed to the new component type
  32981. * `uint` which results in `uvec4`.
  32982. *
  32983. * @param {string} type - The type.
  32984. * @param {string} newComponentType - The new component type.
  32985. * @return {string} The new type.
  32986. */
  32987. changeComponentType( type, newComponentType ) {
  32988. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  32989. }
  32990. /**
  32991. * Returns the integer type pendant for the given type.
  32992. *
  32993. * @param {string} type - The type.
  32994. * @return {string} The integer type.
  32995. */
  32996. getIntegerType( type ) {
  32997. const componentType = this.getComponentType( type );
  32998. if ( componentType === 'int' || componentType === 'uint' ) return type;
  32999. return this.changeComponentType( type, 'int' );
  33000. }
  33001. /**
  33002. * Adds a stack node to the internal stack.
  33003. *
  33004. * @return {StackNode} The added stack node.
  33005. */
  33006. addStack() {
  33007. this.stack = stack( this.stack );
  33008. this.stacks.push( getCurrentStack() || this.stack );
  33009. setCurrentStack( this.stack );
  33010. return this.stack;
  33011. }
  33012. /**
  33013. * Removes the last stack node from the internal stack.
  33014. *
  33015. * @return {StackNode} The removed stack node.
  33016. */
  33017. removeStack() {
  33018. const lastStack = this.stack;
  33019. this.stack = lastStack.parent;
  33020. setCurrentStack( this.stacks.pop() );
  33021. return lastStack;
  33022. }
  33023. /**
  33024. * The builder maintains (cached) data for each node during the building process. This method
  33025. * can be used to get these data for a specific shader stage and cache.
  33026. *
  33027. * @param {Node} node - The node to get the data for.
  33028. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  33029. * @param {?NodeCache} cache - An optional cache.
  33030. * @return {Object} The node data.
  33031. */
  33032. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  33033. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  33034. let nodeData = cache.getData( node );
  33035. if ( nodeData === undefined ) {
  33036. nodeData = {};
  33037. cache.setData( node, nodeData );
  33038. }
  33039. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  33040. //
  33041. let data = nodeData[ shaderStage ];
  33042. const subBuilds = nodeData.any ? nodeData.any.subBuilds : null;
  33043. const subBuild = this.getClosestSubBuild( subBuilds );
  33044. if ( subBuild ) {
  33045. if ( data.subBuildsCache === undefined ) data.subBuildsCache = {};
  33046. data = data.subBuildsCache[ subBuild ] || ( data.subBuildsCache[ subBuild ] = {} );
  33047. data.subBuilds = subBuilds;
  33048. }
  33049. return data;
  33050. }
  33051. /**
  33052. * Returns the properties for the given node and shader stage.
  33053. *
  33054. * @param {Node} node - The node to get the properties for.
  33055. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage='any'] - The shader stage.
  33056. * @return {Object} The node properties.
  33057. */
  33058. getNodeProperties( node, shaderStage = 'any' ) {
  33059. const nodeData = this.getDataFromNode( node, shaderStage );
  33060. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  33061. }
  33062. /**
  33063. * Returns an instance of {@link NodeAttribute} for the given buffer attribute node.
  33064. *
  33065. * @param {BufferAttributeNode} node - The buffer attribute node.
  33066. * @param {string} type - The node type.
  33067. * @return {NodeAttribute} The node attribute.
  33068. */
  33069. getBufferAttributeFromNode( node, type ) {
  33070. const nodeData = this.getDataFromNode( node );
  33071. let bufferAttribute = nodeData.bufferAttribute;
  33072. if ( bufferAttribute === undefined ) {
  33073. const index = this.uniforms.index ++;
  33074. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  33075. this.bufferAttributes.push( bufferAttribute );
  33076. nodeData.bufferAttribute = bufferAttribute;
  33077. }
  33078. return bufferAttribute;
  33079. }
  33080. /**
  33081. * Returns an instance of {@link StructType} for the given output struct node.
  33082. *
  33083. * @param {OutputStructNode} node - The output struct node.
  33084. * @param {Array<Object>} membersLayout - The output struct types.
  33085. * @param {?string} [name=null] - The name of the struct.
  33086. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  33087. * @return {StructType} The struct type attribute.
  33088. */
  33089. getStructTypeFromNode( node, membersLayout, name = null, shaderStage = this.shaderStage ) {
  33090. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  33091. let structType = nodeData.structType;
  33092. if ( structType === undefined ) {
  33093. const index = this.structs.index ++;
  33094. if ( name === null ) name = 'StructType' + index;
  33095. structType = new StructType( name, membersLayout );
  33096. this.structs[ shaderStage ].push( structType );
  33097. nodeData.structType = structType;
  33098. }
  33099. return structType;
  33100. }
  33101. /**
  33102. * Returns an instance of {@link StructType} for the given output struct node.
  33103. *
  33104. * @param {OutputStructNode} node - The output struct node.
  33105. * @param {Array<Object>} membersLayout - The output struct types.
  33106. * @return {StructType} The struct type attribute.
  33107. */
  33108. getOutputStructTypeFromNode( node, membersLayout ) {
  33109. const structType = this.getStructTypeFromNode( node, membersLayout, 'OutputType', 'fragment' );
  33110. structType.output = true;
  33111. return structType;
  33112. }
  33113. /**
  33114. * Returns an instance of {@link NodeUniform} for the given uniform node.
  33115. *
  33116. * @param {UniformNode} node - The uniform node.
  33117. * @param {string} type - The uniform type.
  33118. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  33119. * @param {?string} name - The name of the uniform.
  33120. * @return {NodeUniform} The node uniform.
  33121. */
  33122. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  33123. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  33124. let nodeUniform = nodeData.uniform;
  33125. if ( nodeUniform === undefined ) {
  33126. const index = this.uniforms.index ++;
  33127. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  33128. this.uniforms[ shaderStage ].push( nodeUniform );
  33129. this.registerDeclaration( nodeUniform );
  33130. nodeData.uniform = nodeUniform;
  33131. }
  33132. return nodeUniform;
  33133. }
  33134. /**
  33135. * Returns the array length.
  33136. *
  33137. * @param {Node} node - The node.
  33138. * @return {?number} The array length.
  33139. */
  33140. getArrayCount( node ) {
  33141. let count = null;
  33142. if ( node.isArrayNode ) count = node.count;
  33143. else if ( node.isVarNode && node.node.isArrayNode ) count = node.node.count;
  33144. return count;
  33145. }
  33146. /**
  33147. * Returns an instance of {@link NodeVar} for the given variable node.
  33148. *
  33149. * @param {VarNode} node - The variable node.
  33150. * @param {?string} name - The variable's name.
  33151. * @param {string} [type=node.getNodeType( this )] - The variable's type.
  33152. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  33153. * @param {boolean} [readOnly=false] - Whether the variable is read-only or not.
  33154. *
  33155. * @return {NodeVar} The node variable.
  33156. */
  33157. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage, readOnly = false ) {
  33158. const nodeData = this.getDataFromNode( node, shaderStage );
  33159. const subBuildVariable = this.getSubBuildProperty( 'variable', nodeData.subBuilds );
  33160. let nodeVar = nodeData[ subBuildVariable ];
  33161. if ( nodeVar === undefined ) {
  33162. const idNS = readOnly ? '_const' : '_var';
  33163. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  33164. const id = this.vars[ idNS ] || ( this.vars[ idNS ] = 0 );
  33165. if ( name === null ) {
  33166. name = ( readOnly ? 'nodeConst' : 'nodeVar' ) + id;
  33167. this.vars[ idNS ] ++;
  33168. }
  33169. //
  33170. if ( subBuildVariable !== 'variable' ) {
  33171. name = this.getSubBuildProperty( name, nodeData.subBuilds );
  33172. }
  33173. //
  33174. const count = this.getArrayCount( node );
  33175. nodeVar = new NodeVar( name, type, readOnly, count );
  33176. if ( ! readOnly ) {
  33177. vars.push( nodeVar );
  33178. }
  33179. this.registerDeclaration( nodeVar );
  33180. nodeData[ subBuildVariable ] = nodeVar;
  33181. }
  33182. return nodeVar;
  33183. }
  33184. /**
  33185. * Returns whether a Node or its flow is deterministic, useful for use in `const`.
  33186. *
  33187. * @param {Node} node - The varying node.
  33188. * @return {boolean} Returns true if deterministic.
  33189. */
  33190. isDeterministic( node ) {
  33191. if ( node.isMathNode ) {
  33192. return this.isDeterministic( node.aNode ) &&
  33193. ( node.bNode ? this.isDeterministic( node.bNode ) : true ) &&
  33194. ( node.cNode ? this.isDeterministic( node.cNode ) : true );
  33195. } else if ( node.isOperatorNode ) {
  33196. return this.isDeterministic( node.aNode ) &&
  33197. ( node.bNode ? this.isDeterministic( node.bNode ) : true );
  33198. } else if ( node.isArrayNode ) {
  33199. if ( node.values !== null ) {
  33200. for ( const n of node.values ) {
  33201. if ( ! this.isDeterministic( n ) ) {
  33202. return false;
  33203. }
  33204. }
  33205. }
  33206. return true;
  33207. } else if ( node.isConstNode ) {
  33208. return true;
  33209. }
  33210. return false;
  33211. }
  33212. /**
  33213. * Returns an instance of {@link NodeVarying} for the given varying node.
  33214. *
  33215. * @param {(VaryingNode|PropertyNode)} node - The varying node.
  33216. * @param {?string} name - The varying's name.
  33217. * @param {string} [type=node.getNodeType( this )] - The varying's type.
  33218. * @param {?string} interpolationType - The interpolation type of the varying.
  33219. * @param {?string} interpolationSampling - The interpolation sampling type of the varying.
  33220. * @return {NodeVar} The node varying.
  33221. */
  33222. getVaryingFromNode( node, name = null, type = node.getNodeType( this ), interpolationType = null, interpolationSampling = null ) {
  33223. const nodeData = this.getDataFromNode( node, 'any' );
  33224. const subBuildVarying = this.getSubBuildProperty( 'varying', nodeData.subBuilds );
  33225. let nodeVarying = nodeData[ subBuildVarying ];
  33226. if ( nodeVarying === undefined ) {
  33227. const varyings = this.varyings;
  33228. const index = varyings.length;
  33229. if ( name === null ) name = 'nodeVarying' + index;
  33230. //
  33231. if ( subBuildVarying !== 'varying' ) {
  33232. name = this.getSubBuildProperty( name, nodeData.subBuilds );
  33233. }
  33234. //
  33235. nodeVarying = new NodeVarying( name, type, interpolationType, interpolationSampling );
  33236. varyings.push( nodeVarying );
  33237. this.registerDeclaration( nodeVarying );
  33238. nodeData[ subBuildVarying ] = nodeVarying;
  33239. }
  33240. return nodeVarying;
  33241. }
  33242. /**
  33243. * Registers a node declaration in the current shader stage.
  33244. *
  33245. * @param {Object} node - The node to be registered.
  33246. */
  33247. registerDeclaration( node ) {
  33248. const shaderStage = this.shaderStage;
  33249. const declarations = this.declarations[ shaderStage ] || ( this.declarations[ shaderStage ] = {} );
  33250. const property = this.getPropertyName( node );
  33251. let index = 1;
  33252. let name = property;
  33253. // Automatically renames the property if the name is already in use.
  33254. while ( declarations[ name ] !== undefined ) {
  33255. name = property + '_' + index ++;
  33256. }
  33257. if ( index > 1 ) {
  33258. node.name = name;
  33259. console.warn( `THREE.TSL: Declaration name '${ property }' of '${ node.type }' already in use. Renamed to '${ name }'.` );
  33260. }
  33261. declarations[ name ] = node;
  33262. }
  33263. /**
  33264. * Returns an instance of {@link NodeCode} for the given code node.
  33265. *
  33266. * @param {CodeNode} node - The code node.
  33267. * @param {string} type - The node type.
  33268. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  33269. * @return {NodeCode} The node code.
  33270. */
  33271. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  33272. const nodeData = this.getDataFromNode( node );
  33273. let nodeCode = nodeData.code;
  33274. if ( nodeCode === undefined ) {
  33275. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  33276. const index = codes.length;
  33277. nodeCode = new NodeCode( 'nodeCode' + index, type );
  33278. codes.push( nodeCode );
  33279. nodeData.code = nodeCode;
  33280. }
  33281. return nodeCode;
  33282. }
  33283. /**
  33284. * Adds a code flow based on the code-block hierarchy.
  33285. * This is used so that code-blocks like If,Else create their variables locally if the Node
  33286. * is only used inside one of these conditionals in the current shader stage.
  33287. *
  33288. * @param {Node} node - The node to add.
  33289. * @param {Node} nodeBlock - Node-based code-block. Usually 'ConditionalNode'.
  33290. */
  33291. addFlowCodeHierarchy( node, nodeBlock ) {
  33292. const { flowCodes, flowCodeBlock } = this.getDataFromNode( node );
  33293. let needsFlowCode = true;
  33294. let nodeBlockHierarchy = nodeBlock;
  33295. while ( nodeBlockHierarchy ) {
  33296. if ( flowCodeBlock.get( nodeBlockHierarchy ) === true ) {
  33297. needsFlowCode = false;
  33298. break;
  33299. }
  33300. nodeBlockHierarchy = this.getDataFromNode( nodeBlockHierarchy ).parentNodeBlock;
  33301. }
  33302. if ( needsFlowCode ) {
  33303. for ( const flowCode of flowCodes ) {
  33304. this.addLineFlowCode( flowCode );
  33305. }
  33306. }
  33307. }
  33308. /**
  33309. * Add a inline-code to the current flow code-block.
  33310. *
  33311. * @param {Node} node - The node to add.
  33312. * @param {string} code - The code to add.
  33313. * @param {Node} nodeBlock - Current ConditionalNode
  33314. */
  33315. addLineFlowCodeBlock( node, code, nodeBlock ) {
  33316. const nodeData = this.getDataFromNode( node );
  33317. const flowCodes = nodeData.flowCodes || ( nodeData.flowCodes = [] );
  33318. const codeBlock = nodeData.flowCodeBlock || ( nodeData.flowCodeBlock = new WeakMap() );
  33319. flowCodes.push( code );
  33320. codeBlock.set( nodeBlock, true );
  33321. }
  33322. /**
  33323. * Add a inline-code to the current flow.
  33324. *
  33325. * @param {string} code - The code to add.
  33326. * @param {?Node} [node= null] - Optional Node, can help the system understand if the Node is part of a code-block.
  33327. * @return {NodeBuilder} A reference to this node builder.
  33328. */
  33329. addLineFlowCode( code, node = null ) {
  33330. if ( code === '' ) return this;
  33331. if ( node !== null && this.context.nodeBlock ) {
  33332. this.addLineFlowCodeBlock( node, code, this.context.nodeBlock );
  33333. }
  33334. code = this.tab + code;
  33335. if ( ! /;\s*$/.test( code ) ) {
  33336. code = code + ';\n';
  33337. }
  33338. this.flow.code += code;
  33339. return this;
  33340. }
  33341. /**
  33342. * Adds a code to the current code flow.
  33343. *
  33344. * @param {string} code - Shader code.
  33345. * @return {NodeBuilder} A reference to this node builder.
  33346. */
  33347. addFlowCode( code ) {
  33348. this.flow.code += code;
  33349. return this;
  33350. }
  33351. /**
  33352. * Add tab in the code that will be generated so that other snippets respect the current tabulation.
  33353. * Typically used in codes with If,Else.
  33354. *
  33355. * @return {NodeBuilder} A reference to this node builder.
  33356. */
  33357. addFlowTab() {
  33358. this.tab += '\t';
  33359. return this;
  33360. }
  33361. /**
  33362. * Removes a tab.
  33363. *
  33364. * @return {NodeBuilder} A reference to this node builder.
  33365. */
  33366. removeFlowTab() {
  33367. this.tab = this.tab.slice( 0, -1 );
  33368. return this;
  33369. }
  33370. /**
  33371. * Gets the current flow data based on a Node.
  33372. *
  33373. * @param {Node} node - Node that the flow was started.
  33374. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  33375. * @return {Object} The flow data.
  33376. */
  33377. getFlowData( node/*, shaderStage*/ ) {
  33378. return this.flowsData.get( node );
  33379. }
  33380. /**
  33381. * Executes the node flow based on a root node to generate the final shader code.
  33382. *
  33383. * @param {Node} node - The node to execute.
  33384. * @return {Object} The code flow.
  33385. */
  33386. flowNode( node ) {
  33387. const output = node.getNodeType( this );
  33388. const flowData = this.flowChildNode( node, output );
  33389. this.flowsData.set( node, flowData );
  33390. return flowData;
  33391. }
  33392. /**
  33393. * Includes a node in the current function node.
  33394. *
  33395. * @param {Node} node - The node to include.
  33396. * @returns {void}
  33397. */
  33398. addInclude( node ) {
  33399. if ( this.currentFunctionNode !== null ) {
  33400. this.currentFunctionNode.includes.push( node );
  33401. }
  33402. }
  33403. /**
  33404. * Returns the native shader operator name for a given generic name.
  33405. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  33406. *
  33407. * @param {ShaderNodeInternal} shaderNode - The shader node to build the function node with.
  33408. * @return {FunctionNode} The build function node.
  33409. */
  33410. buildFunctionNode( shaderNode ) {
  33411. const fn = new FunctionNode();
  33412. const previous = this.currentFunctionNode;
  33413. this.currentFunctionNode = fn;
  33414. fn.code = this.buildFunctionCode( shaderNode );
  33415. this.currentFunctionNode = previous;
  33416. return fn;
  33417. }
  33418. /**
  33419. * Generates a code flow based on a TSL function: Fn().
  33420. *
  33421. * @param {ShaderNodeInternal} shaderNode - A function code will be generated based on the input.
  33422. * @return {Object}
  33423. */
  33424. flowShaderNode( shaderNode ) {
  33425. const layout = shaderNode.layout;
  33426. const inputs = {
  33427. [ Symbol.iterator ]() {
  33428. let index = 0;
  33429. const values = Object.values( this );
  33430. return {
  33431. next: () => ( {
  33432. value: values[ index ],
  33433. done: index ++ >= values.length
  33434. } )
  33435. };
  33436. }
  33437. };
  33438. for ( const input of layout.inputs ) {
  33439. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  33440. }
  33441. //
  33442. shaderNode.layout = null;
  33443. const callNode = shaderNode.call( inputs );
  33444. const flowData = this.flowStagesNode( callNode, layout.type );
  33445. shaderNode.layout = layout;
  33446. return flowData;
  33447. }
  33448. /**
  33449. * Runs the node flow through all the steps of creation, 'setup', 'analyze', 'generate'.
  33450. *
  33451. * @param {Node} node - The node to execute.
  33452. * @param {?string} output - Expected output type. For example 'vec3'.
  33453. * @return {Object}
  33454. */
  33455. flowStagesNode( node, output = null ) {
  33456. const previousFlow = this.flow;
  33457. const previousVars = this.vars;
  33458. const previousDeclarations = this.declarations;
  33459. const previousCache = this.cache;
  33460. const previousBuildStage = this.buildStage;
  33461. const previousStack = this.stack;
  33462. const flow = {
  33463. code: ''
  33464. };
  33465. this.flow = flow;
  33466. this.vars = {};
  33467. this.declarations = {};
  33468. this.cache = new NodeCache();
  33469. this.stack = stack();
  33470. for ( const buildStage of defaultBuildStages ) {
  33471. this.setBuildStage( buildStage );
  33472. flow.result = node.build( this, output );
  33473. }
  33474. flow.vars = this.getVars( this.shaderStage );
  33475. this.flow = previousFlow;
  33476. this.vars = previousVars;
  33477. this.declarations = previousDeclarations;
  33478. this.cache = previousCache;
  33479. this.stack = previousStack;
  33480. this.setBuildStage( previousBuildStage );
  33481. return flow;
  33482. }
  33483. /**
  33484. * Returns the native shader operator name for a given generic name.
  33485. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  33486. *
  33487. * @abstract
  33488. * @param {string} op - The operator name to resolve.
  33489. * @return {?string} The resolved operator name.
  33490. */
  33491. getFunctionOperator( /* op */ ) {
  33492. return null;
  33493. }
  33494. /**
  33495. * Builds the given shader node.
  33496. *
  33497. * @abstract
  33498. * @param {ShaderNodeInternal} shaderNode - The shader node.
  33499. * @return {string} The function code.
  33500. */
  33501. buildFunctionCode( /* shaderNode */ ) {
  33502. console.warn( 'Abstract function.' );
  33503. }
  33504. /**
  33505. * Generates a code flow based on a child Node.
  33506. *
  33507. * @param {Node} node - The node to execute.
  33508. * @param {?string} output - Expected output type. For example 'vec3'.
  33509. * @return {Object} The code flow.
  33510. */
  33511. flowChildNode( node, output = null ) {
  33512. const previousFlow = this.flow;
  33513. const flow = {
  33514. code: ''
  33515. };
  33516. this.flow = flow;
  33517. flow.result = node.build( this, output );
  33518. this.flow = previousFlow;
  33519. return flow;
  33520. }
  33521. /**
  33522. * Executes a flow of code in a different stage.
  33523. *
  33524. * Some nodes like `varying()` have the ability to compute code in vertex-stage and
  33525. * return the value in fragment-stage even if it is being executed in an input fragment.
  33526. *
  33527. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  33528. * @param {Node} node - The node to execute.
  33529. * @param {?string} output - Expected output type. For example 'vec3'.
  33530. * @param {?string} propertyName - The property name to assign the result.
  33531. * @return {Object|Node|null} The code flow or node.build() result.
  33532. */
  33533. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  33534. const previousTab = this.tab;
  33535. const previousCache = this.cache;
  33536. const previousShaderStage = this.shaderStage;
  33537. const previousContext = this.context;
  33538. this.setShaderStage( shaderStage );
  33539. const context = { ...this.context };
  33540. delete context.nodeBlock;
  33541. this.cache = this.globalCache;
  33542. this.tab = '\t';
  33543. this.context = context;
  33544. let result = null;
  33545. if ( this.buildStage === 'generate' ) {
  33546. const flowData = this.flowChildNode( node, output );
  33547. if ( propertyName !== null ) {
  33548. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  33549. }
  33550. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  33551. result = flowData;
  33552. } else {
  33553. result = node.build( this );
  33554. }
  33555. this.setShaderStage( previousShaderStage );
  33556. this.cache = previousCache;
  33557. this.tab = previousTab;
  33558. this.context = previousContext;
  33559. return result;
  33560. }
  33561. /**
  33562. * Returns an array holding all node attributes of this node builder.
  33563. *
  33564. * @return {Array<NodeAttribute>} The node attributes of this builder.
  33565. */
  33566. getAttributesArray() {
  33567. return this.attributes.concat( this.bufferAttributes );
  33568. }
  33569. /**
  33570. * Returns the attribute definitions as a shader string for the given shader stage.
  33571. *
  33572. * @abstract
  33573. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  33574. * @return {string} The attribute code section.
  33575. */
  33576. getAttributes( /*shaderStage*/ ) {
  33577. console.warn( 'Abstract function.' );
  33578. }
  33579. /**
  33580. * Returns the varying definitions as a shader string for the given shader stage.
  33581. *
  33582. * @abstract
  33583. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  33584. * @return {string} The varying code section.
  33585. */
  33586. getVaryings( /*shaderStage*/ ) {
  33587. console.warn( 'Abstract function.' );
  33588. }
  33589. /**
  33590. * Returns a single variable definition as a shader string for the given variable type and name.
  33591. *
  33592. * @param {string} type - The variable's type.
  33593. * @param {string} name - The variable's name.
  33594. * @param {?number} [count=null] - The array length.
  33595. * @return {string} The shader string.
  33596. */
  33597. getVar( type, name, count = null ) {
  33598. return `${ count !== null ? this.generateArrayDeclaration( type, count ) : this.getType( type ) } ${ name }`;
  33599. }
  33600. /**
  33601. * Returns the variable definitions as a shader string for the given shader stage.
  33602. *
  33603. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  33604. * @return {string} The variable code section.
  33605. */
  33606. getVars( shaderStage ) {
  33607. let snippet = '';
  33608. const vars = this.vars[ shaderStage ];
  33609. if ( vars !== undefined ) {
  33610. for ( const variable of vars ) {
  33611. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  33612. }
  33613. }
  33614. return snippet;
  33615. }
  33616. /**
  33617. * Returns the uniform definitions as a shader string for the given shader stage.
  33618. *
  33619. * @abstract
  33620. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  33621. * @return {string} The uniform code section.
  33622. */
  33623. getUniforms( /*shaderStage*/ ) {
  33624. console.warn( 'Abstract function.' );
  33625. }
  33626. /**
  33627. * Returns the native code definitions as a shader string for the given shader stage.
  33628. *
  33629. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  33630. * @return {string} The native code section.
  33631. */
  33632. getCodes( shaderStage ) {
  33633. const codes = this.codes[ shaderStage ];
  33634. let code = '';
  33635. if ( codes !== undefined ) {
  33636. for ( const nodeCode of codes ) {
  33637. code += nodeCode.code + '\n';
  33638. }
  33639. }
  33640. return code;
  33641. }
  33642. /**
  33643. * Returns the hash of this node builder.
  33644. *
  33645. * @return {string} The hash.
  33646. */
  33647. getHash() {
  33648. return this.vertexShader + this.fragmentShader + this.computeShader;
  33649. }
  33650. /**
  33651. * Sets the current shader stage.
  33652. *
  33653. * @param {?('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage to set.
  33654. */
  33655. setShaderStage( shaderStage ) {
  33656. this.shaderStage = shaderStage;
  33657. }
  33658. /**
  33659. * Returns the current shader stage.
  33660. *
  33661. * @return {?('vertex'|'fragment'|'compute'|'any')} The current shader stage.
  33662. */
  33663. getShaderStage() {
  33664. return this.shaderStage;
  33665. }
  33666. /**
  33667. * Sets the current build stage.
  33668. *
  33669. * @param {?('setup'|'analyze'|'generate')} buildStage - The build stage to set.
  33670. */
  33671. setBuildStage( buildStage ) {
  33672. this.buildStage = buildStage;
  33673. }
  33674. /**
  33675. * Returns the current build stage.
  33676. *
  33677. * @return {?('setup'|'analyze'|'generate')} The current build stage.
  33678. */
  33679. getBuildStage() {
  33680. return this.buildStage;
  33681. }
  33682. /**
  33683. * Controls the code build of the shader stages.
  33684. *
  33685. * @abstract
  33686. */
  33687. buildCode() {
  33688. console.warn( 'Abstract function.' );
  33689. }
  33690. /**
  33691. * Returns the current sub-build layer.
  33692. *
  33693. * @return {SubBuildNode} The current sub-build layers.
  33694. */
  33695. get subBuild() {
  33696. return this.subBuildLayers[ this.subBuildLayers.length - 1 ] || null;
  33697. }
  33698. /**
  33699. * Adds a sub-build layer to the node builder.
  33700. *
  33701. * @param {SubBuildNode} subBuild - The sub-build layer to add.
  33702. */
  33703. addSubBuild( subBuild ) {
  33704. this.subBuildLayers.push( subBuild );
  33705. }
  33706. /**
  33707. * Removes the last sub-build layer from the node builder.
  33708. *
  33709. * @return {SubBuildNode} The removed sub-build layer.
  33710. */
  33711. removeSubBuild() {
  33712. return this.subBuildLayers.pop();
  33713. }
  33714. /**
  33715. * Returns the closest sub-build layer for the given data.
  33716. *
  33717. * @param {Node|Set|Array} data - The data to get the closest sub-build layer from.
  33718. * @return {?string} The closest sub-build name or null if none found.
  33719. */
  33720. getClosestSubBuild( data ) {
  33721. let subBuilds;
  33722. if ( data && data.isNode ) {
  33723. if ( data.isShaderCallNodeInternal ) {
  33724. subBuilds = data.shaderNode.subBuilds;
  33725. } else if ( data.isStackNode ) {
  33726. subBuilds = [ data.subBuild ];
  33727. } else {
  33728. subBuilds = this.getDataFromNode( data, 'any' ).subBuilds;
  33729. }
  33730. } else if ( data instanceof Set ) {
  33731. subBuilds = [ ...data ];
  33732. } else {
  33733. subBuilds = data;
  33734. }
  33735. if ( ! subBuilds ) return null;
  33736. const subBuildLayers = this.subBuildLayers;
  33737. for ( let i = subBuilds.length - 1; i >= 0; i -- ) {
  33738. const subBuild = subBuilds[ i ];
  33739. if ( subBuildLayers.includes( subBuild ) ) {
  33740. return subBuild;
  33741. }
  33742. }
  33743. return null;
  33744. }
  33745. /**
  33746. * Returns the output node of a sub-build layer.
  33747. *
  33748. * @param {Node} node - The node to get the output from.
  33749. * @return {string} The output node name.
  33750. */
  33751. getSubBuildOutput( node ) {
  33752. return this.getSubBuildProperty( 'outputNode', node );
  33753. }
  33754. /**
  33755. * Returns the sub-build property name for the given property and node.
  33756. *
  33757. * @param {string} [property=''] - The property name.
  33758. * @param {?Node} [node=null] - The node to get the sub-build from.
  33759. * @return {string} The sub-build property name.
  33760. */
  33761. getSubBuildProperty( property = '', node = null ) {
  33762. let subBuild;
  33763. if ( node !== null ) {
  33764. subBuild = this.getClosestSubBuild( node );
  33765. } else {
  33766. subBuild = this.subBuildFn;
  33767. }
  33768. let result;
  33769. if ( subBuild ) {
  33770. result = property ? ( subBuild + '_' + property ) : subBuild;
  33771. } else {
  33772. result = property;
  33773. }
  33774. return result;
  33775. }
  33776. /**
  33777. * Central build method which controls the build for the given object.
  33778. *
  33779. * @return {NodeBuilder} A reference to this node builder.
  33780. */
  33781. build() {
  33782. const { object, material, renderer } = this;
  33783. if ( material !== null ) {
  33784. let nodeMaterial = renderer.library.fromMaterial( material );
  33785. if ( nodeMaterial === null ) {
  33786. console.error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  33787. nodeMaterial = new NodeMaterial();
  33788. }
  33789. nodeMaterial.build( this );
  33790. } else {
  33791. this.addFlow( 'compute', object );
  33792. }
  33793. // setup() -> stage 1: create possible new nodes and returns an output reference node
  33794. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  33795. // generate() -> stage 3: generate shader
  33796. for ( const buildStage of defaultBuildStages ) {
  33797. this.setBuildStage( buildStage );
  33798. if ( this.context.vertex && this.context.vertex.isNode ) {
  33799. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  33800. }
  33801. for ( const shaderStage of shaderStages ) {
  33802. this.setShaderStage( shaderStage );
  33803. const flowNodes = this.flowNodes[ shaderStage ];
  33804. for ( const node of flowNodes ) {
  33805. if ( buildStage === 'generate' ) {
  33806. this.flowNode( node );
  33807. } else {
  33808. node.build( this );
  33809. }
  33810. }
  33811. }
  33812. }
  33813. this.setBuildStage( null );
  33814. this.setShaderStage( null );
  33815. // stage 4: build code for a specific output
  33816. this.buildCode();
  33817. this.buildUpdateNodes();
  33818. return this;
  33819. }
  33820. /**
  33821. * Returns a uniform representation which is later used for UBO generation and rendering.
  33822. *
  33823. * @param {NodeUniform} uniformNode - The uniform node.
  33824. * @param {string} type - The requested type.
  33825. * @return {Uniform} The uniform.
  33826. */
  33827. getNodeUniform( uniformNode, type ) {
  33828. if ( type === 'float' || type === 'int' || type === 'uint' ) return new NumberNodeUniform( uniformNode );
  33829. if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) return new Vector2NodeUniform( uniformNode );
  33830. if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) return new Vector3NodeUniform( uniformNode );
  33831. if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) return new Vector4NodeUniform( uniformNode );
  33832. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  33833. if ( type === 'mat2' ) return new Matrix2NodeUniform( uniformNode );
  33834. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  33835. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  33836. throw new Error( `Uniform "${type}" not declared.` );
  33837. }
  33838. /**
  33839. * Formats the given shader snippet from a given type into another one. E.g.
  33840. * this method might be used to convert a simple float string `"1.0"` into a
  33841. * `vec3` representation: `"vec3<f32>( 1.0 )"`.
  33842. *
  33843. * @param {string} snippet - The shader snippet.
  33844. * @param {string} fromType - The source type.
  33845. * @param {string} toType - The target type.
  33846. * @return {string} The updated shader string.
  33847. */
  33848. format( snippet, fromType, toType ) {
  33849. fromType = this.getVectorType( fromType );
  33850. toType = this.getVectorType( toType );
  33851. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  33852. return snippet;
  33853. }
  33854. const fromTypeLength = this.getTypeLength( fromType );
  33855. const toTypeLength = this.getTypeLength( toType );
  33856. if ( fromTypeLength === 16 && toTypeLength === 9 ) {
  33857. return `${ this.getType( toType ) }( ${ snippet }[ 0 ].xyz, ${ snippet }[ 1 ].xyz, ${ snippet }[ 2 ].xyz )`;
  33858. }
  33859. if ( fromTypeLength === 9 && toTypeLength === 4 ) {
  33860. return `${ this.getType( toType ) }( ${ snippet }[ 0 ].xy, ${ snippet }[ 1 ].xy )`;
  33861. }
  33862. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  33863. // @TODO: ignore for now
  33864. return snippet;
  33865. }
  33866. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  33867. // @TODO: ignore for now
  33868. return snippet;
  33869. }
  33870. if ( fromTypeLength === toTypeLength ) {
  33871. return `${ this.getType( toType ) }( ${ snippet } )`;
  33872. }
  33873. if ( fromTypeLength > toTypeLength ) {
  33874. snippet = toType === 'bool' ? `all( ${ snippet } )` : `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`;
  33875. return this.format( snippet, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  33876. }
  33877. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  33878. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  33879. }
  33880. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  33881. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  33882. }
  33883. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  33884. // convert a number value to vector type, e.g:
  33885. // vec3( 1u ) -> vec3( float( 1u ) )
  33886. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  33887. }
  33888. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  33889. }
  33890. /**
  33891. * Returns a signature with the engine's current revision.
  33892. *
  33893. * @return {string} The signature.
  33894. */
  33895. getSignature() {
  33896. return `// Three.js r${ REVISION } - Node System\n`;
  33897. }
  33898. /**
  33899. * Prevents the node builder from being used as an iterable in TSL.Fn(), avoiding potential runtime errors.
  33900. */
  33901. *[ Symbol.iterator ]() { }
  33902. }
  33903. /**
  33904. * Management class for updating nodes. The module tracks metrics like
  33905. * the elapsed time, delta time, the render and frame ID to correctly
  33906. * call the node update methods {@link Node#updateBefore}, {@link Node#update}
  33907. * and {@link Node#updateAfter} depending on the node's configuration.
  33908. */
  33909. class NodeFrame {
  33910. /**
  33911. * Constructs a new node fame.
  33912. */
  33913. constructor() {
  33914. /**
  33915. * The elapsed time in seconds.
  33916. *
  33917. * @type {number}
  33918. * @default 0
  33919. */
  33920. this.time = 0;
  33921. /**
  33922. * The delta time in seconds.
  33923. *
  33924. * @type {number}
  33925. * @default 0
  33926. */
  33927. this.deltaTime = 0;
  33928. /**
  33929. * The frame ID.
  33930. *
  33931. * @type {number}
  33932. * @default 0
  33933. */
  33934. this.frameId = 0;
  33935. /**
  33936. * The render ID.
  33937. *
  33938. * @type {number}
  33939. * @default 0
  33940. */
  33941. this.renderId = 0;
  33942. /**
  33943. * Used to control the {@link Node#update} call.
  33944. *
  33945. * @type {WeakMap<Node, Object>}
  33946. */
  33947. this.updateMap = new WeakMap();
  33948. /**
  33949. * Used to control the {@link Node#updateBefore} call.
  33950. *
  33951. * @type {WeakMap<Node, Object>}
  33952. */
  33953. this.updateBeforeMap = new WeakMap();
  33954. /**
  33955. * Used to control the {@link Node#updateAfter} call.
  33956. *
  33957. * @type {WeakMap<Node, Object>}
  33958. */
  33959. this.updateAfterMap = new WeakMap();
  33960. /**
  33961. * A reference to the current renderer.
  33962. *
  33963. * @type {?Renderer}
  33964. * @default null
  33965. */
  33966. this.renderer = null;
  33967. /**
  33968. * A reference to the current material.
  33969. *
  33970. * @type {?Material}
  33971. * @default null
  33972. */
  33973. this.material = null;
  33974. /**
  33975. * A reference to the current camera.
  33976. *
  33977. * @type {?Camera}
  33978. * @default null
  33979. */
  33980. this.camera = null;
  33981. /**
  33982. * A reference to the current 3D object.
  33983. *
  33984. * @type {?Object3D}
  33985. * @default null
  33986. */
  33987. this.object = null;
  33988. /**
  33989. * A reference to the current scene.
  33990. *
  33991. * @type {?Scene}
  33992. * @default null
  33993. */
  33994. this.scene = null;
  33995. }
  33996. /**
  33997. * Returns a dictionary for a given node and update map which
  33998. * is used to correctly call node update methods per frame or render.
  33999. *
  34000. * @private
  34001. * @param {WeakMap<Node, Object>} referenceMap - The reference weak map.
  34002. * @param {Node} nodeRef - The reference to the current node.
  34003. * @return {Object<string,WeakMap>} The dictionary.
  34004. */
  34005. _getMaps( referenceMap, nodeRef ) {
  34006. let maps = referenceMap.get( nodeRef );
  34007. if ( maps === undefined ) {
  34008. maps = {
  34009. renderMap: new WeakMap(),
  34010. frameMap: new WeakMap()
  34011. };
  34012. referenceMap.set( nodeRef, maps );
  34013. }
  34014. return maps;
  34015. }
  34016. /**
  34017. * This method executes the {@link Node#updateBefore} for the given node.
  34018. * It makes sure {@link Node#updateBeforeType} is honored meaning the update
  34019. * is only executed once per frame, render or object depending on the update
  34020. * type.
  34021. *
  34022. * @param {Node} node - The node that should be updated.
  34023. */
  34024. updateBeforeNode( node ) {
  34025. const updateType = node.getUpdateBeforeType();
  34026. const reference = node.updateReference( this );
  34027. if ( updateType === NodeUpdateType.FRAME ) {
  34028. const { frameMap } = this._getMaps( this.updateBeforeMap, reference );
  34029. if ( frameMap.get( reference ) !== this.frameId ) {
  34030. if ( node.updateBefore( this ) !== false ) {
  34031. frameMap.set( reference, this.frameId );
  34032. }
  34033. }
  34034. } else if ( updateType === NodeUpdateType.RENDER ) {
  34035. const { renderMap } = this._getMaps( this.updateBeforeMap, reference );
  34036. if ( renderMap.get( reference ) !== this.renderId ) {
  34037. if ( node.updateBefore( this ) !== false ) {
  34038. renderMap.set( reference, this.renderId );
  34039. }
  34040. }
  34041. } else if ( updateType === NodeUpdateType.OBJECT ) {
  34042. node.updateBefore( this );
  34043. }
  34044. }
  34045. /**
  34046. * This method executes the {@link Node#updateAfter} for the given node.
  34047. * It makes sure {@link Node#updateAfterType} is honored meaning the update
  34048. * is only executed once per frame, render or object depending on the update
  34049. * type.
  34050. *
  34051. * @param {Node} node - The node that should be updated.
  34052. */
  34053. updateAfterNode( node ) {
  34054. const updateType = node.getUpdateAfterType();
  34055. const reference = node.updateReference( this );
  34056. if ( updateType === NodeUpdateType.FRAME ) {
  34057. const { frameMap } = this._getMaps( this.updateAfterMap, reference );
  34058. if ( frameMap.get( reference ) !== this.frameId ) {
  34059. if ( node.updateAfter( this ) !== false ) {
  34060. frameMap.set( reference, this.frameId );
  34061. }
  34062. }
  34063. } else if ( updateType === NodeUpdateType.RENDER ) {
  34064. const { renderMap } = this._getMaps( this.updateAfterMap, reference );
  34065. if ( renderMap.get( reference ) !== this.renderId ) {
  34066. if ( node.updateAfter( this ) !== false ) {
  34067. renderMap.set( reference, this.renderId );
  34068. }
  34069. }
  34070. } else if ( updateType === NodeUpdateType.OBJECT ) {
  34071. node.updateAfter( this );
  34072. }
  34073. }
  34074. /**
  34075. * This method executes the {@link Node#update} for the given node.
  34076. * It makes sure {@link Node#updateType} is honored meaning the update
  34077. * is only executed once per frame, render or object depending on the update
  34078. * type.
  34079. *
  34080. * @param {Node} node - The node that should be updated.
  34081. */
  34082. updateNode( node ) {
  34083. const updateType = node.getUpdateType();
  34084. const reference = node.updateReference( this );
  34085. if ( updateType === NodeUpdateType.FRAME ) {
  34086. const { frameMap } = this._getMaps( this.updateMap, reference );
  34087. if ( frameMap.get( reference ) !== this.frameId ) {
  34088. if ( node.update( this ) !== false ) {
  34089. frameMap.set( reference, this.frameId );
  34090. }
  34091. }
  34092. } else if ( updateType === NodeUpdateType.RENDER ) {
  34093. const { renderMap } = this._getMaps( this.updateMap, reference );
  34094. if ( renderMap.get( reference ) !== this.renderId ) {
  34095. if ( node.update( this ) !== false ) {
  34096. renderMap.set( reference, this.renderId );
  34097. }
  34098. }
  34099. } else if ( updateType === NodeUpdateType.OBJECT ) {
  34100. node.update( this );
  34101. }
  34102. }
  34103. /**
  34104. * Updates the internal state of the node frame. This method is
  34105. * called by the renderer in its internal animation loop.
  34106. */
  34107. update() {
  34108. this.frameId ++;
  34109. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  34110. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  34111. this.lastTime = performance.now();
  34112. this.time += this.deltaTime;
  34113. }
  34114. }
  34115. /**
  34116. * Describes the input of a {@link NodeFunction}.
  34117. */
  34118. class NodeFunctionInput {
  34119. /**
  34120. * Constructs a new node function input.
  34121. *
  34122. * @param {string} type - The input type.
  34123. * @param {string} name - The input name.
  34124. * @param {?number} [count=null] - If the input is an Array, count will be the length.
  34125. * @param {('in'|'out'|'inout')} [qualifier=''] - The parameter qualifier (only relevant for GLSL).
  34126. * @param {boolean} [isConst=false] - Whether the input uses a const qualifier or not (only relevant for GLSL).
  34127. */
  34128. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  34129. /**
  34130. * The input type.
  34131. *
  34132. * @type {string}
  34133. */
  34134. this.type = type;
  34135. /**
  34136. * The input name.
  34137. *
  34138. * @type {string}
  34139. */
  34140. this.name = name;
  34141. /**
  34142. * If the input is an Array, count will be the length.
  34143. *
  34144. * @type {?number}
  34145. * @default null
  34146. */
  34147. this.count = count;
  34148. /**
  34149. *The parameter qualifier (only relevant for GLSL).
  34150. *
  34151. * @type {('in'|'out'|'inout')}
  34152. * @default ''
  34153. */
  34154. this.qualifier = qualifier;
  34155. /**
  34156. * Whether the input uses a const qualifier or not (only relevant for GLSL).
  34157. *
  34158. * @type {boolean}
  34159. * @default false
  34160. */
  34161. this.isConst = isConst;
  34162. }
  34163. }
  34164. NodeFunctionInput.isNodeFunctionInput = true;
  34165. /**
  34166. * Module for representing directional lights as nodes.
  34167. *
  34168. * @augments AnalyticLightNode
  34169. */
  34170. class DirectionalLightNode extends AnalyticLightNode {
  34171. static get type() {
  34172. return 'DirectionalLightNode';
  34173. }
  34174. /**
  34175. * Constructs a new directional light node.
  34176. *
  34177. * @param {?DirectionalLight} [light=null] - The directional light source.
  34178. */
  34179. constructor( light = null ) {
  34180. super( light );
  34181. }
  34182. setupDirect() {
  34183. const lightColor = this.colorNode;
  34184. const lightDirection = lightTargetDirection( this.light );
  34185. return { lightDirection, lightColor };
  34186. }
  34187. }
  34188. const _matrix41 = /*@__PURE__*/ new Matrix4();
  34189. const _matrix42 = /*@__PURE__*/ new Matrix4();
  34190. let _ltcLib = null;
  34191. /**
  34192. * Module for representing rect area lights as nodes.
  34193. *
  34194. * @augments AnalyticLightNode
  34195. */
  34196. class RectAreaLightNode extends AnalyticLightNode {
  34197. static get type() {
  34198. return 'RectAreaLightNode';
  34199. }
  34200. /**
  34201. * Constructs a new rect area light node.
  34202. *
  34203. * @param {?RectAreaLight} [light=null] - The rect area light source.
  34204. */
  34205. constructor( light = null ) {
  34206. super( light );
  34207. /**
  34208. * Uniform node representing the half height of the are light.
  34209. *
  34210. * @type {UniformNode<vec3>}
  34211. */
  34212. this.halfHeight = uniform( new Vector3() ).setGroup( renderGroup );
  34213. /**
  34214. * Uniform node representing the half width of the are light.
  34215. *
  34216. * @type {UniformNode<vec3>}
  34217. */
  34218. this.halfWidth = uniform( new Vector3() ).setGroup( renderGroup );
  34219. /**
  34220. * The `updateType` is set to `NodeUpdateType.RENDER` since the light
  34221. * relies on `viewMatrix` which might vary per render call.
  34222. *
  34223. * @type {string}
  34224. * @default 'render'
  34225. */
  34226. this.updateType = NodeUpdateType.RENDER;
  34227. }
  34228. /**
  34229. * Overwritten to updated rect area light specific uniforms.
  34230. *
  34231. * @param {NodeFrame} frame - A reference to the current node frame.
  34232. */
  34233. update( frame ) {
  34234. super.update( frame );
  34235. const { light } = this;
  34236. const viewMatrix = frame.camera.matrixWorldInverse;
  34237. _matrix42.identity();
  34238. _matrix41.copy( light.matrixWorld );
  34239. _matrix41.premultiply( viewMatrix );
  34240. _matrix42.extractRotation( _matrix41 );
  34241. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  34242. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  34243. this.halfWidth.value.applyMatrix4( _matrix42 );
  34244. this.halfHeight.value.applyMatrix4( _matrix42 );
  34245. }
  34246. setupDirectRectArea( builder ) {
  34247. let ltc_1, ltc_2;
  34248. if ( builder.isAvailable( 'float32Filterable' ) ) {
  34249. ltc_1 = texture( _ltcLib.LTC_FLOAT_1 );
  34250. ltc_2 = texture( _ltcLib.LTC_FLOAT_2 );
  34251. } else {
  34252. ltc_1 = texture( _ltcLib.LTC_HALF_1 );
  34253. ltc_2 = texture( _ltcLib.LTC_HALF_2 );
  34254. }
  34255. const { colorNode, light } = this;
  34256. const lightPosition = lightViewPosition( light );
  34257. return {
  34258. lightColor: colorNode,
  34259. lightPosition,
  34260. halfWidth: this.halfWidth,
  34261. halfHeight: this.halfHeight,
  34262. ltc_1,
  34263. ltc_2
  34264. };
  34265. }
  34266. /**
  34267. * Used to configure the internal BRDF approximation texture data.
  34268. *
  34269. * @param {RectAreaLightTexturesLib} ltc - The BRDF approximation texture data.
  34270. */
  34271. static setLTC( ltc ) {
  34272. _ltcLib = ltc;
  34273. }
  34274. }
  34275. /**
  34276. * Module for representing spot lights as nodes.
  34277. *
  34278. * @augments AnalyticLightNode
  34279. */
  34280. class SpotLightNode extends AnalyticLightNode {
  34281. static get type() {
  34282. return 'SpotLightNode';
  34283. }
  34284. /**
  34285. * Constructs a new spot light node.
  34286. *
  34287. * @param {?SpotLight} [light=null] - The spot light source.
  34288. */
  34289. constructor( light = null ) {
  34290. super( light );
  34291. /**
  34292. * Uniform node representing the cone cosine.
  34293. *
  34294. * @type {UniformNode<float>}
  34295. */
  34296. this.coneCosNode = uniform( 0 ).setGroup( renderGroup );
  34297. /**
  34298. * Uniform node representing the penumbra cosine.
  34299. *
  34300. * @type {UniformNode<float>}
  34301. */
  34302. this.penumbraCosNode = uniform( 0 ).setGroup( renderGroup );
  34303. /**
  34304. * Uniform node representing the cutoff distance.
  34305. *
  34306. * @type {UniformNode<float>}
  34307. */
  34308. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  34309. /**
  34310. * Uniform node representing the decay exponent.
  34311. *
  34312. * @type {UniformNode<float>}
  34313. */
  34314. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  34315. /**
  34316. * Uniform node representing the light color.
  34317. *
  34318. * @type {UniformNode<Color>}
  34319. */
  34320. this.colorNode = uniform( this.color ).setGroup( renderGroup );
  34321. }
  34322. /**
  34323. * Overwritten to updated spot light specific uniforms.
  34324. *
  34325. * @param {NodeFrame} frame - A reference to the current node frame.
  34326. */
  34327. update( frame ) {
  34328. super.update( frame );
  34329. const { light } = this;
  34330. this.coneCosNode.value = Math.cos( light.angle );
  34331. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  34332. this.cutoffDistanceNode.value = light.distance;
  34333. this.decayExponentNode.value = light.decay;
  34334. }
  34335. /**
  34336. * Computes the spot attenuation for the given angle.
  34337. *
  34338. * @param {NodeBuilder} builder - The node builder.
  34339. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  34340. * @return {Node<float>} The spot attenuation.
  34341. */
  34342. getSpotAttenuation( builder, angleCosine ) {
  34343. const { coneCosNode, penumbraCosNode } = this;
  34344. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  34345. }
  34346. getLightCoord( builder ) {
  34347. const properties = builder.getNodeProperties( this );
  34348. let projectionUV = properties.projectionUV;
  34349. if ( projectionUV === undefined ) {
  34350. projectionUV = lightProjectionUV( this.light, builder.context.positionWorld );
  34351. properties.projectionUV = projectionUV;
  34352. }
  34353. return projectionUV;
  34354. }
  34355. setupDirect( builder ) {
  34356. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  34357. const lightVector = this.getLightVector( builder );
  34358. const lightDirection = lightVector.normalize();
  34359. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  34360. const spotAttenuation = this.getSpotAttenuation( builder, angleCos );
  34361. const lightDistance = lightVector.length();
  34362. const lightAttenuation = getDistanceAttenuation( {
  34363. lightDistance,
  34364. cutoffDistance: cutoffDistanceNode,
  34365. decayExponent: decayExponentNode
  34366. } );
  34367. let lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  34368. let projected, lightCoord;
  34369. if ( light.colorNode ) {
  34370. lightCoord = this.getLightCoord( builder );
  34371. projected = light.colorNode( lightCoord );
  34372. } else if ( light.map ) {
  34373. lightCoord = this.getLightCoord( builder );
  34374. projected = texture( light.map, lightCoord.xy ).onRenderUpdate( () => light.map );
  34375. }
  34376. if ( projected ) {
  34377. const inSpotLightMap = lightCoord.mul( 2. ).sub( 1. ).abs().lessThan( 1. ).all();
  34378. lightColor = inSpotLightMap.select( lightColor.mul( projected ), lightColor );
  34379. }
  34380. return { lightColor, lightDirection };
  34381. }
  34382. }
  34383. /**
  34384. * An IES version of the default spot light node.
  34385. *
  34386. * @augments SpotLightNode
  34387. */
  34388. class IESSpotLightNode extends SpotLightNode {
  34389. static get type() {
  34390. return 'IESSpotLightNode';
  34391. }
  34392. /**
  34393. * Overwrites the default implementation to compute an IES conform spot attenuation.
  34394. *
  34395. * @param {NodeBuilder} builder - The node builder.
  34396. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  34397. * @return {Node<float>} The spot attenuation.
  34398. */
  34399. getSpotAttenuation( builder, angleCosine ) {
  34400. const iesMap = this.light.iesMap;
  34401. let spotAttenuation = null;
  34402. if ( iesMap && iesMap.isTexture === true ) {
  34403. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  34404. spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r;
  34405. } else {
  34406. spotAttenuation = super.getSpotAttenuation( angleCosine );
  34407. }
  34408. return spotAttenuation;
  34409. }
  34410. }
  34411. const sdBox = /*@__PURE__*/ Fn( ( [ p, b ] ) => {
  34412. const d = p.abs().sub( b );
  34413. return length( max$1( d, 0.0 ) ).add( min$1( max$1( d.x, d.y ), 0.0 ) );
  34414. } );
  34415. /**
  34416. * An implementation of a projector light node.
  34417. *
  34418. * @augments SpotLightNode
  34419. */
  34420. class ProjectorLightNode extends SpotLightNode {
  34421. static get type() {
  34422. return 'ProjectorLightNode';
  34423. }
  34424. update( frame ) {
  34425. super.update( frame );
  34426. const light = this.light;
  34427. this.penumbraCosNode.value = Math.min( Math.cos( light.angle * ( 1 - light.penumbra ) ), .99999 );
  34428. if ( light.aspect === null ) {
  34429. let aspect = 1;
  34430. if ( light.map !== null ) {
  34431. aspect = light.map.width / light.map.height;
  34432. }
  34433. light.shadow.aspect = aspect;
  34434. } else {
  34435. light.shadow.aspect = light.aspect;
  34436. }
  34437. }
  34438. /**
  34439. * Overwrites the default implementation to compute projection attenuation.
  34440. *
  34441. * @param {NodeBuilder} builder - The node builder.
  34442. * @return {Node<float>} The spot attenuation.
  34443. */
  34444. getSpotAttenuation( builder ) {
  34445. const penumbraCos = this.penumbraCosNode;
  34446. const spotLightCoord = this.getLightCoord( builder );
  34447. const coord = spotLightCoord.xyz.div( spotLightCoord.w );
  34448. const boxDist = sdBox( coord.xy.sub( vec2( 0.5 ) ), vec2( 0.5 ) );
  34449. const angleFactor = div( -1, sub( 1.0, acos( penumbraCos ) ).sub( 1.0 ) );
  34450. const attenuation = saturate( boxDist.mul( -2 ).mul( angleFactor ) );
  34451. return attenuation;
  34452. }
  34453. }
  34454. /**
  34455. * Module for representing ambient lights as nodes.
  34456. *
  34457. * @augments AnalyticLightNode
  34458. */
  34459. class AmbientLightNode extends AnalyticLightNode {
  34460. static get type() {
  34461. return 'AmbientLightNode';
  34462. }
  34463. /**
  34464. * Constructs a new ambient light node.
  34465. *
  34466. * @param {?AmbientLight} [light=null] - The ambient light source.
  34467. */
  34468. constructor( light = null ) {
  34469. super( light );
  34470. }
  34471. setup( { context } ) {
  34472. context.irradiance.addAssign( this.colorNode );
  34473. }
  34474. }
  34475. /**
  34476. * Module for representing hemisphere lights as nodes.
  34477. *
  34478. * @augments AnalyticLightNode
  34479. */
  34480. class HemisphereLightNode extends AnalyticLightNode {
  34481. static get type() {
  34482. return 'HemisphereLightNode';
  34483. }
  34484. /**
  34485. * Constructs a new hemisphere light node.
  34486. *
  34487. * @param {?HemisphereLight} [light=null] - The hemisphere light source.
  34488. */
  34489. constructor( light = null ) {
  34490. super( light );
  34491. /**
  34492. * Uniform node representing the light's position.
  34493. *
  34494. * @type {UniformNode<vec3>}
  34495. */
  34496. this.lightPositionNode = lightPosition( light );
  34497. /**
  34498. * A node representing the light's direction.
  34499. *
  34500. * @type {Node<vec3>}
  34501. */
  34502. this.lightDirectionNode = this.lightPositionNode.normalize();
  34503. /**
  34504. * Uniform node representing the light's ground color.
  34505. *
  34506. * @type {UniformNode<vec3>}
  34507. */
  34508. this.groundColorNode = uniform( new Color() ).setGroup( renderGroup );
  34509. }
  34510. /**
  34511. * Overwritten to updated hemisphere light specific uniforms.
  34512. *
  34513. * @param {NodeFrame} frame - A reference to the current node frame.
  34514. */
  34515. update( frame ) {
  34516. const { light } = this;
  34517. super.update( frame );
  34518. this.lightPositionNode.object3d = light;
  34519. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  34520. }
  34521. setup( builder ) {
  34522. const { colorNode, groundColorNode, lightDirectionNode } = this;
  34523. const dotNL = normalWorld.dot( lightDirectionNode );
  34524. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  34525. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  34526. builder.context.irradiance.addAssign( irradiance );
  34527. }
  34528. }
  34529. /**
  34530. * Module for representing light probes as nodes.
  34531. *
  34532. * @augments AnalyticLightNode
  34533. */
  34534. class LightProbeNode extends AnalyticLightNode {
  34535. static get type() {
  34536. return 'LightProbeNode';
  34537. }
  34538. /**
  34539. * Constructs a new light probe node.
  34540. *
  34541. * @param {?LightProbe} [light=null] - The light probe.
  34542. */
  34543. constructor( light = null ) {
  34544. super( light );
  34545. const array = [];
  34546. for ( let i = 0; i < 9; i ++ ) array.push( new Vector3() );
  34547. /**
  34548. * Light probe represented as a uniform of spherical harmonics.
  34549. *
  34550. * @type {UniformArrayNode}
  34551. */
  34552. this.lightProbe = uniformArray( array );
  34553. }
  34554. /**
  34555. * Overwritten to updated light probe specific uniforms.
  34556. *
  34557. * @param {NodeFrame} frame - A reference to the current node frame.
  34558. */
  34559. update( frame ) {
  34560. const { light } = this;
  34561. super.update( frame );
  34562. //
  34563. for ( let i = 0; i < 9; i ++ ) {
  34564. this.lightProbe.array[ i ].copy( light.sh.coefficients[ i ] ).multiplyScalar( light.intensity );
  34565. }
  34566. }
  34567. setup( builder ) {
  34568. const irradiance = getShIrradianceAt( normalWorld, this.lightProbe );
  34569. builder.context.irradiance.addAssign( irradiance );
  34570. }
  34571. }
  34572. /**
  34573. * Base class for node parsers. A derived parser must be implemented
  34574. * for each supported native shader language.
  34575. */
  34576. class NodeParser {
  34577. /**
  34578. * The method parses the given native code an returns a node function.
  34579. *
  34580. * @abstract
  34581. * @param {string} source - The native shader code.
  34582. * @return {NodeFunction} A node function.
  34583. */
  34584. parseFunction( /*source*/ ) {
  34585. console.warn( 'Abstract function.' );
  34586. }
  34587. }
  34588. /**
  34589. * Base class for node functions. A derived module must be implemented
  34590. * for each supported native shader language. Similar to other `Node*` modules,
  34591. * this class is only relevant during the building process and not used
  34592. * in user-level code.
  34593. */
  34594. class NodeFunction {
  34595. /**
  34596. * Constructs a new node function.
  34597. *
  34598. * @param {string} type - The node type. This type is the return type of the node function.
  34599. * @param {Array<NodeFunctionInput>} inputs - The function's inputs.
  34600. * @param {string} [name=''] - The function's name.
  34601. * @param {string} [precision=''] - The precision qualifier.
  34602. */
  34603. constructor( type, inputs, name = '', precision = '' ) {
  34604. /**
  34605. * The node type. This type is the return type of the node function.
  34606. *
  34607. * @type {string}
  34608. */
  34609. this.type = type;
  34610. /**
  34611. * The function's inputs.
  34612. *
  34613. * @type {Array<NodeFunctionInput>}
  34614. */
  34615. this.inputs = inputs;
  34616. /**
  34617. * The name of the uniform.
  34618. *
  34619. * @type {string}
  34620. * @default ''
  34621. */
  34622. this.name = name;
  34623. /**
  34624. * The precision qualifier.
  34625. *
  34626. * @type {string}
  34627. * @default ''
  34628. */
  34629. this.precision = precision;
  34630. }
  34631. /**
  34632. * This method returns the native code of the node function.
  34633. *
  34634. * @abstract
  34635. * @param {string} name - The function's name.
  34636. * @return {string} A shader code.
  34637. */
  34638. getCode( /*name = this.name*/ ) {
  34639. console.warn( 'Abstract function.' );
  34640. }
  34641. }
  34642. NodeFunction.isNodeFunction = true;
  34643. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  34644. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  34645. const pragmaMain = '#pragma main';
  34646. const parse$1 = ( source ) => {
  34647. source = source.trim();
  34648. const pragmaMainIndex = source.indexOf( pragmaMain );
  34649. const mainCode = pragmaMainIndex !== -1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  34650. const declaration = mainCode.match( declarationRegexp$1 );
  34651. if ( declaration !== null && declaration.length === 5 ) {
  34652. // tokenizer
  34653. const inputsCode = declaration[ 4 ];
  34654. const propsMatches = [];
  34655. let nameMatch = null;
  34656. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  34657. propsMatches.push( nameMatch );
  34658. }
  34659. // parser
  34660. const inputs = [];
  34661. let i = 0;
  34662. while ( i < propsMatches.length ) {
  34663. const isConst = propsMatches[ i ][ 0 ] === 'const';
  34664. if ( isConst === true ) {
  34665. i ++;
  34666. }
  34667. let qualifier = propsMatches[ i ][ 0 ];
  34668. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  34669. i ++;
  34670. } else {
  34671. qualifier = '';
  34672. }
  34673. const type = propsMatches[ i ++ ][ 0 ];
  34674. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  34675. if ( Number.isNaN( count ) === false ) i ++;
  34676. else count = null;
  34677. const name = propsMatches[ i ++ ][ 0 ];
  34678. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  34679. }
  34680. //
  34681. const blockCode = mainCode.substring( declaration[ 0 ].length );
  34682. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  34683. const type = declaration[ 2 ];
  34684. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  34685. const headerCode = pragmaMainIndex !== -1 ? source.slice( 0, pragmaMainIndex ) : '';
  34686. return {
  34687. type,
  34688. inputs,
  34689. name,
  34690. precision,
  34691. inputsCode,
  34692. blockCode,
  34693. headerCode
  34694. };
  34695. } else {
  34696. throw new Error( 'FunctionNode: Function is not a GLSL code.' );
  34697. }
  34698. };
  34699. /**
  34700. * This class represents a GLSL node function.
  34701. *
  34702. * @augments NodeFunction
  34703. */
  34704. class GLSLNodeFunction extends NodeFunction {
  34705. /**
  34706. * Constructs a new GLSL node function.
  34707. *
  34708. * @param {string} source - The GLSL source.
  34709. */
  34710. constructor( source ) {
  34711. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  34712. super( type, inputs, name, precision );
  34713. this.inputsCode = inputsCode;
  34714. this.blockCode = blockCode;
  34715. this.headerCode = headerCode;
  34716. }
  34717. /**
  34718. * This method returns the GLSL code of the node function.
  34719. *
  34720. * @param {string} [name=this.name] - The function's name.
  34721. * @return {string} The shader code.
  34722. */
  34723. getCode( name = this.name ) {
  34724. let code;
  34725. const blockCode = this.blockCode;
  34726. if ( blockCode !== '' ) {
  34727. const { type, inputsCode, headerCode, precision } = this;
  34728. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  34729. if ( precision !== '' ) {
  34730. declarationCode = `${ precision } ${ declarationCode }`;
  34731. }
  34732. code = headerCode + declarationCode + blockCode;
  34733. } else {
  34734. // interface function
  34735. code = '';
  34736. }
  34737. return code;
  34738. }
  34739. }
  34740. /**
  34741. * A GLSL node parser.
  34742. *
  34743. * @augments NodeParser
  34744. */
  34745. class GLSLNodeParser extends NodeParser {
  34746. /**
  34747. * The method parses the given GLSL code an returns a node function.
  34748. *
  34749. * @param {string} source - The GLSL code.
  34750. * @return {GLSLNodeFunction} A node function.
  34751. */
  34752. parseFunction( source ) {
  34753. return new GLSLNodeFunction( source );
  34754. }
  34755. }
  34756. const _outputNodeMap = new WeakMap();
  34757. const _chainKeys$2 = [];
  34758. const _cacheKeyValues = [];
  34759. /**
  34760. * This renderer module manages node-related objects and is the
  34761. * primary interface between the renderer and the node system.
  34762. *
  34763. * @private
  34764. * @augments DataMap
  34765. */
  34766. class Nodes extends DataMap {
  34767. /**
  34768. * Constructs a new nodes management component.
  34769. *
  34770. * @param {Renderer} renderer - The renderer.
  34771. * @param {Backend} backend - The renderer's backend.
  34772. */
  34773. constructor( renderer, backend ) {
  34774. super();
  34775. /**
  34776. * The renderer.
  34777. *
  34778. * @type {Renderer}
  34779. */
  34780. this.renderer = renderer;
  34781. /**
  34782. * The renderer's backend.
  34783. *
  34784. * @type {Backend}
  34785. */
  34786. this.backend = backend;
  34787. /**
  34788. * The node frame.
  34789. *
  34790. * @type {Renderer}
  34791. */
  34792. this.nodeFrame = new NodeFrame();
  34793. /**
  34794. * A cache for managing node builder states.
  34795. *
  34796. * @type {Map<number,NodeBuilderState>}
  34797. */
  34798. this.nodeBuilderCache = new Map();
  34799. /**
  34800. * A cache for managing data cache key data.
  34801. *
  34802. * @type {ChainMap}
  34803. */
  34804. this.callHashCache = new ChainMap();
  34805. /**
  34806. * A cache for managing node uniforms group data.
  34807. *
  34808. * @type {ChainMap}
  34809. */
  34810. this.groupsData = new ChainMap();
  34811. /**
  34812. * A cache for managing node objects of
  34813. * scene properties like fog or environments.
  34814. *
  34815. * @type {Object<string,WeakMap>}
  34816. */
  34817. this.cacheLib = {};
  34818. }
  34819. /**
  34820. * Returns `true` if the given node uniforms group must be updated or not.
  34821. *
  34822. * @param {NodeUniformsGroup} nodeUniformsGroup - The node uniforms group.
  34823. * @return {boolean} Whether the node uniforms group requires an update or not.
  34824. */
  34825. updateGroup( nodeUniformsGroup ) {
  34826. const groupNode = nodeUniformsGroup.groupNode;
  34827. const name = groupNode.name;
  34828. // objectGroup is always updated
  34829. if ( name === objectGroup.name ) return true;
  34830. // renderGroup is updated once per render/compute call
  34831. if ( name === renderGroup.name ) {
  34832. const uniformsGroupData = this.get( nodeUniformsGroup );
  34833. const renderId = this.nodeFrame.renderId;
  34834. if ( uniformsGroupData.renderId !== renderId ) {
  34835. uniformsGroupData.renderId = renderId;
  34836. return true;
  34837. }
  34838. return false;
  34839. }
  34840. // frameGroup is updated once per frame
  34841. if ( name === frameGroup.name ) {
  34842. const uniformsGroupData = this.get( nodeUniformsGroup );
  34843. const frameId = this.nodeFrame.frameId;
  34844. if ( uniformsGroupData.frameId !== frameId ) {
  34845. uniformsGroupData.frameId = frameId;
  34846. return true;
  34847. }
  34848. return false;
  34849. }
  34850. // other groups are updated just when groupNode.needsUpdate is true
  34851. _chainKeys$2[ 0 ] = groupNode;
  34852. _chainKeys$2[ 1 ] = nodeUniformsGroup;
  34853. let groupData = this.groupsData.get( _chainKeys$2 );
  34854. if ( groupData === undefined ) this.groupsData.set( _chainKeys$2, groupData = {} );
  34855. _chainKeys$2.length = 0;
  34856. if ( groupData.version !== groupNode.version ) {
  34857. groupData.version = groupNode.version;
  34858. return true;
  34859. }
  34860. return false;
  34861. }
  34862. /**
  34863. * Returns the cache key for the given render object.
  34864. *
  34865. * @param {RenderObject} renderObject - The render object.
  34866. * @return {number} The cache key.
  34867. */
  34868. getForRenderCacheKey( renderObject ) {
  34869. return renderObject.initialCacheKey;
  34870. }
  34871. /**
  34872. * Returns a node builder state for the given render object.
  34873. *
  34874. * @param {RenderObject} renderObject - The render object.
  34875. * @return {NodeBuilderState} The node builder state.
  34876. */
  34877. getForRender( renderObject ) {
  34878. const renderObjectData = this.get( renderObject );
  34879. let nodeBuilderState = renderObjectData.nodeBuilderState;
  34880. if ( nodeBuilderState === undefined ) {
  34881. const { nodeBuilderCache } = this;
  34882. const cacheKey = this.getForRenderCacheKey( renderObject );
  34883. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  34884. if ( nodeBuilderState === undefined ) {
  34885. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  34886. nodeBuilder.scene = renderObject.scene;
  34887. nodeBuilder.material = renderObject.material;
  34888. nodeBuilder.camera = renderObject.camera;
  34889. nodeBuilder.context.material = renderObject.material;
  34890. nodeBuilder.lightsNode = renderObject.lightsNode;
  34891. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  34892. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  34893. nodeBuilder.clippingContext = renderObject.clippingContext;
  34894. if ( this.renderer.getOutputRenderTarget() ? this.renderer.getOutputRenderTarget().multiview : false ) {
  34895. nodeBuilder.enableMultiview();
  34896. }
  34897. nodeBuilder.build();
  34898. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  34899. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  34900. }
  34901. nodeBuilderState.usedTimes ++;
  34902. renderObjectData.nodeBuilderState = nodeBuilderState;
  34903. }
  34904. return nodeBuilderState;
  34905. }
  34906. /**
  34907. * Deletes the given object from the internal data map
  34908. *
  34909. * @param {any} object - The object to delete.
  34910. * @return {?Object} The deleted dictionary.
  34911. */
  34912. delete( object ) {
  34913. if ( object.isRenderObject ) {
  34914. const nodeBuilderState = this.get( object ).nodeBuilderState;
  34915. nodeBuilderState.usedTimes --;
  34916. if ( nodeBuilderState.usedTimes === 0 ) {
  34917. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  34918. }
  34919. }
  34920. return super.delete( object );
  34921. }
  34922. /**
  34923. * Returns a node builder state for the given compute node.
  34924. *
  34925. * @param {Node} computeNode - The compute node.
  34926. * @return {NodeBuilderState} The node builder state.
  34927. */
  34928. getForCompute( computeNode ) {
  34929. const computeData = this.get( computeNode );
  34930. let nodeBuilderState = computeData.nodeBuilderState;
  34931. if ( nodeBuilderState === undefined ) {
  34932. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  34933. nodeBuilder.build();
  34934. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  34935. computeData.nodeBuilderState = nodeBuilderState;
  34936. }
  34937. return nodeBuilderState;
  34938. }
  34939. /**
  34940. * Creates a node builder state for the given node builder.
  34941. *
  34942. * @private
  34943. * @param {NodeBuilder} nodeBuilder - The node builder.
  34944. * @return {NodeBuilderState} The node builder state.
  34945. */
  34946. _createNodeBuilderState( nodeBuilder ) {
  34947. return new NodeBuilderState(
  34948. nodeBuilder.vertexShader,
  34949. nodeBuilder.fragmentShader,
  34950. nodeBuilder.computeShader,
  34951. nodeBuilder.getAttributesArray(),
  34952. nodeBuilder.getBindings(),
  34953. nodeBuilder.updateNodes,
  34954. nodeBuilder.updateBeforeNodes,
  34955. nodeBuilder.updateAfterNodes,
  34956. nodeBuilder.observer,
  34957. nodeBuilder.transforms
  34958. );
  34959. }
  34960. /**
  34961. * Returns an environment node for the current configured
  34962. * scene environment.
  34963. *
  34964. * @param {Scene} scene - The scene.
  34965. * @return {Node} A node representing the current scene environment.
  34966. */
  34967. getEnvironmentNode( scene ) {
  34968. this.updateEnvironment( scene );
  34969. let environmentNode = null;
  34970. if ( scene.environmentNode && scene.environmentNode.isNode ) {
  34971. environmentNode = scene.environmentNode;
  34972. } else {
  34973. const sceneData = this.get( scene );
  34974. if ( sceneData.environmentNode ) {
  34975. environmentNode = sceneData.environmentNode;
  34976. }
  34977. }
  34978. return environmentNode;
  34979. }
  34980. /**
  34981. * Returns a background node for the current configured
  34982. * scene background.
  34983. *
  34984. * @param {Scene} scene - The scene.
  34985. * @return {Node} A node representing the current scene background.
  34986. */
  34987. getBackgroundNode( scene ) {
  34988. this.updateBackground( scene );
  34989. let backgroundNode = null;
  34990. if ( scene.backgroundNode && scene.backgroundNode.isNode ) {
  34991. backgroundNode = scene.backgroundNode;
  34992. } else {
  34993. const sceneData = this.get( scene );
  34994. if ( sceneData.backgroundNode ) {
  34995. backgroundNode = sceneData.backgroundNode;
  34996. }
  34997. }
  34998. return backgroundNode;
  34999. }
  35000. /**
  35001. * Returns a fog node for the current configured scene fog.
  35002. *
  35003. * @param {Scene} scene - The scene.
  35004. * @return {Node} A node representing the current scene fog.
  35005. */
  35006. getFogNode( scene ) {
  35007. this.updateFog( scene );
  35008. return scene.fogNode || this.get( scene ).fogNode || null;
  35009. }
  35010. /**
  35011. * Returns a cache key for the given scene and lights node.
  35012. * This key is used by `RenderObject` as a part of the dynamic
  35013. * cache key (a key that must be checked every time the render
  35014. * objects is drawn).
  35015. *
  35016. * @param {Scene} scene - The scene.
  35017. * @param {LightsNode} lightsNode - The lights node.
  35018. * @return {number} The cache key.
  35019. */
  35020. getCacheKey( scene, lightsNode ) {
  35021. _chainKeys$2[ 0 ] = scene;
  35022. _chainKeys$2[ 1 ] = lightsNode;
  35023. const callId = this.renderer.info.calls;
  35024. const cacheKeyData = this.callHashCache.get( _chainKeys$2 ) || {};
  35025. if ( cacheKeyData.callId !== callId ) {
  35026. const environmentNode = this.getEnvironmentNode( scene );
  35027. const fogNode = this.getFogNode( scene );
  35028. if ( lightsNode ) _cacheKeyValues.push( lightsNode.getCacheKey( true ) );
  35029. if ( environmentNode ) _cacheKeyValues.push( environmentNode.getCacheKey() );
  35030. if ( fogNode ) _cacheKeyValues.push( fogNode.getCacheKey() );
  35031. _cacheKeyValues.push( this.renderer.getOutputRenderTarget() && this.renderer.getOutputRenderTarget().multiview ? 1 : 0 );
  35032. _cacheKeyValues.push( this.renderer.shadowMap.enabled ? 1 : 0 );
  35033. cacheKeyData.callId = callId;
  35034. cacheKeyData.cacheKey = hashArray( _cacheKeyValues );
  35035. this.callHashCache.set( _chainKeys$2, cacheKeyData );
  35036. _cacheKeyValues.length = 0;
  35037. }
  35038. _chainKeys$2.length = 0;
  35039. return cacheKeyData.cacheKey;
  35040. }
  35041. /**
  35042. * A boolean that indicates whether tone mapping should be enabled
  35043. * or not.
  35044. *
  35045. * @type {boolean}
  35046. */
  35047. get isToneMappingState() {
  35048. return this.renderer.getRenderTarget() ? false : true;
  35049. }
  35050. /**
  35051. * If a scene background is configured, this method makes sure to
  35052. * represent the background with a corresponding node-based implementation.
  35053. *
  35054. * @param {Scene} scene - The scene.
  35055. */
  35056. updateBackground( scene ) {
  35057. const sceneData = this.get( scene );
  35058. const background = scene.background;
  35059. if ( background ) {
  35060. const forceUpdate = ( scene.backgroundBlurriness === 0 && sceneData.backgroundBlurriness > 0 ) || ( scene.backgroundBlurriness > 0 && sceneData.backgroundBlurriness === 0 );
  35061. if ( sceneData.background !== background || forceUpdate ) {
  35062. const backgroundNode = this.getCacheNode( 'background', background, () => {
  35063. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping || background.mapping === CubeUVReflectionMapping ) ) {
  35064. if ( scene.backgroundBlurriness > 0 || background.mapping === CubeUVReflectionMapping ) {
  35065. return pmremTexture( background );
  35066. } else {
  35067. let envMap;
  35068. if ( background.isCubeTexture === true ) {
  35069. envMap = cubeTexture( background );
  35070. } else {
  35071. envMap = texture( background );
  35072. }
  35073. return cubeMapNode( envMap );
  35074. }
  35075. } else if ( background.isTexture === true ) {
  35076. return texture( background, screenUV.flipY() ).setUpdateMatrix( true );
  35077. } else if ( background.isColor !== true ) {
  35078. console.error( 'WebGPUNodes: Unsupported background configuration.', background );
  35079. }
  35080. }, forceUpdate );
  35081. sceneData.backgroundNode = backgroundNode;
  35082. sceneData.background = background;
  35083. sceneData.backgroundBlurriness = scene.backgroundBlurriness;
  35084. }
  35085. } else if ( sceneData.backgroundNode ) {
  35086. delete sceneData.backgroundNode;
  35087. delete sceneData.background;
  35088. }
  35089. }
  35090. /**
  35091. * This method is part of the caching of nodes which are used to represents the
  35092. * scene's background, fog or environment.
  35093. *
  35094. * @param {string} type - The type of object to cache.
  35095. * @param {Object} object - The object.
  35096. * @param {Function} callback - A callback that produces a node representation for the given object.
  35097. * @param {boolean} [forceUpdate=false] - Whether an update should be enforced or not.
  35098. * @return {Node} The node representation.
  35099. */
  35100. getCacheNode( type, object, callback, forceUpdate = false ) {
  35101. const nodeCache = this.cacheLib[ type ] || ( this.cacheLib[ type ] = new WeakMap() );
  35102. let node = nodeCache.get( object );
  35103. if ( node === undefined || forceUpdate ) {
  35104. node = callback();
  35105. nodeCache.set( object, node );
  35106. }
  35107. return node;
  35108. }
  35109. /**
  35110. * If a scene fog is configured, this method makes sure to
  35111. * represent the fog with a corresponding node-based implementation.
  35112. *
  35113. * @param {Scene} scene - The scene.
  35114. */
  35115. updateFog( scene ) {
  35116. const sceneData = this.get( scene );
  35117. const sceneFog = scene.fog;
  35118. if ( sceneFog ) {
  35119. if ( sceneData.fog !== sceneFog ) {
  35120. const fogNode = this.getCacheNode( 'fog', sceneFog, () => {
  35121. if ( sceneFog.isFogExp2 ) {
  35122. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  35123. const density = reference( 'density', 'float', sceneFog ).setGroup( renderGroup );
  35124. return fog( color, densityFogFactor( density ) );
  35125. } else if ( sceneFog.isFog ) {
  35126. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  35127. const near = reference( 'near', 'float', sceneFog ).setGroup( renderGroup );
  35128. const far = reference( 'far', 'float', sceneFog ).setGroup( renderGroup );
  35129. return fog( color, rangeFogFactor( near, far ) );
  35130. } else {
  35131. console.error( 'THREE.Renderer: Unsupported fog configuration.', sceneFog );
  35132. }
  35133. } );
  35134. sceneData.fogNode = fogNode;
  35135. sceneData.fog = sceneFog;
  35136. }
  35137. } else {
  35138. delete sceneData.fogNode;
  35139. delete sceneData.fog;
  35140. }
  35141. }
  35142. /**
  35143. * If a scene environment is configured, this method makes sure to
  35144. * represent the environment with a corresponding node-based implementation.
  35145. *
  35146. * @param {Scene} scene - The scene.
  35147. */
  35148. updateEnvironment( scene ) {
  35149. const sceneData = this.get( scene );
  35150. const environment = scene.environment;
  35151. if ( environment ) {
  35152. if ( sceneData.environment !== environment ) {
  35153. const environmentNode = this.getCacheNode( 'environment', environment, () => {
  35154. if ( environment.isCubeTexture === true ) {
  35155. return cubeTexture( environment );
  35156. } else if ( environment.isTexture === true ) {
  35157. return texture( environment );
  35158. } else {
  35159. console.error( 'Nodes: Unsupported environment configuration.', environment );
  35160. }
  35161. } );
  35162. sceneData.environmentNode = environmentNode;
  35163. sceneData.environment = environment;
  35164. }
  35165. } else if ( sceneData.environmentNode ) {
  35166. delete sceneData.environmentNode;
  35167. delete sceneData.environment;
  35168. }
  35169. }
  35170. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  35171. const nodeFrame = this.nodeFrame;
  35172. nodeFrame.renderer = renderer;
  35173. nodeFrame.scene = scene;
  35174. nodeFrame.object = object;
  35175. nodeFrame.camera = camera;
  35176. nodeFrame.material = material;
  35177. return nodeFrame;
  35178. }
  35179. getNodeFrameForRender( renderObject ) {
  35180. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  35181. }
  35182. /**
  35183. * Returns the current output cache key.
  35184. *
  35185. * @return {string} The output cache key.
  35186. */
  35187. getOutputCacheKey() {
  35188. const renderer = this.renderer;
  35189. return renderer.toneMapping + ',' + renderer.currentColorSpace + ',' + renderer.xr.isPresenting;
  35190. }
  35191. /**
  35192. * Checks if the output configuration (tone mapping and color space) for
  35193. * the given target has changed.
  35194. *
  35195. * @param {Texture} outputTarget - The output target.
  35196. * @return {boolean} Whether the output configuration has changed or not.
  35197. */
  35198. hasOutputChange( outputTarget ) {
  35199. const cacheKey = _outputNodeMap.get( outputTarget );
  35200. return cacheKey !== this.getOutputCacheKey();
  35201. }
  35202. /**
  35203. * Returns a node that represents the output configuration (tone mapping and
  35204. * color space) for the current target.
  35205. *
  35206. * @param {Texture} outputTarget - The output target.
  35207. * @return {Node} The output node.
  35208. */
  35209. getOutputNode( outputTarget ) {
  35210. const renderer = this.renderer;
  35211. const cacheKey = this.getOutputCacheKey();
  35212. const output = outputTarget.isArrayTexture ?
  35213. texture3D( outputTarget, vec3( screenUV, builtin( 'gl_ViewID_OVR' ) ) ).renderOutput( renderer.toneMapping, renderer.currentColorSpace ) :
  35214. texture( outputTarget, screenUV ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  35215. _outputNodeMap.set( outputTarget, cacheKey );
  35216. return output;
  35217. }
  35218. /**
  35219. * Triggers the call of `updateBefore()` methods
  35220. * for all nodes of the given render object.
  35221. *
  35222. * @param {RenderObject} renderObject - The render object.
  35223. */
  35224. updateBefore( renderObject ) {
  35225. const nodeBuilder = renderObject.getNodeBuilderState();
  35226. for ( const node of nodeBuilder.updateBeforeNodes ) {
  35227. // update frame state for each node
  35228. this.getNodeFrameForRender( renderObject ).updateBeforeNode( node );
  35229. }
  35230. }
  35231. /**
  35232. * Triggers the call of `updateAfter()` methods
  35233. * for all nodes of the given render object.
  35234. *
  35235. * @param {RenderObject} renderObject - The render object.
  35236. */
  35237. updateAfter( renderObject ) {
  35238. const nodeBuilder = renderObject.getNodeBuilderState();
  35239. for ( const node of nodeBuilder.updateAfterNodes ) {
  35240. // update frame state for each node
  35241. this.getNodeFrameForRender( renderObject ).updateAfterNode( node );
  35242. }
  35243. }
  35244. /**
  35245. * Triggers the call of `update()` methods
  35246. * for all nodes of the given compute node.
  35247. *
  35248. * @param {Node} computeNode - The compute node.
  35249. */
  35250. updateForCompute( computeNode ) {
  35251. const nodeFrame = this.getNodeFrame();
  35252. const nodeBuilder = this.getForCompute( computeNode );
  35253. for ( const node of nodeBuilder.updateNodes ) {
  35254. nodeFrame.updateNode( node );
  35255. }
  35256. }
  35257. /**
  35258. * Triggers the call of `update()` methods
  35259. * for all nodes of the given compute node.
  35260. *
  35261. * @param {RenderObject} renderObject - The render object.
  35262. */
  35263. updateForRender( renderObject ) {
  35264. const nodeFrame = this.getNodeFrameForRender( renderObject );
  35265. const nodeBuilder = renderObject.getNodeBuilderState();
  35266. for ( const node of nodeBuilder.updateNodes ) {
  35267. nodeFrame.updateNode( node );
  35268. }
  35269. }
  35270. /**
  35271. * Returns `true` if the given render object requires a refresh.
  35272. *
  35273. * @param {RenderObject} renderObject - The render object.
  35274. * @return {boolean} Whether the given render object requires a refresh or not.
  35275. */
  35276. needsRefresh( renderObject ) {
  35277. const nodeFrame = this.getNodeFrameForRender( renderObject );
  35278. const monitor = renderObject.getMonitor();
  35279. return monitor.needsRefresh( renderObject, nodeFrame );
  35280. }
  35281. /**
  35282. * Frees the internal resources.
  35283. */
  35284. dispose() {
  35285. super.dispose();
  35286. this.nodeFrame = new NodeFrame();
  35287. this.nodeBuilderCache = new Map();
  35288. this.cacheLib = {};
  35289. }
  35290. }
  35291. const _plane = /*@__PURE__*/ new Plane();
  35292. /**
  35293. * Represents the state that is used to perform clipping via clipping planes.
  35294. * There is a default clipping context for each render context. When the
  35295. * scene holds instances of `ClippingGroup`, there will be a context for each
  35296. * group.
  35297. *
  35298. * @private
  35299. */
  35300. class ClippingContext {
  35301. /**
  35302. * Constructs a new clipping context.
  35303. *
  35304. * @param {?ClippingContext} [parentContext=null] - A reference to the parent clipping context.
  35305. */
  35306. constructor( parentContext = null ) {
  35307. /**
  35308. * The clipping context's version.
  35309. *
  35310. * @type {number}
  35311. * @readonly
  35312. */
  35313. this.version = 0;
  35314. /**
  35315. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  35316. *
  35317. * @type {?boolean}
  35318. * @default null
  35319. */
  35320. this.clipIntersection = null;
  35321. /**
  35322. * The clipping context's cache key.
  35323. *
  35324. * @type {string}
  35325. */
  35326. this.cacheKey = '';
  35327. /**
  35328. * Whether the shadow pass is active or not.
  35329. *
  35330. * @type {boolean}
  35331. * @default false
  35332. */
  35333. this.shadowPass = false;
  35334. /**
  35335. * The view normal matrix.
  35336. *
  35337. * @type {Matrix3}
  35338. */
  35339. this.viewNormalMatrix = new Matrix3();
  35340. /**
  35341. * Internal cache for maintaining clipping contexts.
  35342. *
  35343. * @type {WeakMap<ClippingGroup,ClippingContext>}
  35344. */
  35345. this.clippingGroupContexts = new WeakMap();
  35346. /**
  35347. * The intersection planes.
  35348. *
  35349. * @type {Array<Vector4>}
  35350. */
  35351. this.intersectionPlanes = [];
  35352. /**
  35353. * The intersection planes.
  35354. *
  35355. * @type {Array<Vector4>}
  35356. */
  35357. this.unionPlanes = [];
  35358. /**
  35359. * The version of the clipping context's parent context.
  35360. *
  35361. * @type {?number}
  35362. * @readonly
  35363. */
  35364. this.parentVersion = null;
  35365. if ( parentContext !== null ) {
  35366. this.viewNormalMatrix = parentContext.viewNormalMatrix;
  35367. this.clippingGroupContexts = parentContext.clippingGroupContexts;
  35368. this.shadowPass = parentContext.shadowPass;
  35369. this.viewMatrix = parentContext.viewMatrix;
  35370. }
  35371. }
  35372. /**
  35373. * Projects the given source clipping planes and writes the result into the
  35374. * destination array.
  35375. *
  35376. * @param {Array<Plane>} source - The source clipping planes.
  35377. * @param {Array<Vector4>} destination - The destination.
  35378. * @param {number} offset - The offset.
  35379. */
  35380. projectPlanes( source, destination, offset ) {
  35381. const l = source.length;
  35382. for ( let i = 0; i < l; i ++ ) {
  35383. _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, this.viewNormalMatrix );
  35384. const v = destination[ offset + i ];
  35385. const normal = _plane.normal;
  35386. v.x = - normal.x;
  35387. v.y = - normal.y;
  35388. v.z = - normal.z;
  35389. v.w = _plane.constant;
  35390. }
  35391. }
  35392. /**
  35393. * Updates the root clipping context of a scene.
  35394. *
  35395. * @param {Scene} scene - The scene.
  35396. * @param {Camera} camera - The camera that is used to render the scene.
  35397. */
  35398. updateGlobal( scene, camera ) {
  35399. this.shadowPass = ( scene.overrideMaterial !== null && scene.overrideMaterial.isShadowPassMaterial );
  35400. this.viewMatrix = camera.matrixWorldInverse;
  35401. this.viewNormalMatrix.getNormalMatrix( this.viewMatrix );
  35402. }
  35403. /**
  35404. * Updates the clipping context.
  35405. *
  35406. * @param {ClippingContext} parentContext - The parent context.
  35407. * @param {ClippingGroup} clippingGroup - The clipping group this context belongs to.
  35408. */
  35409. update( parentContext, clippingGroup ) {
  35410. let update = false;
  35411. if ( parentContext.version !== this.parentVersion ) {
  35412. this.intersectionPlanes = Array.from( parentContext.intersectionPlanes );
  35413. this.unionPlanes = Array.from( parentContext.unionPlanes );
  35414. this.parentVersion = parentContext.version;
  35415. }
  35416. if ( this.clipIntersection !== clippingGroup.clipIntersection ) {
  35417. this.clipIntersection = clippingGroup.clipIntersection;
  35418. if ( this.clipIntersection ) {
  35419. this.unionPlanes.length = parentContext.unionPlanes.length;
  35420. } else {
  35421. this.intersectionPlanes.length = parentContext.intersectionPlanes.length;
  35422. }
  35423. }
  35424. const srcClippingPlanes = clippingGroup.clippingPlanes;
  35425. const l = srcClippingPlanes.length;
  35426. let dstClippingPlanes;
  35427. let offset;
  35428. if ( this.clipIntersection ) {
  35429. dstClippingPlanes = this.intersectionPlanes;
  35430. offset = parentContext.intersectionPlanes.length;
  35431. } else {
  35432. dstClippingPlanes = this.unionPlanes;
  35433. offset = parentContext.unionPlanes.length;
  35434. }
  35435. if ( dstClippingPlanes.length !== offset + l ) {
  35436. dstClippingPlanes.length = offset + l;
  35437. for ( let i = 0; i < l; i ++ ) {
  35438. dstClippingPlanes[ offset + i ] = new Vector4();
  35439. }
  35440. update = true;
  35441. }
  35442. this.projectPlanes( srcClippingPlanes, dstClippingPlanes, offset );
  35443. if ( update ) {
  35444. this.version ++;
  35445. this.cacheKey = `${ this.intersectionPlanes.length }:${ this.unionPlanes.length }`;
  35446. }
  35447. }
  35448. /**
  35449. * Returns a clipping context for the given clipping group.
  35450. *
  35451. * @param {ClippingGroup} clippingGroup - The clipping group.
  35452. * @return {ClippingContext} The clipping context.
  35453. */
  35454. getGroupContext( clippingGroup ) {
  35455. if ( this.shadowPass && ! clippingGroup.clipShadows ) return this;
  35456. let context = this.clippingGroupContexts.get( clippingGroup );
  35457. if ( context === undefined ) {
  35458. context = new ClippingContext( this );
  35459. this.clippingGroupContexts.set( clippingGroup, context );
  35460. }
  35461. context.update( this, clippingGroup );
  35462. return context;
  35463. }
  35464. /**
  35465. * The count of union clipping planes.
  35466. *
  35467. * @type {number}
  35468. * @readonly
  35469. */
  35470. get unionClippingCount() {
  35471. return this.unionPlanes.length;
  35472. }
  35473. }
  35474. /**
  35475. * This module is used to represent render bundles inside the renderer
  35476. * for further processing.
  35477. *
  35478. * @private
  35479. */
  35480. class RenderBundle {
  35481. /**
  35482. * Constructs a new bundle group.
  35483. *
  35484. * @param {BundleGroup} bundleGroup - The bundle group.
  35485. * @param {Camera} camera - The camera the bundle group is rendered with.
  35486. */
  35487. constructor( bundleGroup, camera ) {
  35488. this.bundleGroup = bundleGroup;
  35489. this.camera = camera;
  35490. }
  35491. }
  35492. const _chainKeys$1 = [];
  35493. /**
  35494. * This renderer module manages render bundles.
  35495. *
  35496. * @private
  35497. */
  35498. class RenderBundles {
  35499. /**
  35500. * Constructs a new render bundle management component.
  35501. */
  35502. constructor() {
  35503. /**
  35504. * A chain map for maintaining the render bundles.
  35505. *
  35506. * @type {ChainMap}
  35507. */
  35508. this.bundles = new ChainMap();
  35509. }
  35510. /**
  35511. * Returns a render bundle for the given bundle group and camera.
  35512. *
  35513. * @param {BundleGroup} bundleGroup - The bundle group.
  35514. * @param {Camera} camera - The camera the bundle group is rendered with.
  35515. * @return {RenderBundle} The render bundle.
  35516. */
  35517. get( bundleGroup, camera ) {
  35518. const bundles = this.bundles;
  35519. _chainKeys$1[ 0 ] = bundleGroup;
  35520. _chainKeys$1[ 1 ] = camera;
  35521. let bundle = bundles.get( _chainKeys$1 );
  35522. if ( bundle === undefined ) {
  35523. bundle = new RenderBundle( bundleGroup, camera );
  35524. bundles.set( _chainKeys$1, bundle );
  35525. }
  35526. _chainKeys$1.length = 0;
  35527. return bundle;
  35528. }
  35529. /**
  35530. * Frees all internal resources.
  35531. */
  35532. dispose() {
  35533. this.bundles = new ChainMap();
  35534. }
  35535. }
  35536. /**
  35537. * The purpose of a node library is to assign node implementations
  35538. * to existing library features. In `WebGPURenderer` lights, materials
  35539. * which are not based on `NodeMaterial` as well as tone mapping techniques
  35540. * are implemented with node-based modules.
  35541. *
  35542. * @private
  35543. */
  35544. class NodeLibrary {
  35545. /**
  35546. * Constructs a new node library.
  35547. */
  35548. constructor() {
  35549. /**
  35550. * A weak map that maps lights to light nodes.
  35551. *
  35552. * @type {WeakMap<Light.constructor,AnalyticLightNode.constructor>}
  35553. */
  35554. this.lightNodes = new WeakMap();
  35555. /**
  35556. * A map that maps materials to node materials.
  35557. *
  35558. * @type {Map<string,NodeMaterial.constructor>}
  35559. */
  35560. this.materialNodes = new Map();
  35561. /**
  35562. * A map that maps tone mapping techniques (constants)
  35563. * to tone mapping node functions.
  35564. *
  35565. * @type {Map<number,Function>}
  35566. */
  35567. this.toneMappingNodes = new Map();
  35568. }
  35569. /**
  35570. * Returns a matching node material instance for the given material object.
  35571. *
  35572. * This method also assigns/copies the properties of the given material object
  35573. * to the node material. This is done to make sure the current material
  35574. * configuration carries over to the node version.
  35575. *
  35576. * @param {Material} material - A material.
  35577. * @return {NodeMaterial} The corresponding node material.
  35578. */
  35579. fromMaterial( material ) {
  35580. if ( material.isNodeMaterial ) return material;
  35581. let nodeMaterial = null;
  35582. const nodeMaterialClass = this.getMaterialNodeClass( material.type );
  35583. if ( nodeMaterialClass !== null ) {
  35584. nodeMaterial = new nodeMaterialClass();
  35585. for ( const key in material ) {
  35586. nodeMaterial[ key ] = material[ key ];
  35587. }
  35588. }
  35589. return nodeMaterial;
  35590. }
  35591. /**
  35592. * Adds a tone mapping node function for a tone mapping technique (constant).
  35593. *
  35594. * @param {Function} toneMappingNode - The tone mapping node function.
  35595. * @param {number} toneMapping - The tone mapping.
  35596. */
  35597. addToneMapping( toneMappingNode, toneMapping ) {
  35598. this.addType( toneMappingNode, toneMapping, this.toneMappingNodes );
  35599. }
  35600. /**
  35601. * Returns a tone mapping node function for a tone mapping technique (constant).
  35602. *
  35603. * @param {number} toneMapping - The tone mapping.
  35604. * @return {?Function} The tone mapping node function. Returns `null` if no node function is found.
  35605. */
  35606. getToneMappingFunction( toneMapping ) {
  35607. return this.toneMappingNodes.get( toneMapping ) || null;
  35608. }
  35609. /**
  35610. * Returns a node material class definition for a material type.
  35611. *
  35612. * @param {string} materialType - The material type.
  35613. * @return {?NodeMaterial.constructor} The node material class definition. Returns `null` if no node material is found.
  35614. */
  35615. getMaterialNodeClass( materialType ) {
  35616. return this.materialNodes.get( materialType ) || null;
  35617. }
  35618. /**
  35619. * Adds a node material class definition for a given material type.
  35620. *
  35621. * @param {NodeMaterial.constructor} materialNodeClass - The node material class definition.
  35622. * @param {string} materialClassType - The material type.
  35623. */
  35624. addMaterial( materialNodeClass, materialClassType ) {
  35625. this.addType( materialNodeClass, materialClassType, this.materialNodes );
  35626. }
  35627. /**
  35628. * Returns a light node class definition for a light class definition.
  35629. *
  35630. * @param {Light.constructor} light - The light class definition.
  35631. * @return {?AnalyticLightNode.constructor} The light node class definition. Returns `null` if no light node is found.
  35632. */
  35633. getLightNodeClass( light ) {
  35634. return this.lightNodes.get( light ) || null;
  35635. }
  35636. /**
  35637. * Adds a light node class definition for a given light class definition.
  35638. *
  35639. * @param {AnalyticLightNode.constructor} lightNodeClass - The light node class definition.
  35640. * @param {Light.constructor} lightClass - The light class definition.
  35641. */
  35642. addLight( lightNodeClass, lightClass ) {
  35643. this.addClass( lightNodeClass, lightClass, this.lightNodes );
  35644. }
  35645. /**
  35646. * Adds a node class definition for the given type to the provided type library.
  35647. *
  35648. * @param {any} nodeClass - The node class definition.
  35649. * @param {number|string} type - The object type.
  35650. * @param {Map} library - The type library.
  35651. */
  35652. addType( nodeClass, type, library ) {
  35653. if ( library.has( type ) ) {
  35654. console.warn( `Redefinition of node ${ type }` );
  35655. return;
  35656. }
  35657. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  35658. if ( typeof type === 'function' || typeof type === 'object' ) throw new Error( `Base class ${ type } is not a class.` );
  35659. library.set( type, nodeClass );
  35660. }
  35661. /**
  35662. * Adds a node class definition for the given class definition to the provided type library.
  35663. *
  35664. * @param {any} nodeClass - The node class definition.
  35665. * @param {any} baseClass - The class definition.
  35666. * @param {WeakMap} library - The type library.
  35667. */
  35668. addClass( nodeClass, baseClass, library ) {
  35669. if ( library.has( baseClass ) ) {
  35670. console.warn( `Redefinition of node ${ baseClass.name }` );
  35671. return;
  35672. }
  35673. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  35674. if ( typeof baseClass !== 'function' ) throw new Error( `Base class ${ baseClass.name } is not a class.` );
  35675. library.set( baseClass, nodeClass );
  35676. }
  35677. }
  35678. const _defaultLights = /*@__PURE__*/ new LightsNode();
  35679. const _chainKeys = [];
  35680. /**
  35681. * This renderer module manages the lights nodes which are unique
  35682. * per scene and camera combination.
  35683. *
  35684. * The lights node itself is later configured in the render list
  35685. * with the actual lights from the scene.
  35686. *
  35687. * @private
  35688. * @augments ChainMap
  35689. */
  35690. class Lighting extends ChainMap {
  35691. /**
  35692. * Constructs a lighting management component.
  35693. */
  35694. constructor() {
  35695. super();
  35696. }
  35697. /**
  35698. * Creates a new lights node for the given array of lights.
  35699. *
  35700. * @param {Array<Light>} lights - The render object.
  35701. * @return {LightsNode} The lights node.
  35702. */
  35703. createNode( lights = [] ) {
  35704. return new LightsNode().setLights( lights );
  35705. }
  35706. /**
  35707. * Returns a lights node for the given scene and camera.
  35708. *
  35709. * @param {Scene} scene - The scene.
  35710. * @param {Camera} camera - The camera.
  35711. * @return {LightsNode} The lights node.
  35712. */
  35713. getNode( scene, camera ) {
  35714. // ignore post-processing
  35715. if ( scene.isQuadMesh ) return _defaultLights;
  35716. _chainKeys[ 0 ] = scene;
  35717. _chainKeys[ 1 ] = camera;
  35718. let node = this.get( _chainKeys );
  35719. if ( node === undefined ) {
  35720. node = this.createNode();
  35721. this.set( _chainKeys, node );
  35722. }
  35723. _chainKeys.length = 0;
  35724. return node;
  35725. }
  35726. }
  35727. /**
  35728. * A special type of render target that is used when rendering
  35729. * with the WebXR Device API.
  35730. *
  35731. * @private
  35732. * @augments RenderTarget
  35733. */
  35734. class XRRenderTarget extends RenderTarget {
  35735. /**
  35736. * Constructs a new XR render target.
  35737. *
  35738. * @param {number} [width=1] - The width of the render target.
  35739. * @param {number} [height=1] - The height of the render target.
  35740. * @param {Object} [options={}] - The configuration options.
  35741. */
  35742. constructor( width = 1, height = 1, options = {} ) {
  35743. super( width, height, options );
  35744. /**
  35745. * This flag can be used for type testing.
  35746. *
  35747. * @type {boolean}
  35748. * @readonly
  35749. * @default true
  35750. */
  35751. this.isXRRenderTarget = true;
  35752. /**
  35753. * Whether the attachments of the render target
  35754. * are defined by external textures. This flag is
  35755. * set to `true` when using the WebXR Layers API.
  35756. *
  35757. * @private
  35758. * @type {boolean}
  35759. * @default false
  35760. */
  35761. this._hasExternalTextures = false;
  35762. /**
  35763. * Whether a depth buffer should automatically be allocated
  35764. * for this XR render target or not.
  35765. *
  35766. * Allocating a depth buffer is the default behavior of XR render
  35767. * targets. However, when using the WebXR Layers API, this flag
  35768. * must be set to `false` when the `ignoreDepthValues` property of
  35769. * the projection layers evaluates to `false`.
  35770. *
  35771. * Reference: {@link https://www.w3.org/TR/webxrlayers-1/#dom-xrprojectionlayer-ignoredepthvalues}.
  35772. *
  35773. * @private
  35774. * @type {boolean}
  35775. * @default true
  35776. */
  35777. this._autoAllocateDepthBuffer = true;
  35778. /**
  35779. * Whether this render target is associated with a XRWebGLLayer.
  35780. *
  35781. * A XRWebGLLayer points to an opaque framebuffer. Basically,
  35782. * this means that you don't have access to its bound color,
  35783. * stencil and depth buffers. We need to handle this framebuffer
  35784. * differently since its textures are always bound.
  35785. *
  35786. * @private
  35787. * @type {boolean}
  35788. * @default false
  35789. * */
  35790. this._isOpaqueFramebuffer = false;
  35791. }
  35792. copy( source ) {
  35793. super.copy( source );
  35794. this._hasExternalTextures = source._hasExternalTextures;
  35795. this._autoAllocateDepthBuffer = source._autoAllocateDepthBuffer;
  35796. this._isOpaqueFramebuffer = source._isOpaqueFramebuffer;
  35797. return this;
  35798. }
  35799. }
  35800. const _cameraLPos = /*@__PURE__*/ new Vector3();
  35801. const _cameraRPos = /*@__PURE__*/ new Vector3();
  35802. /**
  35803. * The XR manager is built on top of the WebXR Device API to
  35804. * manage XR sessions with `WebGPURenderer`.
  35805. *
  35806. * XR is currently only supported with a WebGL 2 backend.
  35807. *
  35808. * @augments EventDispatcher
  35809. */
  35810. class XRManager extends EventDispatcher {
  35811. /**
  35812. * Constructs a new XR manager.
  35813. *
  35814. * @param {Renderer} renderer - The renderer.
  35815. * @param {boolean} [multiview=false] - Enables multiview if the device supports it.
  35816. */
  35817. constructor( renderer, multiview = false ) {
  35818. super();
  35819. /**
  35820. * This flag globally enables XR rendering.
  35821. *
  35822. * @type {boolean}
  35823. * @default false
  35824. */
  35825. this.enabled = false;
  35826. /**
  35827. * Whether the XR device is currently presenting or not.
  35828. *
  35829. * @type {boolean}
  35830. * @default false
  35831. * @readonly
  35832. */
  35833. this.isPresenting = false;
  35834. /**
  35835. * Whether the XR camera should automatically be updated or not.
  35836. *
  35837. * @type {boolean}
  35838. * @default true
  35839. */
  35840. this.cameraAutoUpdate = true;
  35841. /**
  35842. * The renderer.
  35843. *
  35844. * @private
  35845. * @type {Renderer}
  35846. */
  35847. this._renderer = renderer;
  35848. // camera
  35849. /**
  35850. * Represents the camera for the left eye.
  35851. *
  35852. * @private
  35853. * @type {PerspectiveCamera}
  35854. */
  35855. this._cameraL = new PerspectiveCamera();
  35856. this._cameraL.viewport = new Vector4();
  35857. /**
  35858. * Represents the camera for the right eye.
  35859. *
  35860. * @private
  35861. * @type {PerspectiveCamera}
  35862. */
  35863. this._cameraR = new PerspectiveCamera();
  35864. this._cameraR.viewport = new Vector4();
  35865. /**
  35866. * A list of cameras used for rendering the XR views.
  35867. *
  35868. * @private
  35869. * @type {Array<Camera>}
  35870. */
  35871. this._cameras = [ this._cameraL, this._cameraR ];
  35872. /**
  35873. * The main XR camera.
  35874. *
  35875. * @private
  35876. * @type {ArrayCamera}
  35877. */
  35878. this._cameraXR = new ArrayCamera();
  35879. /**
  35880. * The current near value of the XR camera.
  35881. *
  35882. * @private
  35883. * @type {?number}
  35884. * @default null
  35885. */
  35886. this._currentDepthNear = null;
  35887. /**
  35888. * The current far value of the XR camera.
  35889. *
  35890. * @private
  35891. * @type {?number}
  35892. * @default null
  35893. */
  35894. this._currentDepthFar = null;
  35895. /**
  35896. * A list of WebXR controllers requested by the application.
  35897. *
  35898. * @private
  35899. * @type {Array<WebXRController>}
  35900. */
  35901. this._controllers = [];
  35902. /**
  35903. * A list of XR input source. Each input source belongs to
  35904. * an instance of WebXRController.
  35905. *
  35906. * @private
  35907. * @type {Array<XRInputSource?>}
  35908. */
  35909. this._controllerInputSources = [];
  35910. /**
  35911. * The XR render target that represents the rendering destination
  35912. * during an active XR session.
  35913. *
  35914. * @private
  35915. * @type {?RenderTarget}
  35916. * @default null
  35917. */
  35918. this._xrRenderTarget = null;
  35919. /**
  35920. * An array holding all the non-projection layers
  35921. *
  35922. * @private
  35923. * @type {Array<Object>}
  35924. * @default []
  35925. */
  35926. this._layers = [];
  35927. /**
  35928. * Whether the device has support for all layer types.
  35929. *
  35930. * @type {boolean}
  35931. * @default false
  35932. */
  35933. this._supportsLayers = false;
  35934. /**
  35935. * Whether the device supports binding gl objects.
  35936. *
  35937. * @private
  35938. * @type {boolean}
  35939. * @readonly
  35940. */
  35941. this._supportsGlBinding = typeof XRWebGLBinding !== 'undefined';
  35942. this._frameBufferTargets = null;
  35943. /**
  35944. * Helper function to create native WebXR Layer.
  35945. *
  35946. * @private
  35947. * @type {Function}
  35948. */
  35949. this._createXRLayer = createXRLayer.bind( this );
  35950. /**
  35951. * The current WebGL context.
  35952. *
  35953. * @private
  35954. * @type {?WebGL2RenderingContext}
  35955. * @default null
  35956. */
  35957. this._gl = null;
  35958. /**
  35959. * The current animation context.
  35960. *
  35961. * @private
  35962. * @type {?Window}
  35963. * @default null
  35964. */
  35965. this._currentAnimationContext = null;
  35966. /**
  35967. * The current animation loop.
  35968. *
  35969. * @private
  35970. * @type {?Function}
  35971. * @default null
  35972. */
  35973. this._currentAnimationLoop = null;
  35974. /**
  35975. * The current pixel ratio.
  35976. *
  35977. * @private
  35978. * @type {?number}
  35979. * @default null
  35980. */
  35981. this._currentPixelRatio = null;
  35982. /**
  35983. * The current size of the renderer's canvas
  35984. * in logical pixel unit.
  35985. *
  35986. * @private
  35987. * @type {Vector2}
  35988. */
  35989. this._currentSize = new Vector2();
  35990. /**
  35991. * The default event listener for handling events inside a XR session.
  35992. *
  35993. * @private
  35994. * @type {Function}
  35995. */
  35996. this._onSessionEvent = onSessionEvent.bind( this );
  35997. /**
  35998. * The event listener for handling the end of a XR session.
  35999. *
  36000. * @private
  36001. * @type {Function}
  36002. */
  36003. this._onSessionEnd = onSessionEnd.bind( this );
  36004. /**
  36005. * The event listener for handling the `inputsourceschange` event.
  36006. *
  36007. * @private
  36008. * @type {Function}
  36009. */
  36010. this._onInputSourcesChange = onInputSourcesChange.bind( this );
  36011. /**
  36012. * The animation loop which is used as a replacement for the default
  36013. * animation loop of the application. It is only used when a XR session
  36014. * is active.
  36015. *
  36016. * @private
  36017. * @type {Function}
  36018. */
  36019. this._onAnimationFrame = onAnimationFrame.bind( this );
  36020. /**
  36021. * The current XR reference space.
  36022. *
  36023. * @private
  36024. * @type {?XRReferenceSpace}
  36025. * @default null
  36026. */
  36027. this._referenceSpace = null;
  36028. /**
  36029. * The current XR reference space type.
  36030. *
  36031. * @private
  36032. * @type {XRReferenceSpaceType}
  36033. * @default 'local-floor'
  36034. */
  36035. this._referenceSpaceType = 'local-floor';
  36036. /**
  36037. * A custom reference space defined by the application.
  36038. *
  36039. * @private
  36040. * @type {?XRReferenceSpace}
  36041. * @default null
  36042. */
  36043. this._customReferenceSpace = null;
  36044. /**
  36045. * The framebuffer scale factor.
  36046. *
  36047. * @private
  36048. * @type {number}
  36049. * @default 1
  36050. */
  36051. this._framebufferScaleFactor = 1;
  36052. /**
  36053. * The foveation factor.
  36054. *
  36055. * @private
  36056. * @type {number}
  36057. * @default 1
  36058. */
  36059. this._foveation = 1.0;
  36060. /**
  36061. * A reference to the current XR session.
  36062. *
  36063. * @private
  36064. * @type {?XRSession}
  36065. * @default null
  36066. */
  36067. this._session = null;
  36068. /**
  36069. * A reference to the current XR base layer.
  36070. *
  36071. * @private
  36072. * @type {?XRWebGLLayer}
  36073. * @default null
  36074. */
  36075. this._glBaseLayer = null;
  36076. /**
  36077. * A reference to the current XR binding.
  36078. *
  36079. * @private
  36080. * @type {?XRWebGLBinding}
  36081. * @default null
  36082. */
  36083. this._glBinding = null;
  36084. /**
  36085. * A reference to the current XR projection layer.
  36086. *
  36087. * @private
  36088. * @type {?XRProjectionLayer}
  36089. * @default null
  36090. */
  36091. this._glProjLayer = null;
  36092. /**
  36093. * A reference to the current XR frame.
  36094. *
  36095. * @private
  36096. * @type {?XRFrame}
  36097. * @default null
  36098. */
  36099. this._xrFrame = null;
  36100. /**
  36101. * Whether to use the WebXR Layers API or not.
  36102. *
  36103. * @private
  36104. * @type {boolean}
  36105. * @readonly
  36106. */
  36107. this._useLayers = ( this._supportsGlBinding && 'createProjectionLayer' in XRWebGLBinding.prototype ); // eslint-disable-line compat/compat
  36108. /**
  36109. * Whether the usage of multiview has been requested by the application or not.
  36110. *
  36111. * @private
  36112. * @type {boolean}
  36113. * @default false
  36114. * @readonly
  36115. */
  36116. this._useMultiviewIfPossible = multiview;
  36117. /**
  36118. * Whether the usage of multiview is actually enabled. This flag only evaluates to `true`
  36119. * if multiview has been requested by the application and the `OVR_multiview2` is available.
  36120. *
  36121. * @private
  36122. * @type {boolean}
  36123. * @readonly
  36124. */
  36125. this._useMultiview = false;
  36126. }
  36127. /**
  36128. * Returns an instance of `THREE.Group` that represents the transformation
  36129. * of a XR controller in target ray space. The requested controller is defined
  36130. * by the given index.
  36131. *
  36132. * @param {number} index - The index of the XR controller.
  36133. * @return {Group} A group that represents the controller's transformation.
  36134. */
  36135. getController( index ) {
  36136. const controller = this._getController( index );
  36137. return controller.getTargetRaySpace();
  36138. }
  36139. /**
  36140. * Returns an instance of `THREE.Group` that represents the transformation
  36141. * of a XR controller in grip space. The requested controller is defined
  36142. * by the given index.
  36143. *
  36144. * @param {number} index - The index of the XR controller.
  36145. * @return {Group} A group that represents the controller's transformation.
  36146. */
  36147. getControllerGrip( index ) {
  36148. const controller = this._getController( index );
  36149. return controller.getGripSpace();
  36150. }
  36151. /**
  36152. * Returns an instance of `THREE.Group` that represents the transformation
  36153. * of a XR controller in hand space. The requested controller is defined
  36154. * by the given index.
  36155. *
  36156. * @param {number} index - The index of the XR controller.
  36157. * @return {Group} A group that represents the controller's transformation.
  36158. */
  36159. getHand( index ) {
  36160. const controller = this._getController( index );
  36161. return controller.getHandSpace();
  36162. }
  36163. /**
  36164. * Returns the foveation value.
  36165. *
  36166. * @return {number|undefined} The foveation value. Returns `undefined` if no base or projection layer is defined.
  36167. */
  36168. getFoveation() {
  36169. if ( this._glProjLayer === null && this._glBaseLayer === null ) {
  36170. return undefined;
  36171. }
  36172. return this._foveation;
  36173. }
  36174. /**
  36175. * Sets the foveation value.
  36176. *
  36177. * @param {number} foveation - A number in the range `[0,1]` where `0` means no foveation (full resolution)
  36178. * and `1` means maximum foveation (the edges render at lower resolution).
  36179. */
  36180. setFoveation( foveation ) {
  36181. this._foveation = foveation;
  36182. if ( this._glProjLayer !== null ) {
  36183. this._glProjLayer.fixedFoveation = foveation;
  36184. }
  36185. if ( this._glBaseLayer !== null && this._glBaseLayer.fixedFoveation !== undefined ) {
  36186. this._glBaseLayer.fixedFoveation = foveation;
  36187. }
  36188. }
  36189. /**
  36190. * Returns the framebuffer scale factor.
  36191. *
  36192. * @return {number} The framebuffer scale factor.
  36193. */
  36194. getFramebufferScaleFactor() {
  36195. return this._framebufferScaleFactor;
  36196. }
  36197. /**
  36198. * Sets the framebuffer scale factor.
  36199. *
  36200. * This method can not be used during a XR session.
  36201. *
  36202. * @param {number} factor - The framebuffer scale factor.
  36203. */
  36204. setFramebufferScaleFactor( factor ) {
  36205. this._framebufferScaleFactor = factor;
  36206. if ( this.isPresenting === true ) {
  36207. console.warn( 'THREE.XRManager: Cannot change framebuffer scale while presenting.' );
  36208. }
  36209. }
  36210. /**
  36211. * Returns the reference space type.
  36212. *
  36213. * @return {XRReferenceSpaceType} The reference space type.
  36214. */
  36215. getReferenceSpaceType() {
  36216. return this._referenceSpaceType;
  36217. }
  36218. /**
  36219. * Sets the reference space type.
  36220. *
  36221. * This method can not be used during a XR session.
  36222. *
  36223. * @param {XRReferenceSpaceType} type - The reference space type.
  36224. */
  36225. setReferenceSpaceType( type ) {
  36226. this._referenceSpaceType = type;
  36227. if ( this.isPresenting === true ) {
  36228. console.warn( 'THREE.XRManager: Cannot change reference space type while presenting.' );
  36229. }
  36230. }
  36231. /**
  36232. * Returns the XR reference space.
  36233. *
  36234. * @return {XRReferenceSpace} The XR reference space.
  36235. */
  36236. getReferenceSpace() {
  36237. return this._customReferenceSpace || this._referenceSpace;
  36238. }
  36239. /**
  36240. * Sets a custom XR reference space.
  36241. *
  36242. * @param {XRReferenceSpace} space - The XR reference space.
  36243. */
  36244. setReferenceSpace( space ) {
  36245. this._customReferenceSpace = space;
  36246. }
  36247. /**
  36248. * Returns the XR camera.
  36249. *
  36250. * @return {ArrayCamera} The XR camera.
  36251. */
  36252. getCamera() {
  36253. return this._cameraXR;
  36254. }
  36255. /**
  36256. * Returns the environment blend mode from the current XR session.
  36257. *
  36258. * @return {'opaque'|'additive'|'alpha-blend'|undefined} The environment blend mode. Returns `undefined` when used outside of a XR session.
  36259. */
  36260. getEnvironmentBlendMode() {
  36261. if ( this._session !== null ) {
  36262. return this._session.environmentBlendMode;
  36263. }
  36264. }
  36265. /**
  36266. * Returns the current XR frame.
  36267. *
  36268. * @return {?XRFrame} The XR frame. Returns `null` when used outside a XR session.
  36269. */
  36270. getFrame() {
  36271. return this._xrFrame;
  36272. }
  36273. /**
  36274. * Returns `true` if the engine renders to a multiview target.
  36275. *
  36276. * @return {boolean} Whether the engine renders to a multiview render target or not.
  36277. */
  36278. useMultiview() {
  36279. return this._useMultiview;
  36280. }
  36281. /**
  36282. * This method can be used in XR applications to create a quadratic layer that presents a separate
  36283. * rendered scene.
  36284. *
  36285. * @param {number} width - The width of the layer plane in world units.
  36286. * @param {number} height - The height of the layer plane in world units.
  36287. * @param {Vector3} translation - The position/translation of the layer plane in world units.
  36288. * @param {Quaternion} quaternion - The orientation of the layer plane expressed as a quaternion.
  36289. * @param {number} pixelwidth - The width of the layer's render target in pixels.
  36290. * @param {number} pixelheight - The height of the layer's render target in pixels.
  36291. * @param {Function} rendercall - A callback function that renders the layer. Similar to code in
  36292. * the default animation loop, this method can be used to update/transform 3D object in the layer's scene.
  36293. * @param {Object} [attributes={}] - Allows to configure the layer's render target.
  36294. * @return {Mesh} A mesh representing the quadratic XR layer. This mesh should be added to the XR scene.
  36295. */
  36296. createQuadLayer( width, height, translation, quaternion, pixelwidth, pixelheight, rendercall, attributes = {} ) {
  36297. const geometry = new PlaneGeometry( width, height );
  36298. const renderTarget = new XRRenderTarget(
  36299. pixelwidth,
  36300. pixelheight,
  36301. {
  36302. format: RGBAFormat,
  36303. type: UnsignedByteType,
  36304. depthTexture: new DepthTexture(
  36305. pixelwidth,
  36306. pixelheight,
  36307. attributes.stencil ? UnsignedInt248Type : UnsignedIntType,
  36308. undefined,
  36309. undefined,
  36310. undefined,
  36311. undefined,
  36312. undefined,
  36313. undefined,
  36314. attributes.stencil ? DepthStencilFormat : DepthFormat
  36315. ),
  36316. stencilBuffer: attributes.stencil,
  36317. resolveDepthBuffer: false,
  36318. resolveStencilBuffer: false
  36319. } );
  36320. renderTarget._autoAllocateDepthBuffer = true;
  36321. const material = new MeshBasicMaterial( { color: 0xffffff, side: FrontSide } );
  36322. material.map = renderTarget.texture;
  36323. material.map.offset.y = 1;
  36324. material.map.repeat.y = -1;
  36325. const plane = new Mesh( geometry, material );
  36326. plane.position.copy( translation );
  36327. plane.quaternion.copy( quaternion );
  36328. const layer = {
  36329. type: 'quad',
  36330. width: width,
  36331. height: height,
  36332. translation: translation,
  36333. quaternion: quaternion,
  36334. pixelwidth: pixelwidth,
  36335. pixelheight: pixelheight,
  36336. plane: plane,
  36337. material: material,
  36338. rendercall: rendercall,
  36339. renderTarget: renderTarget };
  36340. this._layers.push( layer );
  36341. if ( this._session !== null ) {
  36342. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: FrontSide } );
  36343. layer.plane.material.blending = CustomBlending;
  36344. layer.plane.material.blendEquation = AddEquation;
  36345. layer.plane.material.blendSrc = ZeroFactor;
  36346. layer.plane.material.blendDst = ZeroFactor;
  36347. layer.xrlayer = this._createXRLayer( layer );
  36348. const xrlayers = this._session.renderState.layers;
  36349. xrlayers.unshift( layer.xrlayer );
  36350. this._session.updateRenderState( { layers: xrlayers } );
  36351. } else {
  36352. renderTarget.isXRRenderTarget = false;
  36353. }
  36354. return plane;
  36355. }
  36356. /**
  36357. * This method can be used in XR applications to create a cylindrical layer that presents a separate
  36358. * rendered scene.
  36359. *
  36360. * @param {number} radius - The radius of the cylinder in world units.
  36361. * @param {number} centralAngle - The central angle of the cylinder in radians.
  36362. * @param {number} aspectratio - The aspect ratio.
  36363. * @param {Vector3} translation - The position/translation of the layer plane in world units.
  36364. * @param {Quaternion} quaternion - The orientation of the layer plane expressed as a quaternion.
  36365. * @param {number} pixelwidth - The width of the layer's render target in pixels.
  36366. * @param {number} pixelheight - The height of the layer's render target in pixels.
  36367. * @param {Function} rendercall - A callback function that renders the layer. Similar to code in
  36368. * the default animation loop, this method can be used to update/transform 3D object in the layer's scene.
  36369. * @param {Object} [attributes={}] - Allows to configure the layer's render target.
  36370. * @return {Mesh} A mesh representing the cylindrical XR layer. This mesh should be added to the XR scene.
  36371. */
  36372. createCylinderLayer( radius, centralAngle, aspectratio, translation, quaternion, pixelwidth, pixelheight, rendercall, attributes = {} ) {
  36373. const geometry = new CylinderGeometry( radius, radius, radius * centralAngle / aspectratio, 64, 64, true, Math.PI - centralAngle / 2, centralAngle );
  36374. const renderTarget = new XRRenderTarget(
  36375. pixelwidth,
  36376. pixelheight,
  36377. {
  36378. format: RGBAFormat,
  36379. type: UnsignedByteType,
  36380. depthTexture: new DepthTexture(
  36381. pixelwidth,
  36382. pixelheight,
  36383. attributes.stencil ? UnsignedInt248Type : UnsignedIntType,
  36384. undefined,
  36385. undefined,
  36386. undefined,
  36387. undefined,
  36388. undefined,
  36389. undefined,
  36390. attributes.stencil ? DepthStencilFormat : DepthFormat
  36391. ),
  36392. stencilBuffer: attributes.stencil,
  36393. resolveDepthBuffer: false,
  36394. resolveStencilBuffer: false
  36395. } );
  36396. renderTarget._autoAllocateDepthBuffer = true;
  36397. const material = new MeshBasicMaterial( { color: 0xffffff, side: BackSide } );
  36398. material.map = renderTarget.texture;
  36399. material.map.offset.y = 1;
  36400. material.map.repeat.y = -1;
  36401. const plane = new Mesh( geometry, material );
  36402. plane.position.copy( translation );
  36403. plane.quaternion.copy( quaternion );
  36404. const layer = {
  36405. type: 'cylinder',
  36406. radius: radius,
  36407. centralAngle: centralAngle,
  36408. aspectratio: aspectratio,
  36409. translation: translation,
  36410. quaternion: quaternion,
  36411. pixelwidth: pixelwidth,
  36412. pixelheight: pixelheight,
  36413. plane: plane,
  36414. material: material,
  36415. rendercall: rendercall,
  36416. renderTarget: renderTarget };
  36417. this._layers.push( layer );
  36418. if ( this._session !== null ) {
  36419. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: BackSide } );
  36420. layer.plane.material.blending = CustomBlending;
  36421. layer.plane.material.blendEquation = AddEquation;
  36422. layer.plane.material.blendSrc = ZeroFactor;
  36423. layer.plane.material.blendDst = ZeroFactor;
  36424. layer.xrlayer = this._createXRLayer( layer );
  36425. const xrlayers = this._session.renderState.layers;
  36426. xrlayers.unshift( layer.xrlayer );
  36427. this._session.updateRenderState( { layers: xrlayers } );
  36428. } else {
  36429. renderTarget.isXRRenderTarget = false;
  36430. }
  36431. return plane;
  36432. }
  36433. /**
  36434. * Renders the XR layers that have been previously added to the scene.
  36435. *
  36436. * This method is usually called in your animation loop before rendering
  36437. * the actual scene via `renderer.render( scene, camera );`.
  36438. */
  36439. renderLayers( ) {
  36440. const translationObject = new Vector3();
  36441. const quaternionObject = new Quaternion();
  36442. const renderer = this._renderer;
  36443. const wasPresenting = this.isPresenting;
  36444. const rendererOutputTarget = renderer.getOutputRenderTarget();
  36445. const rendererFramebufferTarget = renderer._frameBufferTarget;
  36446. this.isPresenting = false;
  36447. const rendererSize = new Vector2();
  36448. renderer.getSize( rendererSize );
  36449. const rendererQuad = renderer._quad;
  36450. for ( const layer of this._layers ) {
  36451. layer.renderTarget.isXRRenderTarget = this._session !== null;
  36452. layer.renderTarget._hasExternalTextures = layer.renderTarget.isXRRenderTarget;
  36453. if ( layer.renderTarget.isXRRenderTarget && this._supportsLayers ) {
  36454. layer.xrlayer.transform = new XRRigidTransform( layer.plane.getWorldPosition( translationObject ), layer.plane.getWorldQuaternion( quaternionObject ) );
  36455. const glSubImage = this._glBinding.getSubImage( layer.xrlayer, this._xrFrame );
  36456. renderer.backend.setXRRenderTargetTextures(
  36457. layer.renderTarget,
  36458. glSubImage.colorTexture,
  36459. undefined );
  36460. renderer._setXRLayerSize( layer.renderTarget.width, layer.renderTarget.height );
  36461. renderer.setOutputRenderTarget( layer.renderTarget );
  36462. renderer.setRenderTarget( null );
  36463. renderer._frameBufferTarget = null;
  36464. this._frameBufferTargets || ( this._frameBufferTargets = new WeakMap() );
  36465. const { frameBufferTarget, quad } = this._frameBufferTargets.get( layer.renderTarget ) || { frameBufferTarget: null, quad: null };
  36466. if ( ! frameBufferTarget ) {
  36467. renderer._quad = new QuadMesh( new NodeMaterial() );
  36468. this._frameBufferTargets.set( layer.renderTarget, { frameBufferTarget: renderer._getFrameBufferTarget(), quad: renderer._quad } );
  36469. } else {
  36470. renderer._frameBufferTarget = frameBufferTarget;
  36471. renderer._quad = quad;
  36472. }
  36473. layer.rendercall();
  36474. renderer._frameBufferTarget = null;
  36475. } else {
  36476. renderer.setRenderTarget( layer.renderTarget );
  36477. layer.rendercall();
  36478. }
  36479. }
  36480. renderer.setRenderTarget( null );
  36481. renderer.setOutputRenderTarget( rendererOutputTarget );
  36482. renderer._frameBufferTarget = rendererFramebufferTarget;
  36483. renderer._setXRLayerSize( rendererSize.x, rendererSize.y );
  36484. renderer._quad = rendererQuad;
  36485. this.isPresenting = wasPresenting;
  36486. }
  36487. /**
  36488. * Returns the current XR session.
  36489. *
  36490. * @return {?XRSession} The XR session. Returns `null` when used outside a XR session.
  36491. */
  36492. getSession() {
  36493. return this._session;
  36494. }
  36495. /**
  36496. * After a XR session has been requested usually with one of the `*Button` modules, it
  36497. * is injected into the renderer with this method. This method triggers the start of
  36498. * the actual XR rendering.
  36499. *
  36500. * @async
  36501. * @param {XRSession} session - The XR session to set.
  36502. * @return {Promise} A Promise that resolves when the session has been set.
  36503. */
  36504. async setSession( session ) {
  36505. const renderer = this._renderer;
  36506. const backend = renderer.backend;
  36507. this._gl = renderer.getContext();
  36508. const gl = this._gl;
  36509. const attributes = gl.getContextAttributes();
  36510. this._session = session;
  36511. if ( session !== null ) {
  36512. 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.' );
  36513. session.addEventListener( 'select', this._onSessionEvent );
  36514. session.addEventListener( 'selectstart', this._onSessionEvent );
  36515. session.addEventListener( 'selectend', this._onSessionEvent );
  36516. session.addEventListener( 'squeeze', this._onSessionEvent );
  36517. session.addEventListener( 'squeezestart', this._onSessionEvent );
  36518. session.addEventListener( 'squeezeend', this._onSessionEvent );
  36519. session.addEventListener( 'end', this._onSessionEnd );
  36520. session.addEventListener( 'inputsourceschange', this._onInputSourcesChange );
  36521. await backend.makeXRCompatible();
  36522. this._currentPixelRatio = renderer.getPixelRatio();
  36523. renderer.getSize( this._currentSize );
  36524. this._currentAnimationContext = renderer._animation.getContext();
  36525. this._currentAnimationLoop = renderer._animation.getAnimationLoop();
  36526. renderer._animation.stop();
  36527. //
  36528. if ( this._supportsGlBinding ) {
  36529. const glBinding = new XRWebGLBinding( session, gl );
  36530. this._glBinding = glBinding;
  36531. }
  36532. //
  36533. if ( this._useLayers === true ) {
  36534. // default path using XRProjectionLayer
  36535. let depthFormat = null;
  36536. let depthType = null;
  36537. let glDepthFormat = null;
  36538. if ( renderer.depth ) {
  36539. glDepthFormat = renderer.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  36540. depthFormat = renderer.stencil ? DepthStencilFormat : DepthFormat;
  36541. depthType = renderer.stencil ? UnsignedInt248Type : UnsignedIntType;
  36542. }
  36543. const projectionlayerInit = {
  36544. colorFormat: gl.RGBA8,
  36545. depthFormat: glDepthFormat,
  36546. scaleFactor: this._framebufferScaleFactor,
  36547. clearOnAccess: false
  36548. };
  36549. if ( this._useMultiviewIfPossible && renderer.hasFeature( 'OVR_multiview2' ) ) {
  36550. projectionlayerInit.textureType = 'texture-array';
  36551. this._useMultiview = true;
  36552. }
  36553. const glProjLayer = this._glBinding.createProjectionLayer( projectionlayerInit );
  36554. const layersArray = [ glProjLayer ];
  36555. this._glProjLayer = glProjLayer;
  36556. renderer.setPixelRatio( 1 );
  36557. renderer._setXRLayerSize( glProjLayer.textureWidth, glProjLayer.textureHeight );
  36558. const depth = this._useMultiview ? 2 : 1;
  36559. const depthTexture = new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat, depth );
  36560. this._xrRenderTarget = new XRRenderTarget(
  36561. glProjLayer.textureWidth,
  36562. glProjLayer.textureHeight,
  36563. {
  36564. format: RGBAFormat,
  36565. type: UnsignedByteType,
  36566. colorSpace: renderer.outputColorSpace,
  36567. depthTexture: depthTexture,
  36568. stencilBuffer: renderer.stencil,
  36569. samples: attributes.antialias ? 4 : 0,
  36570. resolveDepthBuffer: ( glProjLayer.ignoreDepthValues === false ),
  36571. resolveStencilBuffer: ( glProjLayer.ignoreDepthValues === false ),
  36572. depth: this._useMultiview ? 2 : 1,
  36573. multiview: this._useMultiview
  36574. } );
  36575. this._xrRenderTarget._hasExternalTextures = true;
  36576. this._xrRenderTarget.depth = this._useMultiview ? 2 : 1;
  36577. this._supportsLayers = session.enabledFeatures.includes( 'layers' );
  36578. this._referenceSpace = await session.requestReferenceSpace( this.getReferenceSpaceType() );
  36579. if ( this._supportsLayers ) {
  36580. // switch layers to native
  36581. for ( const layer of this._layers ) {
  36582. // change material so it "punches" out a hole to show the XR Layer.
  36583. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: layer.type === 'cylinder' ? BackSide : FrontSide } );
  36584. layer.plane.material.blending = CustomBlending;
  36585. layer.plane.material.blendEquation = AddEquation;
  36586. layer.plane.material.blendSrc = ZeroFactor;
  36587. layer.plane.material.blendDst = ZeroFactor;
  36588. layer.xrlayer = this._createXRLayer( layer );
  36589. layersArray.unshift( layer.xrlayer );
  36590. }
  36591. }
  36592. session.updateRenderState( { layers: layersArray } );
  36593. } else {
  36594. // fallback to XRWebGLLayer
  36595. const layerInit = {
  36596. antialias: renderer.samples > 0,
  36597. alpha: true,
  36598. depth: renderer.depth,
  36599. stencil: renderer.stencil,
  36600. framebufferScaleFactor: this.getFramebufferScaleFactor()
  36601. };
  36602. const glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  36603. this._glBaseLayer = glBaseLayer;
  36604. session.updateRenderState( { baseLayer: glBaseLayer } );
  36605. renderer.setPixelRatio( 1 );
  36606. renderer._setXRLayerSize( glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight );
  36607. this._xrRenderTarget = new XRRenderTarget(
  36608. glBaseLayer.framebufferWidth,
  36609. glBaseLayer.framebufferHeight,
  36610. {
  36611. format: RGBAFormat,
  36612. type: UnsignedByteType,
  36613. colorSpace: renderer.outputColorSpace,
  36614. stencilBuffer: renderer.stencil,
  36615. resolveDepthBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  36616. resolveStencilBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  36617. }
  36618. );
  36619. this._xrRenderTarget._isOpaqueFramebuffer = true;
  36620. this._referenceSpace = await session.requestReferenceSpace( this.getReferenceSpaceType() );
  36621. }
  36622. //
  36623. this.setFoveation( this.getFoveation() );
  36624. renderer._animation.setAnimationLoop( this._onAnimationFrame );
  36625. renderer._animation.setContext( session );
  36626. renderer._animation.start();
  36627. this.isPresenting = true;
  36628. this.dispatchEvent( { type: 'sessionstart' } );
  36629. }
  36630. }
  36631. /**
  36632. * This method is called by the renderer per frame and updates the XR camera
  36633. * and it sub cameras based on the given camera. The given camera is the "user"
  36634. * camera created on application level and used for non-XR rendering.
  36635. *
  36636. * @param {PerspectiveCamera} camera - The camera.
  36637. */
  36638. updateCamera( camera ) {
  36639. const session = this._session;
  36640. if ( session === null ) return;
  36641. const depthNear = camera.near;
  36642. const depthFar = camera.far;
  36643. const cameraXR = this._cameraXR;
  36644. const cameraL = this._cameraL;
  36645. const cameraR = this._cameraR;
  36646. cameraXR.near = cameraR.near = cameraL.near = depthNear;
  36647. cameraXR.far = cameraR.far = cameraL.far = depthFar;
  36648. cameraXR.isMultiViewCamera = this._useMultiview;
  36649. if ( this._currentDepthNear !== cameraXR.near || this._currentDepthFar !== cameraXR.far ) {
  36650. // Note that the new renderState won't apply until the next frame. See #18320
  36651. session.updateRenderState( {
  36652. depthNear: cameraXR.near,
  36653. depthFar: cameraXR.far
  36654. } );
  36655. this._currentDepthNear = cameraXR.near;
  36656. this._currentDepthFar = cameraXR.far;
  36657. }
  36658. cameraL.layers.mask = camera.layers.mask | 0b010;
  36659. cameraR.layers.mask = camera.layers.mask | 0b100;
  36660. cameraXR.layers.mask = cameraL.layers.mask | cameraR.layers.mask;
  36661. const parent = camera.parent;
  36662. const cameras = cameraXR.cameras;
  36663. updateCamera( cameraXR, parent );
  36664. for ( let i = 0; i < cameras.length; i ++ ) {
  36665. updateCamera( cameras[ i ], parent );
  36666. }
  36667. // update projection matrix for proper view frustum culling
  36668. if ( cameras.length === 2 ) {
  36669. setProjectionFromUnion( cameraXR, cameraL, cameraR );
  36670. } else {
  36671. // assume single camera setup (AR)
  36672. cameraXR.projectionMatrix.copy( cameraL.projectionMatrix );
  36673. }
  36674. // update user camera and its children
  36675. updateUserCamera( camera, cameraXR, parent );
  36676. }
  36677. /**
  36678. * Returns a WebXR controller for the given controller index.
  36679. *
  36680. * @private
  36681. * @param {number} index - The controller index.
  36682. * @return {WebXRController} The XR controller.
  36683. */
  36684. _getController( index ) {
  36685. let controller = this._controllers[ index ];
  36686. if ( controller === undefined ) {
  36687. controller = new WebXRController();
  36688. this._controllers[ index ] = controller;
  36689. }
  36690. return controller;
  36691. }
  36692. }
  36693. /**
  36694. * Assumes 2 cameras that are parallel and share an X-axis, and that
  36695. * the cameras' projection and world matrices have already been set.
  36696. * And that near and far planes are identical for both cameras.
  36697. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  36698. *
  36699. * @param {ArrayCamera} camera - The camera to update.
  36700. * @param {PerspectiveCamera} cameraL - The left camera.
  36701. * @param {PerspectiveCamera} cameraR - The right camera.
  36702. */
  36703. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  36704. _cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  36705. _cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  36706. const ipd = _cameraLPos.distanceTo( _cameraRPos );
  36707. const projL = cameraL.projectionMatrix.elements;
  36708. const projR = cameraR.projectionMatrix.elements;
  36709. // VR systems will have identical far and near planes, and
  36710. // most likely identical top and bottom frustum extents.
  36711. // Use the left camera for these values.
  36712. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  36713. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  36714. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  36715. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  36716. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  36717. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  36718. const left = near * leftFov;
  36719. const right = near * rightFov;
  36720. // Calculate the new camera's position offset from the
  36721. // left camera. xOffset should be roughly half `ipd`.
  36722. const zOffset = ipd / ( - leftFov + rightFov );
  36723. const xOffset = zOffset * - leftFov;
  36724. // TODO: Better way to apply this offset?
  36725. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  36726. camera.translateX( xOffset );
  36727. camera.translateZ( zOffset );
  36728. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  36729. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  36730. // Check if the projection uses an infinite far plane.
  36731. if ( projL[ 10 ] === -1 ) {
  36732. // Use the projection matrix from the left eye.
  36733. // The camera offset is sufficient to include the view volumes
  36734. // of both eyes (assuming symmetric projections).
  36735. camera.projectionMatrix.copy( cameraL.projectionMatrix );
  36736. camera.projectionMatrixInverse.copy( cameraL.projectionMatrixInverse );
  36737. } else {
  36738. // Find the union of the frustum values of the cameras and scale
  36739. // the values so that the near plane's position does not change in world space,
  36740. // although must now be relative to the new union camera.
  36741. const near2 = near + zOffset;
  36742. const far2 = far + zOffset;
  36743. const left2 = left - xOffset;
  36744. const right2 = right + ( ipd - xOffset );
  36745. const top2 = topFov * far / far2 * near2;
  36746. const bottom2 = bottomFov * far / far2 * near2;
  36747. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  36748. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  36749. }
  36750. }
  36751. /**
  36752. * Updates the world matrices for the given camera based on the parent 3D object.
  36753. *
  36754. * @inner
  36755. * @param {Camera} camera - The camera to update.
  36756. * @param {Object3D} parent - The parent 3D object.
  36757. */
  36758. function updateCamera( camera, parent ) {
  36759. if ( parent === null ) {
  36760. camera.matrixWorld.copy( camera.matrix );
  36761. } else {
  36762. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  36763. }
  36764. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  36765. }
  36766. /**
  36767. * Updates the given camera with the transformation of the XR camera and parent object.
  36768. *
  36769. * @inner
  36770. * @param {Camera} camera - The camera to update.
  36771. * @param {ArrayCamera} cameraXR - The XR camera.
  36772. * @param {Object3D} parent - The parent 3D object.
  36773. */
  36774. function updateUserCamera( camera, cameraXR, parent ) {
  36775. if ( parent === null ) {
  36776. camera.matrix.copy( cameraXR.matrixWorld );
  36777. } else {
  36778. camera.matrix.copy( parent.matrixWorld );
  36779. camera.matrix.invert();
  36780. camera.matrix.multiply( cameraXR.matrixWorld );
  36781. }
  36782. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  36783. camera.updateMatrixWorld( true );
  36784. camera.projectionMatrix.copy( cameraXR.projectionMatrix );
  36785. camera.projectionMatrixInverse.copy( cameraXR.projectionMatrixInverse );
  36786. if ( camera.isPerspectiveCamera ) {
  36787. camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );
  36788. camera.zoom = 1;
  36789. }
  36790. }
  36791. function onSessionEvent( event ) {
  36792. const controllerIndex = this._controllerInputSources.indexOf( event.inputSource );
  36793. if ( controllerIndex === -1 ) {
  36794. return;
  36795. }
  36796. const controller = this._controllers[ controllerIndex ];
  36797. if ( controller !== undefined ) {
  36798. const referenceSpace = this.getReferenceSpace();
  36799. controller.update( event.inputSource, event.frame, referenceSpace );
  36800. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  36801. }
  36802. }
  36803. function onSessionEnd() {
  36804. const session = this._session;
  36805. const renderer = this._renderer;
  36806. session.removeEventListener( 'select', this._onSessionEvent );
  36807. session.removeEventListener( 'selectstart', this._onSessionEvent );
  36808. session.removeEventListener( 'selectend', this._onSessionEvent );
  36809. session.removeEventListener( 'squeeze', this._onSessionEvent );
  36810. session.removeEventListener( 'squeezestart', this._onSessionEvent );
  36811. session.removeEventListener( 'squeezeend', this._onSessionEvent );
  36812. session.removeEventListener( 'end', this._onSessionEnd );
  36813. session.removeEventListener( 'inputsourceschange', this._onInputSourcesChange );
  36814. for ( let i = 0; i < this._controllers.length; i ++ ) {
  36815. const inputSource = this._controllerInputSources[ i ];
  36816. if ( inputSource === null ) continue;
  36817. this._controllerInputSources[ i ] = null;
  36818. this._controllers[ i ].disconnect( inputSource );
  36819. }
  36820. this._currentDepthNear = null;
  36821. this._currentDepthFar = null;
  36822. // restore framebuffer/rendering state
  36823. renderer._resetXRState();
  36824. this._session = null;
  36825. this._xrRenderTarget = null;
  36826. // switch layers back to emulated
  36827. if ( this._supportsLayers === true ) {
  36828. for ( const layer of this._layers ) {
  36829. // Recreate layer render target to reset state
  36830. layer.renderTarget = new XRRenderTarget(
  36831. layer.pixelwidth,
  36832. layer.pixelheight,
  36833. {
  36834. format: RGBAFormat,
  36835. type: UnsignedByteType,
  36836. depthTexture: new DepthTexture(
  36837. layer.pixelwidth,
  36838. layer.pixelheight,
  36839. layer.stencilBuffer ? UnsignedInt248Type : UnsignedIntType,
  36840. undefined,
  36841. undefined,
  36842. undefined,
  36843. undefined,
  36844. undefined,
  36845. undefined,
  36846. layer.stencilBuffer ? DepthStencilFormat : DepthFormat
  36847. ),
  36848. stencilBuffer: layer.stencilBuffer,
  36849. resolveDepthBuffer: false,
  36850. resolveStencilBuffer: false
  36851. } );
  36852. layer.renderTarget.isXRRenderTarget = false;
  36853. layer.plane.material = layer.material;
  36854. layer.material.map = layer.renderTarget.texture;
  36855. layer.material.map.offset.y = 1;
  36856. layer.material.map.repeat.y = -1;
  36857. delete layer.xrlayer;
  36858. }
  36859. }
  36860. //
  36861. this.isPresenting = false;
  36862. this._useMultiview = false;
  36863. renderer._animation.stop();
  36864. renderer._animation.setAnimationLoop( this._currentAnimationLoop );
  36865. renderer._animation.setContext( this._currentAnimationContext );
  36866. renderer._animation.start();
  36867. renderer.setPixelRatio( this._currentPixelRatio );
  36868. renderer.setSize( this._currentSize.width, this._currentSize.height, false );
  36869. this.dispatchEvent( { type: 'sessionend' } );
  36870. }
  36871. function onInputSourcesChange( event ) {
  36872. const controllers = this._controllers;
  36873. const controllerInputSources = this._controllerInputSources;
  36874. // Notify disconnected
  36875. for ( let i = 0; i < event.removed.length; i ++ ) {
  36876. const inputSource = event.removed[ i ];
  36877. const index = controllerInputSources.indexOf( inputSource );
  36878. if ( index >= 0 ) {
  36879. controllerInputSources[ index ] = null;
  36880. controllers[ index ].disconnect( inputSource );
  36881. }
  36882. }
  36883. // Notify connected
  36884. for ( let i = 0; i < event.added.length; i ++ ) {
  36885. const inputSource = event.added[ i ];
  36886. let controllerIndex = controllerInputSources.indexOf( inputSource );
  36887. if ( controllerIndex === -1 ) {
  36888. // Assign input source a controller that currently has no input source
  36889. for ( let i = 0; i < controllers.length; i ++ ) {
  36890. if ( i >= controllerInputSources.length ) {
  36891. controllerInputSources.push( inputSource );
  36892. controllerIndex = i;
  36893. break;
  36894. } else if ( controllerInputSources[ i ] === null ) {
  36895. controllerInputSources[ i ] = inputSource;
  36896. controllerIndex = i;
  36897. break;
  36898. }
  36899. }
  36900. // If all controllers do currently receive input we ignore new ones
  36901. if ( controllerIndex === -1 ) break;
  36902. }
  36903. const controller = controllers[ controllerIndex ];
  36904. if ( controller ) {
  36905. controller.connect( inputSource );
  36906. }
  36907. }
  36908. }
  36909. // Creation method for native WebXR layers
  36910. function createXRLayer( layer ) {
  36911. if ( layer.type === 'quad' ) {
  36912. return this._glBinding.createQuadLayer( {
  36913. transform: new XRRigidTransform( layer.translation, layer.quaternion ),
  36914. width: layer.width / 2,
  36915. height: layer.height / 2,
  36916. space: this._referenceSpace,
  36917. viewPixelWidth: layer.pixelwidth,
  36918. viewPixelHeight: layer.pixelheight,
  36919. clearOnAccess: false
  36920. } );
  36921. } else {
  36922. return this._glBinding.createCylinderLayer( {
  36923. transform: new XRRigidTransform( layer.translation, layer.quaternion ),
  36924. radius: layer.radius,
  36925. centralAngle: layer.centralAngle,
  36926. aspectRatio: layer.aspectRatio,
  36927. space: this._referenceSpace,
  36928. viewPixelWidth: layer.pixelwidth,
  36929. viewPixelHeight: layer.pixelheight,
  36930. clearOnAccess: false
  36931. } );
  36932. }
  36933. }
  36934. // Animation Loop
  36935. function onAnimationFrame( time, frame ) {
  36936. if ( frame === undefined ) return;
  36937. const cameraXR = this._cameraXR;
  36938. const renderer = this._renderer;
  36939. const backend = renderer.backend;
  36940. const glBaseLayer = this._glBaseLayer;
  36941. const referenceSpace = this.getReferenceSpace();
  36942. const pose = frame.getViewerPose( referenceSpace );
  36943. this._xrFrame = frame;
  36944. if ( pose !== null ) {
  36945. const views = pose.views;
  36946. if ( this._glBaseLayer !== null ) {
  36947. backend.setXRTarget( glBaseLayer.framebuffer );
  36948. }
  36949. let cameraXRNeedsUpdate = false;
  36950. // check if it's necessary to rebuild cameraXR's camera list
  36951. if ( views.length !== cameraXR.cameras.length ) {
  36952. cameraXR.cameras.length = 0;
  36953. cameraXRNeedsUpdate = true;
  36954. }
  36955. for ( let i = 0; i < views.length; i ++ ) {
  36956. const view = views[ i ];
  36957. let viewport;
  36958. if ( this._useLayers === true ) {
  36959. const glSubImage = this._glBinding.getViewSubImage( this._glProjLayer, view );
  36960. viewport = glSubImage.viewport;
  36961. // For side-by-side projection, we only produce a single texture for both eyes.
  36962. if ( i === 0 ) {
  36963. backend.setXRRenderTargetTextures(
  36964. this._xrRenderTarget,
  36965. glSubImage.colorTexture,
  36966. ( this._glProjLayer.ignoreDepthValues && ! this._useMultiview ) ? undefined : glSubImage.depthStencilTexture
  36967. );
  36968. }
  36969. } else {
  36970. viewport = glBaseLayer.getViewport( view );
  36971. }
  36972. let camera = this._cameras[ i ];
  36973. if ( camera === undefined ) {
  36974. camera = new PerspectiveCamera();
  36975. camera.layers.enable( i );
  36976. camera.viewport = new Vector4();
  36977. this._cameras[ i ] = camera;
  36978. }
  36979. camera.matrix.fromArray( view.transform.matrix );
  36980. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  36981. camera.projectionMatrix.fromArray( view.projectionMatrix );
  36982. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  36983. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  36984. if ( i === 0 ) {
  36985. cameraXR.matrix.copy( camera.matrix );
  36986. cameraXR.matrix.decompose( cameraXR.position, cameraXR.quaternion, cameraXR.scale );
  36987. }
  36988. if ( cameraXRNeedsUpdate === true ) {
  36989. cameraXR.cameras.push( camera );
  36990. }
  36991. }
  36992. renderer.setOutputRenderTarget( this._xrRenderTarget );
  36993. }
  36994. //
  36995. for ( let i = 0; i < this._controllers.length; i ++ ) {
  36996. const inputSource = this._controllerInputSources[ i ];
  36997. const controller = this._controllers[ i ];
  36998. if ( inputSource !== null && controller !== undefined ) {
  36999. controller.update( inputSource, frame, referenceSpace );
  37000. }
  37001. }
  37002. if ( this._currentAnimationLoop ) this._currentAnimationLoop( time, frame );
  37003. if ( frame.detectedPlanes ) {
  37004. this.dispatchEvent( { type: 'planesdetected', data: frame } );
  37005. }
  37006. this._xrFrame = null;
  37007. }
  37008. const _scene = /*@__PURE__*/ new Scene();
  37009. const _drawingBufferSize = /*@__PURE__*/ new Vector2();
  37010. const _screen = /*@__PURE__*/ new Vector4();
  37011. const _frustum = /*@__PURE__*/ new Frustum();
  37012. const _frustumArray = /*@__PURE__*/ new FrustumArray();
  37013. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  37014. const _vector4 = /*@__PURE__*/ new Vector4();
  37015. /**
  37016. * Base class for renderers.
  37017. */
  37018. class Renderer {
  37019. /**
  37020. * Renderer options.
  37021. *
  37022. * @typedef {Object} Renderer~Options
  37023. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  37024. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  37025. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  37026. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  37027. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  37028. * @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
  37029. * to overwrite the default.
  37030. * @property {?Function} [getFallback=null] - This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  37031. * @property {number} [colorBufferType=HalfFloatType] - Defines the type of color buffers. The default `HalfFloatType` is recommend for best
  37032. * quality. To save memory and bandwidth, `UnsignedByteType` might be used. This will reduce rendering quality though.
  37033. * @property {boolean} [multiview=false] - If set to `true`, the renderer will use multiview during WebXR rendering if supported.
  37034. */
  37035. /**
  37036. * Constructs a new renderer.
  37037. *
  37038. * @param {Backend} backend - The backend the renderer is targeting (e.g. WebGPU or WebGL 2).
  37039. * @param {Renderer~Options} [parameters] - The configuration parameter.
  37040. */
  37041. constructor( backend, parameters = {} ) {
  37042. /**
  37043. * This flag can be used for type testing.
  37044. *
  37045. * @type {boolean}
  37046. * @readonly
  37047. * @default true
  37048. */
  37049. this.isRenderer = true;
  37050. //
  37051. const {
  37052. logarithmicDepthBuffer = false,
  37053. alpha = true,
  37054. depth = true,
  37055. stencil = false,
  37056. antialias = false,
  37057. samples = 0,
  37058. getFallback = null,
  37059. colorBufferType = HalfFloatType,
  37060. multiview = false
  37061. } = parameters;
  37062. /**
  37063. * A reference to the canvas element the renderer is drawing to.
  37064. * This value of this property will automatically be created by
  37065. * the renderer.
  37066. *
  37067. * @type {HTMLCanvasElement|OffscreenCanvas}
  37068. */
  37069. this.domElement = backend.getDomElement();
  37070. /**
  37071. * A reference to the current backend.
  37072. *
  37073. * @type {Backend}
  37074. */
  37075. this.backend = backend;
  37076. /**
  37077. * The number of MSAA samples.
  37078. *
  37079. * @type {number}
  37080. * @default 0
  37081. */
  37082. this.samples = samples || ( antialias === true ) ? 4 : 0;
  37083. /**
  37084. * Whether the renderer should automatically clear the current rendering target
  37085. * before execute a `render()` call. The target can be the canvas (default framebuffer)
  37086. * or the current bound render target (custom framebuffer).
  37087. *
  37088. * @type {boolean}
  37089. * @default true
  37090. */
  37091. this.autoClear = true;
  37092. /**
  37093. * When `autoClear` is set to `true`, this property defines whether the renderer
  37094. * should clear the color buffer.
  37095. *
  37096. * @type {boolean}
  37097. * @default true
  37098. */
  37099. this.autoClearColor = true;
  37100. /**
  37101. * When `autoClear` is set to `true`, this property defines whether the renderer
  37102. * should clear the depth buffer.
  37103. *
  37104. * @type {boolean}
  37105. * @default true
  37106. */
  37107. this.autoClearDepth = true;
  37108. /**
  37109. * When `autoClear` is set to `true`, this property defines whether the renderer
  37110. * should clear the stencil buffer.
  37111. *
  37112. * @type {boolean}
  37113. * @default true
  37114. */
  37115. this.autoClearStencil = true;
  37116. /**
  37117. * Whether the default framebuffer should be transparent or opaque.
  37118. *
  37119. * @type {boolean}
  37120. * @default true
  37121. */
  37122. this.alpha = alpha;
  37123. /**
  37124. * Whether logarithmic depth buffer is enabled or not.
  37125. *
  37126. * @type {boolean}
  37127. * @default false
  37128. */
  37129. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  37130. /**
  37131. * Defines the output color space of the renderer.
  37132. *
  37133. * @type {string}
  37134. * @default SRGBColorSpace
  37135. */
  37136. this.outputColorSpace = SRGBColorSpace;
  37137. /**
  37138. * Defines the tone mapping of the renderer.
  37139. *
  37140. * @type {number}
  37141. * @default NoToneMapping
  37142. */
  37143. this.toneMapping = NoToneMapping;
  37144. /**
  37145. * Defines the tone mapping exposure.
  37146. *
  37147. * @type {number}
  37148. * @default 1
  37149. */
  37150. this.toneMappingExposure = 1.0;
  37151. /**
  37152. * Whether the renderer should sort its render lists or not.
  37153. *
  37154. * Note: Sorting is used to attempt to properly render objects that have some degree of transparency.
  37155. * By definition, sorting objects may not work in all cases. Depending on the needs of application,
  37156. * it may be necessary to turn off sorting and use other methods to deal with transparency rendering
  37157. * e.g. manually determining each object's rendering order.
  37158. *
  37159. * @type {boolean}
  37160. * @default true
  37161. */
  37162. this.sortObjects = true;
  37163. /**
  37164. * Whether the default framebuffer should have a depth buffer or not.
  37165. *
  37166. * @type {boolean}
  37167. * @default true
  37168. */
  37169. this.depth = depth;
  37170. /**
  37171. * Whether the default framebuffer should have a stencil buffer or not.
  37172. *
  37173. * @type {boolean}
  37174. * @default false
  37175. */
  37176. this.stencil = stencil;
  37177. /**
  37178. * Holds a series of statistical information about the GPU memory
  37179. * and the rendering process. Useful for debugging and monitoring.
  37180. *
  37181. * @type {Info}
  37182. */
  37183. this.info = new Info();
  37184. /**
  37185. * Stores override nodes for specific transformations or calculations.
  37186. * These nodes can be used to replace default behavior in the rendering pipeline.
  37187. *
  37188. * @type {Object}
  37189. * @property {?Node} modelViewMatrix - An override node for the model-view matrix.
  37190. * @property {?Node} modelNormalViewMatrix - An override node for the model normal view matrix.
  37191. */
  37192. this.overrideNodes = {
  37193. modelViewMatrix: null,
  37194. modelNormalViewMatrix: null
  37195. };
  37196. /**
  37197. * The node library defines how certain library objects like materials, lights
  37198. * or tone mapping functions are mapped to node types. This is required since
  37199. * although instances of classes like `MeshBasicMaterial` or `PointLight` can
  37200. * be part of the scene graph, they are internally represented as nodes for
  37201. * further processing.
  37202. *
  37203. * @type {NodeLibrary}
  37204. */
  37205. this.library = new NodeLibrary();
  37206. /**
  37207. * A map-like data structure for managing lights.
  37208. *
  37209. * @type {Lighting}
  37210. */
  37211. this.lighting = new Lighting();
  37212. // internals
  37213. /**
  37214. * This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  37215. *
  37216. * @private
  37217. * @type {?Function}
  37218. */
  37219. this._getFallback = getFallback;
  37220. /**
  37221. * The renderer's pixel ratio.
  37222. *
  37223. * @private
  37224. * @type {number}
  37225. * @default 1
  37226. */
  37227. this._pixelRatio = 1;
  37228. /**
  37229. * The width of the renderer's default framebuffer in logical pixel unit.
  37230. *
  37231. * @private
  37232. * @type {number}
  37233. */
  37234. this._width = this.domElement.width;
  37235. /**
  37236. * The height of the renderer's default framebuffer in logical pixel unit.
  37237. *
  37238. * @private
  37239. * @type {number}
  37240. */
  37241. this._height = this.domElement.height;
  37242. /**
  37243. * The viewport of the renderer in logical pixel unit.
  37244. *
  37245. * @private
  37246. * @type {Vector4}
  37247. */
  37248. this._viewport = new Vector4( 0, 0, this._width, this._height );
  37249. /**
  37250. * The scissor rectangle of the renderer in logical pixel unit.
  37251. *
  37252. * @private
  37253. * @type {Vector4}
  37254. */
  37255. this._scissor = new Vector4( 0, 0, this._width, this._height );
  37256. /**
  37257. * Whether the scissor test should be enabled or not.
  37258. *
  37259. * @private
  37260. * @type {boolean}
  37261. */
  37262. this._scissorTest = false;
  37263. /**
  37264. * A reference to a renderer module for managing shader attributes.
  37265. *
  37266. * @private
  37267. * @type {?Attributes}
  37268. * @default null
  37269. */
  37270. this._attributes = null;
  37271. /**
  37272. * A reference to a renderer module for managing geometries.
  37273. *
  37274. * @private
  37275. * @type {?Geometries}
  37276. * @default null
  37277. */
  37278. this._geometries = null;
  37279. /**
  37280. * A reference to a renderer module for managing node related logic.
  37281. *
  37282. * @private
  37283. * @type {?Nodes}
  37284. * @default null
  37285. */
  37286. this._nodes = null;
  37287. /**
  37288. * A reference to a renderer module for managing the internal animation loop.
  37289. *
  37290. * @private
  37291. * @type {?Animation}
  37292. * @default null
  37293. */
  37294. this._animation = null;
  37295. /**
  37296. * A reference to a renderer module for managing shader program bindings.
  37297. *
  37298. * @private
  37299. * @type {?Bindings}
  37300. * @default null
  37301. */
  37302. this._bindings = null;
  37303. /**
  37304. * A reference to a renderer module for managing render objects.
  37305. *
  37306. * @private
  37307. * @type {?RenderObjects}
  37308. * @default null
  37309. */
  37310. this._objects = null;
  37311. /**
  37312. * A reference to a renderer module for managing render and compute pipelines.
  37313. *
  37314. * @private
  37315. * @type {?Pipelines}
  37316. * @default null
  37317. */
  37318. this._pipelines = null;
  37319. /**
  37320. * A reference to a renderer module for managing render bundles.
  37321. *
  37322. * @private
  37323. * @type {?RenderBundles}
  37324. * @default null
  37325. */
  37326. this._bundles = null;
  37327. /**
  37328. * A reference to a renderer module for managing render lists.
  37329. *
  37330. * @private
  37331. * @type {?RenderLists}
  37332. * @default null
  37333. */
  37334. this._renderLists = null;
  37335. /**
  37336. * A reference to a renderer module for managing render contexts.
  37337. *
  37338. * @private
  37339. * @type {?RenderContexts}
  37340. * @default null
  37341. */
  37342. this._renderContexts = null;
  37343. /**
  37344. * A reference to a renderer module for managing textures.
  37345. *
  37346. * @private
  37347. * @type {?Textures}
  37348. * @default null
  37349. */
  37350. this._textures = null;
  37351. /**
  37352. * A reference to a renderer module for backgrounds.
  37353. *
  37354. * @private
  37355. * @type {?Background}
  37356. * @default null
  37357. */
  37358. this._background = null;
  37359. /**
  37360. * This fullscreen quad is used for internal render passes
  37361. * like the tone mapping and color space output pass.
  37362. *
  37363. * @private
  37364. * @type {QuadMesh}
  37365. */
  37366. this._quad = new QuadMesh( new NodeMaterial() );
  37367. this._quad.material.name = 'Renderer_output';
  37368. /**
  37369. * A reference to the current render context.
  37370. *
  37371. * @private
  37372. * @type {?RenderContext}
  37373. * @default null
  37374. */
  37375. this._currentRenderContext = null;
  37376. /**
  37377. * A custom sort function for the opaque render list.
  37378. *
  37379. * @private
  37380. * @type {?Function}
  37381. * @default null
  37382. */
  37383. this._opaqueSort = null;
  37384. /**
  37385. * A custom sort function for the transparent render list.
  37386. *
  37387. * @private
  37388. * @type {?Function}
  37389. * @default null
  37390. */
  37391. this._transparentSort = null;
  37392. /**
  37393. * The framebuffer target.
  37394. *
  37395. * @private
  37396. * @type {?RenderTarget}
  37397. * @default null
  37398. */
  37399. this._frameBufferTarget = null;
  37400. const alphaClear = this.alpha === true ? 0 : 1;
  37401. /**
  37402. * The clear color value.
  37403. *
  37404. * @private
  37405. * @type {Color4}
  37406. */
  37407. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  37408. /**
  37409. * The clear depth value.
  37410. *
  37411. * @private
  37412. * @type {number}
  37413. * @default 1
  37414. */
  37415. this._clearDepth = 1;
  37416. /**
  37417. * The clear stencil value.
  37418. *
  37419. * @private
  37420. * @type {number}
  37421. * @default 0
  37422. */
  37423. this._clearStencil = 0;
  37424. /**
  37425. * The current render target.
  37426. *
  37427. * @private
  37428. * @type {?RenderTarget}
  37429. * @default null
  37430. */
  37431. this._renderTarget = null;
  37432. /**
  37433. * The active cube face.
  37434. *
  37435. * @private
  37436. * @type {number}
  37437. * @default 0
  37438. */
  37439. this._activeCubeFace = 0;
  37440. /**
  37441. * The active mipmap level.
  37442. *
  37443. * @private
  37444. * @type {number}
  37445. * @default 0
  37446. */
  37447. this._activeMipmapLevel = 0;
  37448. /**
  37449. * The current output render target.
  37450. *
  37451. * @private
  37452. * @type {?RenderTarget}
  37453. * @default null
  37454. */
  37455. this._outputRenderTarget = null;
  37456. /**
  37457. * The MRT setting.
  37458. *
  37459. * @private
  37460. * @type {?MRTNode}
  37461. * @default null
  37462. */
  37463. this._mrt = null;
  37464. /**
  37465. * This function defines how a render object is going
  37466. * to be rendered.
  37467. *
  37468. * @private
  37469. * @type {?Function}
  37470. * @default null
  37471. */
  37472. this._renderObjectFunction = null;
  37473. /**
  37474. * Used to keep track of the current render object function.
  37475. *
  37476. * @private
  37477. * @type {?Function}
  37478. * @default null
  37479. */
  37480. this._currentRenderObjectFunction = null;
  37481. /**
  37482. * Used to keep track of the current render bundle.
  37483. *
  37484. * @private
  37485. * @type {?RenderBundle}
  37486. * @default null
  37487. */
  37488. this._currentRenderBundle = null;
  37489. /**
  37490. * Next to `_renderObjectFunction()`, this function provides another hook
  37491. * for influencing the render process of a render object. It is meant for internal
  37492. * use and only relevant for `compileAsync()` right now. Instead of using
  37493. * the default logic of `_renderObjectDirect()` which actually draws the render object,
  37494. * a different function might be used which performs no draw but just the node
  37495. * and pipeline updates.
  37496. *
  37497. * @private
  37498. * @type {?Function}
  37499. * @default null
  37500. */
  37501. this._handleObjectFunction = this._renderObjectDirect;
  37502. /**
  37503. * Indicates whether the device has been lost or not. In WebGL terms, the device
  37504. * lost is considered as a context lost. When this is set to `true`, rendering
  37505. * isn't possible anymore.
  37506. *
  37507. * @private
  37508. * @type {boolean}
  37509. * @default false
  37510. */
  37511. this._isDeviceLost = false;
  37512. /**
  37513. * A callback function that defines what should happen when a device/context lost occurs.
  37514. *
  37515. * @type {Function}
  37516. */
  37517. this.onDeviceLost = this._onDeviceLost;
  37518. /**
  37519. * Defines the type of color buffers. The default `HalfFloatType` is recommend for
  37520. * best quality. To save memory and bandwidth, `UnsignedByteType` might be used.
  37521. * This will reduce rendering quality though.
  37522. *
  37523. * @private
  37524. * @type {number}
  37525. * @default HalfFloatType
  37526. */
  37527. this._colorBufferType = colorBufferType;
  37528. /**
  37529. * Whether the renderer has been initialized or not.
  37530. *
  37531. * @private
  37532. * @type {boolean}
  37533. * @default false
  37534. */
  37535. this._initialized = false;
  37536. /**
  37537. * A reference to the promise which initializes the renderer.
  37538. *
  37539. * @private
  37540. * @type {?Promise<this>}
  37541. * @default null
  37542. */
  37543. this._initPromise = null;
  37544. /**
  37545. * An array of compilation promises which are used in `compileAsync()`.
  37546. *
  37547. * @private
  37548. * @type {?Array<Promise>}
  37549. * @default null
  37550. */
  37551. this._compilationPromises = null;
  37552. /**
  37553. * Whether the renderer should render transparent render objects or not.
  37554. *
  37555. * @type {boolean}
  37556. * @default true
  37557. */
  37558. this.transparent = true;
  37559. /**
  37560. * Whether the renderer should render opaque render objects or not.
  37561. *
  37562. * @type {boolean}
  37563. * @default true
  37564. */
  37565. this.opaque = true;
  37566. /**
  37567. * Shadow map configuration
  37568. * @typedef {Object} ShadowMapConfig
  37569. * @property {boolean} enabled - Whether to globally enable shadows or not.
  37570. * @property {number} type - The shadow map type.
  37571. */
  37572. /**
  37573. * The renderer's shadow configuration.
  37574. *
  37575. * @type {ShadowMapConfig}
  37576. */
  37577. this.shadowMap = {
  37578. enabled: false,
  37579. type: PCFShadowMap
  37580. };
  37581. /**
  37582. * XR configuration.
  37583. * @typedef {Object} XRConfig
  37584. * @property {boolean} enabled - Whether to globally enable XR or not.
  37585. */
  37586. /**
  37587. * The renderer's XR manager.
  37588. *
  37589. * @type {XRManager}
  37590. */
  37591. this.xr = new XRManager( this, multiview );
  37592. /**
  37593. * Debug configuration.
  37594. * @typedef {Object} DebugConfig
  37595. * @property {boolean} checkShaderErrors - Whether shader errors should be checked or not.
  37596. * @property {?Function} onShaderError - A callback function that is executed when a shader error happens. Only supported with WebGL 2 right now.
  37597. * @property {Function} getShaderAsync - Allows the get the raw shader code for the given scene, camera and 3D object.
  37598. */
  37599. /**
  37600. * The renderer's debug configuration.
  37601. *
  37602. * @type {DebugConfig}
  37603. */
  37604. this.debug = {
  37605. checkShaderErrors: true,
  37606. onShaderError: null,
  37607. getShaderAsync: async ( scene, camera, object ) => {
  37608. await this.compileAsync( scene, camera );
  37609. const renderList = this._renderLists.get( scene, camera );
  37610. const renderContext = this._renderContexts.get( scene, camera, this._renderTarget );
  37611. const material = scene.overrideMaterial || object.material;
  37612. const renderObject = this._objects.get( object, material, scene, camera, renderList.lightsNode, renderContext, renderContext.clippingContext );
  37613. const { fragmentShader, vertexShader } = renderObject.getNodeBuilderState();
  37614. return { fragmentShader, vertexShader };
  37615. }
  37616. };
  37617. }
  37618. /**
  37619. * Initializes the renderer so it is ready for usage.
  37620. *
  37621. * @async
  37622. * @return {Promise<this>} A Promise that resolves when the renderer has been initialized.
  37623. */
  37624. async init() {
  37625. if ( this._initialized ) {
  37626. throw new Error( 'Renderer: Backend has already been initialized.' );
  37627. }
  37628. if ( this._initPromise !== null ) {
  37629. return this._initPromise;
  37630. }
  37631. this._initPromise = new Promise( async ( resolve, reject ) => {
  37632. let backend = this.backend;
  37633. try {
  37634. await backend.init( this );
  37635. } catch ( error ) {
  37636. if ( this._getFallback !== null ) {
  37637. // try the fallback
  37638. try {
  37639. this.backend = backend = this._getFallback( error );
  37640. await backend.init( this );
  37641. } catch ( error ) {
  37642. reject( error );
  37643. return;
  37644. }
  37645. } else {
  37646. reject( error );
  37647. return;
  37648. }
  37649. }
  37650. this._nodes = new Nodes( this, backend );
  37651. this._animation = new Animation( this._nodes, this.info );
  37652. this._attributes = new Attributes( backend );
  37653. this._background = new Background( this, this._nodes );
  37654. this._geometries = new Geometries( this._attributes, this.info );
  37655. this._textures = new Textures( this, backend, this.info );
  37656. this._pipelines = new Pipelines( backend, this._nodes );
  37657. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  37658. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  37659. this._renderLists = new RenderLists( this.lighting );
  37660. this._bundles = new RenderBundles();
  37661. this._renderContexts = new RenderContexts();
  37662. //
  37663. this._animation.start();
  37664. this._initialized = true;
  37665. resolve( this );
  37666. } );
  37667. return this._initPromise;
  37668. }
  37669. /**
  37670. * The coordinate system of the renderer. The value of this property
  37671. * depends on the selected backend. Either `THREE.WebGLCoordinateSystem` or
  37672. * `THREE.WebGPUCoordinateSystem`.
  37673. *
  37674. * @readonly
  37675. * @type {number}
  37676. */
  37677. get coordinateSystem() {
  37678. return this.backend.coordinateSystem;
  37679. }
  37680. /**
  37681. * Compiles all materials in the given scene. This can be useful to avoid a
  37682. * phenomenon which is called "shader compilation stutter", which occurs when
  37683. * rendering an object with a new shader for the first time.
  37684. *
  37685. * If you want to add a 3D object to an existing scene, use the third optional
  37686. * parameter for applying the target scene. Note that the (target) scene's lighting
  37687. * and environment must be configured before calling this method.
  37688. *
  37689. * @async
  37690. * @param {Object3D} scene - The scene or 3D object to precompile.
  37691. * @param {Camera} camera - The camera that is used to render the scene.
  37692. * @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.
  37693. * @return {Promise<Array|undefined>} A Promise that resolves when the compile has been finished.
  37694. */
  37695. async compileAsync( scene, camera, targetScene = null ) {
  37696. if ( this._isDeviceLost === true ) return;
  37697. if ( this._initialized === false ) await this.init();
  37698. // preserve render tree
  37699. const nodeFrame = this._nodes.nodeFrame;
  37700. const previousRenderId = nodeFrame.renderId;
  37701. const previousRenderContext = this._currentRenderContext;
  37702. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  37703. const previousCompilationPromises = this._compilationPromises;
  37704. //
  37705. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  37706. if ( targetScene === null ) targetScene = scene;
  37707. const renderTarget = this._renderTarget;
  37708. const renderContext = this._renderContexts.get( targetScene, camera, renderTarget );
  37709. const activeMipmapLevel = this._activeMipmapLevel;
  37710. const compilationPromises = [];
  37711. this._currentRenderContext = renderContext;
  37712. this._currentRenderObjectFunction = this.renderObject;
  37713. this._handleObjectFunction = this._createObjectPipeline;
  37714. this._compilationPromises = compilationPromises;
  37715. nodeFrame.renderId ++;
  37716. //
  37717. nodeFrame.update();
  37718. //
  37719. renderContext.depth = this.depth;
  37720. renderContext.stencil = this.stencil;
  37721. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  37722. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  37723. //
  37724. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  37725. //
  37726. const renderList = this._renderLists.get( scene, camera );
  37727. renderList.begin();
  37728. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  37729. // include lights from target scene
  37730. if ( targetScene !== scene ) {
  37731. targetScene.traverseVisible( function ( object ) {
  37732. if ( object.isLight && object.layers.test( camera.layers ) ) {
  37733. renderList.pushLight( object );
  37734. }
  37735. } );
  37736. }
  37737. renderList.finish();
  37738. //
  37739. if ( renderTarget !== null ) {
  37740. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  37741. const renderTargetData = this._textures.get( renderTarget );
  37742. renderContext.textures = renderTargetData.textures;
  37743. renderContext.depthTexture = renderTargetData.depthTexture;
  37744. } else {
  37745. renderContext.textures = null;
  37746. renderContext.depthTexture = null;
  37747. }
  37748. //
  37749. this._background.update( sceneRef, renderList, renderContext );
  37750. // process render lists
  37751. const opaqueObjects = renderList.opaque;
  37752. const transparentObjects = renderList.transparent;
  37753. const transparentDoublePassObjects = renderList.transparentDoublePass;
  37754. const lightsNode = renderList.lightsNode;
  37755. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  37756. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  37757. // restore render tree
  37758. nodeFrame.renderId = previousRenderId;
  37759. this._currentRenderContext = previousRenderContext;
  37760. this._currentRenderObjectFunction = previousRenderObjectFunction;
  37761. this._compilationPromises = previousCompilationPromises;
  37762. this._handleObjectFunction = this._renderObjectDirect;
  37763. // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete
  37764. await Promise.all( compilationPromises );
  37765. }
  37766. /**
  37767. * Renders the scene in an async fashion.
  37768. *
  37769. * @async
  37770. * @param {Object3D} scene - The scene or 3D object to render.
  37771. * @param {Camera} camera - The camera.
  37772. * @return {Promise} A Promise that resolves when the render has been finished.
  37773. */
  37774. async renderAsync( scene, camera ) {
  37775. if ( this._initialized === false ) await this.init();
  37776. this._renderScene( scene, camera );
  37777. }
  37778. /**
  37779. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  37780. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  37781. *
  37782. * @async
  37783. * @return {Promise} A Promise that resolves when synchronization has been finished.
  37784. */
  37785. async waitForGPU() {
  37786. await this.backend.waitForGPU();
  37787. }
  37788. /**
  37789. * Enables or disables high precision for model-view and normal-view matrices.
  37790. * When enabled, will use CPU 64-bit precision for higher precision instead of GPU 32-bit for higher performance.
  37791. *
  37792. * NOTE: 64-bit precision is not compatible with `InstancedMesh` and `SkinnedMesh`.
  37793. *
  37794. * @param {boolean} value - Whether to enable or disable high precision.
  37795. * @type {boolean}
  37796. */
  37797. set highPrecision( value ) {
  37798. if ( value === true ) {
  37799. this.overrideNodes.modelViewMatrix = highpModelViewMatrix;
  37800. this.overrideNodes.modelNormalViewMatrix = highpModelNormalViewMatrix;
  37801. } else if ( this.highPrecision ) {
  37802. this.overrideNodes.modelViewMatrix = null;
  37803. this.overrideNodes.modelNormalViewMatrix = null;
  37804. }
  37805. }
  37806. /**
  37807. * Returns whether high precision is enabled or not.
  37808. *
  37809. * @return {boolean} Whether high precision is enabled or not.
  37810. * @type {boolean}
  37811. */
  37812. get highPrecision() {
  37813. return this.overrideNodes.modelViewMatrix === highpModelViewMatrix && this.overrideNodes.modelNormalViewMatrix === highpModelNormalViewMatrix;
  37814. }
  37815. /**
  37816. * Sets the given MRT configuration.
  37817. *
  37818. * @param {MRTNode} mrt - The MRT node to set.
  37819. * @return {Renderer} A reference to this renderer.
  37820. */
  37821. setMRT( mrt ) {
  37822. this._mrt = mrt;
  37823. return this;
  37824. }
  37825. /**
  37826. * Returns the MRT configuration.
  37827. *
  37828. * @return {MRTNode} The MRT configuration.
  37829. */
  37830. getMRT() {
  37831. return this._mrt;
  37832. }
  37833. /**
  37834. * Returns the color buffer type.
  37835. *
  37836. * @return {number} The color buffer type.
  37837. */
  37838. getColorBufferType() {
  37839. return this._colorBufferType;
  37840. }
  37841. /**
  37842. * Default implementation of the device lost callback.
  37843. *
  37844. * @private
  37845. * @param {Object} info - Information about the context lost.
  37846. */
  37847. _onDeviceLost( info ) {
  37848. let errorMessage = `THREE.WebGPURenderer: ${info.api} Device Lost:\n\nMessage: ${info.message}`;
  37849. if ( info.reason ) {
  37850. errorMessage += `\nReason: ${info.reason}`;
  37851. }
  37852. console.error( errorMessage );
  37853. this._isDeviceLost = true;
  37854. }
  37855. /**
  37856. * Renders the given render bundle.
  37857. *
  37858. * @private
  37859. * @param {Object} bundle - Render bundle data.
  37860. * @param {Scene} sceneRef - The scene the render bundle belongs to.
  37861. * @param {LightsNode} lightsNode - The lights node.
  37862. */
  37863. _renderBundle( bundle, sceneRef, lightsNode ) {
  37864. const { bundleGroup, camera, renderList } = bundle;
  37865. const renderContext = this._currentRenderContext;
  37866. //
  37867. const renderBundle = this._bundles.get( bundleGroup, camera );
  37868. const renderBundleData = this.backend.get( renderBundle );
  37869. if ( renderBundleData.renderContexts === undefined ) renderBundleData.renderContexts = new Set();
  37870. //
  37871. const needsUpdate = bundleGroup.version !== renderBundleData.version;
  37872. const renderBundleNeedsUpdate = renderBundleData.renderContexts.has( renderContext ) === false || needsUpdate;
  37873. renderBundleData.renderContexts.add( renderContext );
  37874. if ( renderBundleNeedsUpdate ) {
  37875. this.backend.beginBundle( renderContext );
  37876. if ( renderBundleData.renderObjects === undefined || needsUpdate ) {
  37877. renderBundleData.renderObjects = [];
  37878. }
  37879. this._currentRenderBundle = renderBundle;
  37880. const {
  37881. transparentDoublePass: transparentDoublePassObjects,
  37882. transparent: transparentObjects,
  37883. opaque: opaqueObjects
  37884. } = renderList;
  37885. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  37886. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  37887. this._currentRenderBundle = null;
  37888. //
  37889. this.backend.finishBundle( renderContext, renderBundle );
  37890. renderBundleData.version = bundleGroup.version;
  37891. } else {
  37892. const { renderObjects } = renderBundleData;
  37893. for ( let i = 0, l = renderObjects.length; i < l; i ++ ) {
  37894. const renderObject = renderObjects[ i ];
  37895. if ( this._nodes.needsRefresh( renderObject ) ) {
  37896. this._nodes.updateBefore( renderObject );
  37897. this._nodes.updateForRender( renderObject );
  37898. this._bindings.updateForRender( renderObject );
  37899. this._nodes.updateAfter( renderObject );
  37900. }
  37901. }
  37902. }
  37903. this.backend.addBundle( renderContext, renderBundle );
  37904. }
  37905. /**
  37906. * Renders the scene or 3D object with the given camera. This method can only be called
  37907. * if the renderer has been initialized.
  37908. *
  37909. * The target of the method is the default framebuffer (meaning the canvas)
  37910. * or alternatively a render target when specified via `setRenderTarget()`.
  37911. *
  37912. * @param {Object3D} scene - The scene or 3D object to render.
  37913. * @param {Camera} camera - The camera to render the scene with.
  37914. * @return {?Promise} A Promise that resolve when the scene has been rendered.
  37915. * Only returned when the renderer has not been initialized.
  37916. */
  37917. render( scene, camera ) {
  37918. if ( this._initialized === false ) {
  37919. console.warn( 'THREE.Renderer: .render() called before the backend is initialized. Try using .renderAsync() instead.' );
  37920. return this.renderAsync( scene, camera );
  37921. }
  37922. this._renderScene( scene, camera );
  37923. }
  37924. /**
  37925. * Returns an internal render target which is used when computing the output tone mapping
  37926. * and color space conversion. Unlike in `WebGLRenderer`, this is done in a separate render
  37927. * pass and not inline to achieve more correct results.
  37928. *
  37929. * @private
  37930. * @return {?RenderTarget} The render target. The method returns `null` if no output conversion should be applied.
  37931. */
  37932. _getFrameBufferTarget() {
  37933. const { currentToneMapping, currentColorSpace } = this;
  37934. const useToneMapping = currentToneMapping !== NoToneMapping;
  37935. const useColorSpace = currentColorSpace !== LinearSRGBColorSpace;
  37936. if ( useToneMapping === false && useColorSpace === false ) return null;
  37937. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  37938. const { depth, stencil } = this;
  37939. let frameBufferTarget = this._frameBufferTarget;
  37940. if ( frameBufferTarget === null ) {
  37941. frameBufferTarget = new RenderTarget( width, height, {
  37942. depthBuffer: depth,
  37943. stencilBuffer: stencil,
  37944. type: this._colorBufferType,
  37945. format: RGBAFormat,
  37946. colorSpace: LinearSRGBColorSpace,
  37947. generateMipmaps: false,
  37948. minFilter: LinearFilter,
  37949. magFilter: LinearFilter,
  37950. samples: this.samples
  37951. } );
  37952. frameBufferTarget.isPostProcessingRenderTarget = true;
  37953. this._frameBufferTarget = frameBufferTarget;
  37954. }
  37955. const outputRenderTarget = this.getOutputRenderTarget();
  37956. frameBufferTarget.depthBuffer = depth;
  37957. frameBufferTarget.stencilBuffer = stencil;
  37958. if ( outputRenderTarget !== null ) {
  37959. frameBufferTarget.setSize( outputRenderTarget.width, outputRenderTarget.height, outputRenderTarget.depth );
  37960. } else {
  37961. frameBufferTarget.setSize( width, height, 1 );
  37962. }
  37963. frameBufferTarget.viewport.copy( this._viewport );
  37964. frameBufferTarget.scissor.copy( this._scissor );
  37965. frameBufferTarget.viewport.multiplyScalar( this._pixelRatio );
  37966. frameBufferTarget.scissor.multiplyScalar( this._pixelRatio );
  37967. frameBufferTarget.scissorTest = this._scissorTest;
  37968. frameBufferTarget.multiview = outputRenderTarget !== null ? outputRenderTarget.multiview : false;
  37969. frameBufferTarget.resolveDepthBuffer = outputRenderTarget !== null ? outputRenderTarget.resolveDepthBuffer : true;
  37970. frameBufferTarget._autoAllocateDepthBuffer = outputRenderTarget !== null ? outputRenderTarget._autoAllocateDepthBuffer : false;
  37971. return frameBufferTarget;
  37972. }
  37973. /**
  37974. * Renders the scene or 3D object with the given camera.
  37975. *
  37976. * @private
  37977. * @param {Object3D} scene - The scene or 3D object to render.
  37978. * @param {Camera} camera - The camera to render the scene with.
  37979. * @param {boolean} [useFrameBufferTarget=true] - Whether to use a framebuffer target or not.
  37980. * @return {RenderContext} The current render context.
  37981. */
  37982. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  37983. if ( this._isDeviceLost === true ) return;
  37984. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  37985. // preserve render tree
  37986. const nodeFrame = this._nodes.nodeFrame;
  37987. const previousRenderId = nodeFrame.renderId;
  37988. const previousRenderContext = this._currentRenderContext;
  37989. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  37990. //
  37991. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  37992. const outputRenderTarget = this._renderTarget || this._outputRenderTarget;
  37993. const activeCubeFace = this._activeCubeFace;
  37994. const activeMipmapLevel = this._activeMipmapLevel;
  37995. //
  37996. let renderTarget;
  37997. if ( frameBufferTarget !== null ) {
  37998. renderTarget = frameBufferTarget;
  37999. this.setRenderTarget( renderTarget );
  38000. } else {
  38001. renderTarget = outputRenderTarget;
  38002. }
  38003. //
  38004. const renderContext = this._renderContexts.get( scene, camera, renderTarget );
  38005. this._currentRenderContext = renderContext;
  38006. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  38007. //
  38008. this.info.calls ++;
  38009. this.info.render.calls ++;
  38010. this.info.render.frameCalls ++;
  38011. nodeFrame.renderId = this.info.calls;
  38012. //
  38013. const coordinateSystem = this.coordinateSystem;
  38014. const xr = this.xr;
  38015. if ( camera.coordinateSystem !== coordinateSystem && xr.isPresenting === false ) {
  38016. camera.coordinateSystem = coordinateSystem;
  38017. camera.updateProjectionMatrix();
  38018. if ( camera.isArrayCamera ) {
  38019. for ( const subCamera of camera.cameras ) {
  38020. subCamera.coordinateSystem = coordinateSystem;
  38021. subCamera.updateProjectionMatrix();
  38022. }
  38023. }
  38024. }
  38025. //
  38026. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  38027. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  38028. if ( xr.enabled === true && xr.isPresenting === true ) {
  38029. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  38030. camera = xr.getCamera(); // use XR camera for rendering
  38031. }
  38032. //
  38033. let viewport = this._viewport;
  38034. let scissor = this._scissor;
  38035. let pixelRatio = this._pixelRatio;
  38036. if ( renderTarget !== null ) {
  38037. viewport = renderTarget.viewport;
  38038. scissor = renderTarget.scissor;
  38039. pixelRatio = 1;
  38040. }
  38041. this.getDrawingBufferSize( _drawingBufferSize );
  38042. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  38043. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  38044. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  38045. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  38046. renderContext.viewportValue.width >>= activeMipmapLevel;
  38047. renderContext.viewportValue.height >>= activeMipmapLevel;
  38048. renderContext.viewportValue.minDepth = minDepth;
  38049. renderContext.viewportValue.maxDepth = maxDepth;
  38050. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  38051. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  38052. renderContext.scissor = this._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  38053. renderContext.scissorValue.width >>= activeMipmapLevel;
  38054. renderContext.scissorValue.height >>= activeMipmapLevel;
  38055. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  38056. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  38057. //
  38058. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  38059. //
  38060. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  38061. if ( ! camera.isArrayCamera ) {
  38062. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  38063. frustum.setFromProjectionMatrix( _projScreenMatrix, coordinateSystem );
  38064. }
  38065. const renderList = this._renderLists.get( scene, camera );
  38066. renderList.begin();
  38067. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  38068. renderList.finish();
  38069. if ( this.sortObjects === true ) {
  38070. renderList.sort( this._opaqueSort, this._transparentSort );
  38071. }
  38072. //
  38073. if ( renderTarget !== null ) {
  38074. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  38075. const renderTargetData = this._textures.get( renderTarget );
  38076. renderContext.textures = renderTargetData.textures;
  38077. renderContext.depthTexture = renderTargetData.depthTexture;
  38078. renderContext.width = renderTargetData.width;
  38079. renderContext.height = renderTargetData.height;
  38080. renderContext.renderTarget = renderTarget;
  38081. renderContext.depth = renderTarget.depthBuffer;
  38082. renderContext.stencil = renderTarget.stencilBuffer;
  38083. } else {
  38084. renderContext.textures = null;
  38085. renderContext.depthTexture = null;
  38086. renderContext.width = this.domElement.width;
  38087. renderContext.height = this.domElement.height;
  38088. renderContext.depth = this.depth;
  38089. renderContext.stencil = this.stencil;
  38090. }
  38091. renderContext.width >>= activeMipmapLevel;
  38092. renderContext.height >>= activeMipmapLevel;
  38093. renderContext.activeCubeFace = activeCubeFace;
  38094. renderContext.activeMipmapLevel = activeMipmapLevel;
  38095. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  38096. //
  38097. this._background.update( sceneRef, renderList, renderContext );
  38098. //
  38099. renderContext.camera = camera;
  38100. this.backend.beginRender( renderContext );
  38101. // process render lists
  38102. const {
  38103. bundles,
  38104. lightsNode,
  38105. transparentDoublePass: transparentDoublePassObjects,
  38106. transparent: transparentObjects,
  38107. opaque: opaqueObjects
  38108. } = renderList;
  38109. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  38110. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  38111. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  38112. // finish render pass
  38113. this.backend.finishRender( renderContext );
  38114. // restore render tree
  38115. nodeFrame.renderId = previousRenderId;
  38116. this._currentRenderContext = previousRenderContext;
  38117. this._currentRenderObjectFunction = previousRenderObjectFunction;
  38118. //
  38119. if ( frameBufferTarget !== null ) {
  38120. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  38121. this._renderOutput( renderTarget );
  38122. }
  38123. //
  38124. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  38125. //
  38126. return renderContext;
  38127. }
  38128. _setXRLayerSize( width, height ) {
  38129. this._width = width;
  38130. this._height = height;
  38131. this.setViewport( 0, 0, width, height );
  38132. }
  38133. /**
  38134. * The output pass performs tone mapping and color space conversion.
  38135. *
  38136. * @private
  38137. * @param {RenderTarget} renderTarget - The current render target.
  38138. */
  38139. _renderOutput( renderTarget ) {
  38140. const quad = this._quad;
  38141. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  38142. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  38143. quad.material.needsUpdate = true;
  38144. }
  38145. // a clear operation clears the intermediate renderTarget texture, but should not update the screen canvas.
  38146. const currentAutoClear = this.autoClear;
  38147. const currentXR = this.xr.enabled;
  38148. this.autoClear = false;
  38149. this.xr.enabled = false;
  38150. this._renderScene( quad, quad.camera, false );
  38151. this.autoClear = currentAutoClear;
  38152. this.xr.enabled = currentXR;
  38153. }
  38154. /**
  38155. * Returns the maximum available anisotropy for texture filtering.
  38156. *
  38157. * @return {number} The maximum available anisotropy.
  38158. */
  38159. getMaxAnisotropy() {
  38160. return this.backend.getMaxAnisotropy();
  38161. }
  38162. /**
  38163. * Returns the active cube face.
  38164. *
  38165. * @return {number} The active cube face.
  38166. */
  38167. getActiveCubeFace() {
  38168. return this._activeCubeFace;
  38169. }
  38170. /**
  38171. * Returns the active mipmap level.
  38172. *
  38173. * @return {number} The active mipmap level.
  38174. */
  38175. getActiveMipmapLevel() {
  38176. return this._activeMipmapLevel;
  38177. }
  38178. /**
  38179. * Applications are advised to always define the animation loop
  38180. * with this method and not manually with `requestAnimationFrame()`
  38181. * for best compatibility.
  38182. *
  38183. * @async
  38184. * @param {?Function} callback - The application's animation loop.
  38185. * @return {Promise} A Promise that resolves when the set has been executed.
  38186. */
  38187. async setAnimationLoop( callback ) {
  38188. if ( this._initialized === false ) await this.init();
  38189. this._animation.setAnimationLoop( callback );
  38190. }
  38191. /**
  38192. * Can be used to transfer buffer data from a storage buffer attribute
  38193. * from the GPU to the CPU in context of compute shaders.
  38194. *
  38195. * @async
  38196. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  38197. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  38198. */
  38199. async getArrayBufferAsync( attribute ) {
  38200. return await this.backend.getArrayBufferAsync( attribute );
  38201. }
  38202. /**
  38203. * Returns the rendering context.
  38204. *
  38205. * @return {GPUCanvasContext|WebGL2RenderingContext} The rendering context.
  38206. */
  38207. getContext() {
  38208. return this.backend.getContext();
  38209. }
  38210. /**
  38211. * Returns the pixel ratio.
  38212. *
  38213. * @return {number} The pixel ratio.
  38214. */
  38215. getPixelRatio() {
  38216. return this._pixelRatio;
  38217. }
  38218. /**
  38219. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  38220. *
  38221. * @param {Vector2} target - The method writes the result in this target object.
  38222. * @return {Vector2} The drawing buffer size.
  38223. */
  38224. getDrawingBufferSize( target ) {
  38225. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  38226. }
  38227. /**
  38228. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  38229. *
  38230. * @param {Vector2} target - The method writes the result in this target object.
  38231. * @return {Vector2} The renderer's size in logical pixels.
  38232. */
  38233. getSize( target ) {
  38234. return target.set( this._width, this._height );
  38235. }
  38236. /**
  38237. * Sets the given pixel ratio and resizes the canvas if necessary.
  38238. *
  38239. * @param {number} [value=1] - The pixel ratio.
  38240. */
  38241. setPixelRatio( value = 1 ) {
  38242. if ( this._pixelRatio === value ) return;
  38243. this._pixelRatio = value;
  38244. this.setSize( this._width, this._height, false );
  38245. }
  38246. /**
  38247. * This method allows to define the drawing buffer size by specifying
  38248. * width, height and pixel ratio all at once. The size of the drawing
  38249. * buffer is computed with this formula:
  38250. * ```js
  38251. * size.x = width * pixelRatio;
  38252. * size.y = height * pixelRatio;
  38253. * ```
  38254. *
  38255. * @param {number} width - The width in logical pixels.
  38256. * @param {number} height - The height in logical pixels.
  38257. * @param {number} pixelRatio - The pixel ratio.
  38258. */
  38259. setDrawingBufferSize( width, height, pixelRatio ) {
  38260. // Renderer can't be resized while presenting in XR.
  38261. if ( this.xr && this.xr.isPresenting ) return;
  38262. this._width = width;
  38263. this._height = height;
  38264. this._pixelRatio = pixelRatio;
  38265. this.domElement.width = Math.floor( width * pixelRatio );
  38266. this.domElement.height = Math.floor( height * pixelRatio );
  38267. this.setViewport( 0, 0, width, height );
  38268. if ( this._initialized ) this.backend.updateSize();
  38269. }
  38270. /**
  38271. * Sets the size of the renderer.
  38272. *
  38273. * @param {number} width - The width in logical pixels.
  38274. * @param {number} height - The height in logical pixels.
  38275. * @param {boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  38276. */
  38277. setSize( width, height, updateStyle = true ) {
  38278. // Renderer can't be resized while presenting in XR.
  38279. if ( this.xr && this.xr.isPresenting ) return;
  38280. this._width = width;
  38281. this._height = height;
  38282. this.domElement.width = Math.floor( width * this._pixelRatio );
  38283. this.domElement.height = Math.floor( height * this._pixelRatio );
  38284. if ( updateStyle === true ) {
  38285. this.domElement.style.width = width + 'px';
  38286. this.domElement.style.height = height + 'px';
  38287. }
  38288. this.setViewport( 0, 0, width, height );
  38289. if ( this._initialized ) this.backend.updateSize();
  38290. }
  38291. /**
  38292. * Defines a manual sort function for the opaque render list.
  38293. * Pass `null` to use the default sort.
  38294. *
  38295. * @param {Function} method - The sort function.
  38296. */
  38297. setOpaqueSort( method ) {
  38298. this._opaqueSort = method;
  38299. }
  38300. /**
  38301. * Defines a manual sort function for the transparent render list.
  38302. * Pass `null` to use the default sort.
  38303. *
  38304. * @param {Function} method - The sort function.
  38305. */
  38306. setTransparentSort( method ) {
  38307. this._transparentSort = method;
  38308. }
  38309. /**
  38310. * Returns the scissor rectangle.
  38311. *
  38312. * @param {Vector4} target - The method writes the result in this target object.
  38313. * @return {Vector4} The scissor rectangle.
  38314. */
  38315. getScissor( target ) {
  38316. const scissor = this._scissor;
  38317. target.x = scissor.x;
  38318. target.y = scissor.y;
  38319. target.width = scissor.width;
  38320. target.height = scissor.height;
  38321. return target;
  38322. }
  38323. /**
  38324. * Defines the scissor rectangle.
  38325. *
  38326. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  38327. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  38328. * @param {number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  38329. * @param {number} width - The width of the scissor box in logical pixel unit.
  38330. * @param {number} height - The height of the scissor box in logical pixel unit.
  38331. */
  38332. setScissor( x, y, width, height ) {
  38333. const scissor = this._scissor;
  38334. if ( x.isVector4 ) {
  38335. scissor.copy( x );
  38336. } else {
  38337. scissor.set( x, y, width, height );
  38338. }
  38339. }
  38340. /**
  38341. * Returns the scissor test value.
  38342. *
  38343. * @return {boolean} Whether the scissor test should be enabled or not.
  38344. */
  38345. getScissorTest() {
  38346. return this._scissorTest;
  38347. }
  38348. /**
  38349. * Defines the scissor test.
  38350. *
  38351. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  38352. */
  38353. setScissorTest( boolean ) {
  38354. this._scissorTest = boolean;
  38355. this.backend.setScissorTest( boolean );
  38356. }
  38357. /**
  38358. * Returns the viewport definition.
  38359. *
  38360. * @param {Vector4} target - The method writes the result in this target object.
  38361. * @return {Vector4} The viewport definition.
  38362. */
  38363. getViewport( target ) {
  38364. return target.copy( this._viewport );
  38365. }
  38366. /**
  38367. * Defines the viewport.
  38368. *
  38369. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  38370. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  38371. * @param {number} width - The width of the viewport in logical pixel unit.
  38372. * @param {number} height - The height of the viewport in logical pixel unit.
  38373. * @param {number} minDepth - The minimum depth value of the viewport. WebGPU only.
  38374. * @param {number} maxDepth - The maximum depth value of the viewport. WebGPU only.
  38375. */
  38376. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  38377. const viewport = this._viewport;
  38378. if ( x.isVector4 ) {
  38379. viewport.copy( x );
  38380. } else {
  38381. viewport.set( x, y, width, height );
  38382. }
  38383. viewport.minDepth = minDepth;
  38384. viewport.maxDepth = maxDepth;
  38385. }
  38386. /**
  38387. * Returns the clear color.
  38388. *
  38389. * @param {Color} target - The method writes the result in this target object.
  38390. * @return {Color} The clear color.
  38391. */
  38392. getClearColor( target ) {
  38393. return target.copy( this._clearColor );
  38394. }
  38395. /**
  38396. * Defines the clear color and optionally the clear alpha.
  38397. *
  38398. * @param {Color} color - The clear color.
  38399. * @param {number} [alpha=1] - The clear alpha.
  38400. */
  38401. setClearColor( color, alpha = 1 ) {
  38402. this._clearColor.set( color );
  38403. this._clearColor.a = alpha;
  38404. }
  38405. /**
  38406. * Returns the clear alpha.
  38407. *
  38408. * @return {number} The clear alpha.
  38409. */
  38410. getClearAlpha() {
  38411. return this._clearColor.a;
  38412. }
  38413. /**
  38414. * Defines the clear alpha.
  38415. *
  38416. * @param {number} alpha - The clear alpha.
  38417. */
  38418. setClearAlpha( alpha ) {
  38419. this._clearColor.a = alpha;
  38420. }
  38421. /**
  38422. * Returns the clear depth.
  38423. *
  38424. * @return {number} The clear depth.
  38425. */
  38426. getClearDepth() {
  38427. return this._clearDepth;
  38428. }
  38429. /**
  38430. * Defines the clear depth.
  38431. *
  38432. * @param {number} depth - The clear depth.
  38433. */
  38434. setClearDepth( depth ) {
  38435. this._clearDepth = depth;
  38436. }
  38437. /**
  38438. * Returns the clear stencil.
  38439. *
  38440. * @return {number} The clear stencil.
  38441. */
  38442. getClearStencil() {
  38443. return this._clearStencil;
  38444. }
  38445. /**
  38446. * Defines the clear stencil.
  38447. *
  38448. * @param {number} stencil - The clear stencil.
  38449. */
  38450. setClearStencil( stencil ) {
  38451. this._clearStencil = stencil;
  38452. }
  38453. /**
  38454. * This method performs an occlusion query for the given 3D object.
  38455. * It returns `true` if the given 3D object is fully occluded by other
  38456. * 3D objects in the scene.
  38457. *
  38458. * @param {Object3D} object - The 3D object to test.
  38459. * @return {boolean} Whether the 3D object is fully occluded or not.
  38460. */
  38461. isOccluded( object ) {
  38462. const renderContext = this._currentRenderContext;
  38463. return renderContext && this.backend.isOccluded( renderContext, object );
  38464. }
  38465. /**
  38466. * Performs a manual clear operation. This method ignores `autoClear` properties.
  38467. *
  38468. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  38469. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  38470. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  38471. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  38472. * Only returned when the renderer has not been initialized.
  38473. */
  38474. clear( color = true, depth = true, stencil = true ) {
  38475. if ( this._initialized === false ) {
  38476. console.warn( 'THREE.Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead.' );
  38477. return this.clearAsync( color, depth, stencil );
  38478. }
  38479. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  38480. let renderContext = null;
  38481. if ( renderTarget !== null ) {
  38482. this._textures.updateRenderTarget( renderTarget );
  38483. const renderTargetData = this._textures.get( renderTarget );
  38484. renderContext = this._renderContexts.getForClear( renderTarget );
  38485. renderContext.textures = renderTargetData.textures;
  38486. renderContext.depthTexture = renderTargetData.depthTexture;
  38487. renderContext.width = renderTargetData.width;
  38488. renderContext.height = renderTargetData.height;
  38489. renderContext.renderTarget = renderTarget;
  38490. renderContext.depth = renderTarget.depthBuffer;
  38491. renderContext.stencil = renderTarget.stencilBuffer;
  38492. // #30329
  38493. renderContext.clearColorValue = this.backend.getClearColor();
  38494. renderContext.activeCubeFace = this.getActiveCubeFace();
  38495. renderContext.activeMipmapLevel = this.getActiveMipmapLevel();
  38496. }
  38497. this.backend.clear( color, depth, stencil, renderContext );
  38498. if ( renderTarget !== null && this._renderTarget === null ) {
  38499. this._renderOutput( renderTarget );
  38500. }
  38501. }
  38502. /**
  38503. * Performs a manual clear operation of the color buffer. This method ignores `autoClear` properties.
  38504. *
  38505. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  38506. * Only returned when the renderer has not been initialized.
  38507. */
  38508. clearColor() {
  38509. return this.clear( true, false, false );
  38510. }
  38511. /**
  38512. * Performs a manual clear operation of the depth buffer. This method ignores `autoClear` properties.
  38513. *
  38514. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  38515. * Only returned when the renderer has not been initialized.
  38516. */
  38517. clearDepth() {
  38518. return this.clear( false, true, false );
  38519. }
  38520. /**
  38521. * Performs a manual clear operation of the stencil buffer. This method ignores `autoClear` properties.
  38522. *
  38523. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  38524. * Only returned when the renderer has not been initialized.
  38525. */
  38526. clearStencil() {
  38527. return this.clear( false, false, true );
  38528. }
  38529. /**
  38530. * Async version of {@link Renderer#clear}.
  38531. *
  38532. * @async
  38533. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  38534. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  38535. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  38536. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  38537. */
  38538. async clearAsync( color = true, depth = true, stencil = true ) {
  38539. if ( this._initialized === false ) await this.init();
  38540. this.clear( color, depth, stencil );
  38541. }
  38542. /**
  38543. * Async version of {@link Renderer#clearColor}.
  38544. *
  38545. * @async
  38546. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  38547. */
  38548. async clearColorAsync() {
  38549. this.clearAsync( true, false, false );
  38550. }
  38551. /**
  38552. * Async version of {@link Renderer#clearDepth}.
  38553. *
  38554. * @async
  38555. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  38556. */
  38557. async clearDepthAsync() {
  38558. this.clearAsync( false, true, false );
  38559. }
  38560. /**
  38561. * Async version of {@link Renderer#clearStencil}.
  38562. *
  38563. * @async
  38564. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  38565. */
  38566. async clearStencilAsync() {
  38567. this.clearAsync( false, false, true );
  38568. }
  38569. /**
  38570. * The current output tone mapping of the renderer. When a render target is set,
  38571. * the output tone mapping is always `NoToneMapping`.
  38572. *
  38573. * @type {number}
  38574. */
  38575. get currentToneMapping() {
  38576. return this.isOutputTarget ? this.toneMapping : NoToneMapping;
  38577. }
  38578. /**
  38579. * The current output color space of the renderer. When a render target is set,
  38580. * the output color space is always `LinearSRGBColorSpace`.
  38581. *
  38582. * @type {string}
  38583. */
  38584. get currentColorSpace() {
  38585. return this.isOutputTarget ? this.outputColorSpace : LinearSRGBColorSpace;
  38586. }
  38587. /**
  38588. * Returns `true` if the rendering settings are set to screen output.
  38589. *
  38590. * @returns {boolean} True if the current render target is the same of output render target or `null`, otherwise false.
  38591. */
  38592. get isOutputTarget() {
  38593. return this._renderTarget === this._outputRenderTarget || this._renderTarget === null;
  38594. }
  38595. /**
  38596. * Frees all internal resources of the renderer. Call this method if the renderer
  38597. * is no longer in use by your app.
  38598. */
  38599. dispose() {
  38600. this.info.dispose();
  38601. this.backend.dispose();
  38602. this._animation.dispose();
  38603. this._objects.dispose();
  38604. this._pipelines.dispose();
  38605. this._nodes.dispose();
  38606. this._bindings.dispose();
  38607. this._renderLists.dispose();
  38608. this._renderContexts.dispose();
  38609. this._textures.dispose();
  38610. if ( this._frameBufferTarget !== null ) this._frameBufferTarget.dispose();
  38611. Object.values( this.backend.timestampQueryPool ).forEach( queryPool => {
  38612. if ( queryPool !== null ) queryPool.dispose();
  38613. } );
  38614. this.setRenderTarget( null );
  38615. this.setAnimationLoop( null );
  38616. }
  38617. /**
  38618. * Sets the given render target. Calling this method means the renderer does not
  38619. * target the default framebuffer (meaning the canvas) anymore but a custom framebuffer.
  38620. * Use `null` as the first argument to reset the state.
  38621. *
  38622. * @param {?RenderTarget} renderTarget - The render target to set.
  38623. * @param {number} [activeCubeFace=0] - The active cube face.
  38624. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  38625. */
  38626. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  38627. this._renderTarget = renderTarget;
  38628. this._activeCubeFace = activeCubeFace;
  38629. this._activeMipmapLevel = activeMipmapLevel;
  38630. }
  38631. /**
  38632. * Returns the current render target.
  38633. *
  38634. * @return {?RenderTarget} The render target. Returns `null` if no render target is set.
  38635. */
  38636. getRenderTarget() {
  38637. return this._renderTarget;
  38638. }
  38639. /**
  38640. * Sets the output render target for the renderer.
  38641. *
  38642. * @param {Object} renderTarget - The render target to set as the output target.
  38643. */
  38644. setOutputRenderTarget( renderTarget ) {
  38645. this._outputRenderTarget = renderTarget;
  38646. }
  38647. /**
  38648. * Returns the current output target.
  38649. *
  38650. * @return {?RenderTarget} The current output render target. Returns `null` if no output target is set.
  38651. */
  38652. getOutputRenderTarget() {
  38653. return this._outputRenderTarget;
  38654. }
  38655. /**
  38656. * Resets the renderer to the initial state before WebXR started.
  38657. *
  38658. */
  38659. _resetXRState() {
  38660. this.backend.setXRTarget( null );
  38661. this.setOutputRenderTarget( null );
  38662. this.setRenderTarget( null );
  38663. this._frameBufferTarget.dispose();
  38664. this._frameBufferTarget = null;
  38665. }
  38666. /**
  38667. * Callback for {@link Renderer#setRenderObjectFunction}.
  38668. *
  38669. * @callback renderObjectFunction
  38670. * @param {Object3D} object - The 3D object.
  38671. * @param {Scene} scene - The scene the 3D object belongs to.
  38672. * @param {Camera} camera - The camera the object should be rendered with.
  38673. * @param {BufferGeometry} geometry - The object's geometry.
  38674. * @param {Material} material - The object's material.
  38675. * @param {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  38676. * @param {LightsNode} lightsNode - The current lights node.
  38677. * @param {ClippingContext} clippingContext - The clipping context.
  38678. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  38679. */
  38680. /**
  38681. * Sets the given render object function. Calling this method overwrites the default implementation
  38682. * which is {@link Renderer#renderObject}. Defining a custom function can be useful
  38683. * if you want to modify the way objects are rendered. For example you can define things like "every
  38684. * object that has material of a certain type should perform a pre-pass with a special overwrite material".
  38685. * The custom function must always call `renderObject()` in its implementation.
  38686. *
  38687. * Use `null` as the first argument to reset the state.
  38688. *
  38689. * @param {?renderObjectFunction} renderObjectFunction - The render object function.
  38690. */
  38691. setRenderObjectFunction( renderObjectFunction ) {
  38692. this._renderObjectFunction = renderObjectFunction;
  38693. }
  38694. /**
  38695. * Returns the current render object function.
  38696. *
  38697. * @return {?Function} The current render object function. Returns `null` if no function is set.
  38698. */
  38699. getRenderObjectFunction() {
  38700. return this._renderObjectFunction;
  38701. }
  38702. /**
  38703. * Execute a single or an array of compute nodes. This method can only be called
  38704. * if the renderer has been initialized.
  38705. *
  38706. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  38707. * @param {Array<number>|number} [dispatchSizeOrCount=null] - Array with [ x, y, z ] values for dispatch or a single number for the count.
  38708. * @return {Promise|undefined} A Promise that resolve when the compute has finished. Only returned when the renderer has not been initialized.
  38709. */
  38710. compute( computeNodes, dispatchSizeOrCount = null ) {
  38711. if ( this._isDeviceLost === true ) return;
  38712. if ( this._initialized === false ) {
  38713. console.warn( 'THREE.Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead.' );
  38714. return this.computeAsync( computeNodes );
  38715. }
  38716. //
  38717. const nodeFrame = this._nodes.nodeFrame;
  38718. const previousRenderId = nodeFrame.renderId;
  38719. //
  38720. this.info.calls ++;
  38721. this.info.compute.calls ++;
  38722. this.info.compute.frameCalls ++;
  38723. nodeFrame.renderId = this.info.calls;
  38724. //
  38725. const backend = this.backend;
  38726. const pipelines = this._pipelines;
  38727. const bindings = this._bindings;
  38728. const nodes = this._nodes;
  38729. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  38730. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  38731. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  38732. }
  38733. backend.beginCompute( computeNodes );
  38734. for ( const computeNode of computeList ) {
  38735. // onInit
  38736. if ( pipelines.has( computeNode ) === false ) {
  38737. const dispose = () => {
  38738. computeNode.removeEventListener( 'dispose', dispose );
  38739. pipelines.delete( computeNode );
  38740. bindings.delete( computeNode );
  38741. nodes.delete( computeNode );
  38742. };
  38743. computeNode.addEventListener( 'dispose', dispose );
  38744. //
  38745. const onInitFn = computeNode.onInitFunction;
  38746. if ( onInitFn !== null ) {
  38747. onInitFn.call( computeNode, { renderer: this } );
  38748. }
  38749. }
  38750. nodes.updateForCompute( computeNode );
  38751. bindings.updateForCompute( computeNode );
  38752. const computeBindings = bindings.getForCompute( computeNode );
  38753. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  38754. backend.compute( computeNodes, computeNode, computeBindings, computePipeline, dispatchSizeOrCount );
  38755. }
  38756. backend.finishCompute( computeNodes );
  38757. //
  38758. nodeFrame.renderId = previousRenderId;
  38759. }
  38760. /**
  38761. * Execute a single or an array of compute nodes.
  38762. *
  38763. * @async
  38764. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  38765. * @param {Array<number>|number} [dispatchSizeOrCount=null] - Array with [ x, y, z ] values for dispatch or a single number for the count.
  38766. * @return {Promise} A Promise that resolve when the compute has finished.
  38767. */
  38768. async computeAsync( computeNodes, dispatchSizeOrCount = null ) {
  38769. if ( this._initialized === false ) await this.init();
  38770. this.compute( computeNodes, dispatchSizeOrCount );
  38771. }
  38772. /**
  38773. * Checks if the given feature is supported by the selected backend.
  38774. *
  38775. * @async
  38776. * @param {string} name - The feature's name.
  38777. * @return {Promise<boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  38778. */
  38779. async hasFeatureAsync( name ) {
  38780. if ( this._initialized === false ) await this.init();
  38781. return this.backend.hasFeature( name );
  38782. }
  38783. async resolveTimestampsAsync( type = 'render' ) {
  38784. if ( this._initialized === false ) await this.init();
  38785. return this.backend.resolveTimestampsAsync( type );
  38786. }
  38787. /**
  38788. * Checks if the given feature is supported by the selected backend. If the
  38789. * renderer has not been initialized, this method always returns `false`.
  38790. *
  38791. * @param {string} name - The feature's name.
  38792. * @return {boolean} Whether the feature is supported or not.
  38793. */
  38794. hasFeature( name ) {
  38795. if ( this._initialized === false ) {
  38796. console.warn( 'THREE.Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead.' );
  38797. return false;
  38798. }
  38799. return this.backend.hasFeature( name );
  38800. }
  38801. /**
  38802. * Returns `true` when the renderer has been initialized.
  38803. *
  38804. * @return {boolean} Whether the renderer has been initialized or not.
  38805. */
  38806. hasInitialized() {
  38807. return this._initialized;
  38808. }
  38809. /**
  38810. * Initializes the given textures. Useful for preloading a texture rather than waiting until first render
  38811. * (which can cause noticeable lags due to decode and GPU upload overhead).
  38812. *
  38813. * @async
  38814. * @param {Texture} texture - The texture.
  38815. * @return {Promise} A Promise that resolves when the texture has been initialized.
  38816. */
  38817. async initTextureAsync( texture ) {
  38818. if ( this._initialized === false ) await this.init();
  38819. this._textures.updateTexture( texture );
  38820. }
  38821. /**
  38822. * Initializes the given texture. Useful for preloading a texture rather than waiting until first render
  38823. * (which can cause noticeable lags due to decode and GPU upload overhead).
  38824. *
  38825. * This method can only be used if the renderer has been initialized.
  38826. *
  38827. * @param {Texture} texture - The texture.
  38828. */
  38829. initTexture( texture ) {
  38830. if ( this._initialized === false ) {
  38831. console.warn( 'THREE.Renderer: .initTexture() called before the backend is initialized. Try using .initTextureAsync() instead.' );
  38832. }
  38833. this._textures.updateTexture( texture );
  38834. }
  38835. /**
  38836. * Copies the current bound framebuffer into the given texture.
  38837. *
  38838. * @param {FramebufferTexture} framebufferTexture - The texture.
  38839. * @param {?Vector2|Vector4} [rectangle=null] - A two or four dimensional vector that defines the rectangular portion of the framebuffer that should be copied.
  38840. */
  38841. copyFramebufferToTexture( framebufferTexture, rectangle = null ) {
  38842. if ( rectangle !== null ) {
  38843. if ( rectangle.isVector2 ) {
  38844. rectangle = _vector4.set( rectangle.x, rectangle.y, framebufferTexture.image.width, framebufferTexture.image.height ).floor();
  38845. } else if ( rectangle.isVector4 ) {
  38846. rectangle = _vector4.copy( rectangle ).floor();
  38847. } else {
  38848. console.error( 'THREE.Renderer.copyFramebufferToTexture: Invalid rectangle.' );
  38849. return;
  38850. }
  38851. } else {
  38852. rectangle = _vector4.set( 0, 0, framebufferTexture.image.width, framebufferTexture.image.height );
  38853. }
  38854. //
  38855. let renderContext = this._currentRenderContext;
  38856. let renderTarget;
  38857. if ( renderContext !== null ) {
  38858. renderTarget = renderContext.renderTarget;
  38859. } else {
  38860. renderTarget = this._renderTarget || this._getFrameBufferTarget();
  38861. if ( renderTarget !== null ) {
  38862. this._textures.updateRenderTarget( renderTarget );
  38863. renderContext = this._textures.get( renderTarget );
  38864. }
  38865. }
  38866. //
  38867. this._textures.updateTexture( framebufferTexture, { renderTarget } );
  38868. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext, rectangle );
  38869. }
  38870. /**
  38871. * Copies data of the given source texture into a destination texture.
  38872. *
  38873. * @param {Texture} srcTexture - The source texture.
  38874. * @param {Texture} dstTexture - The destination texture.
  38875. * @param {Box2|Box3} [srcRegion=null] - A bounding box which describes the source region. Can be two or three-dimensional.
  38876. * @param {Vector2|Vector3} [dstPosition=null] - A vector that represents the origin of the destination region. Can be two or three-dimensional.
  38877. * @param {number} [srcLevel=0] - The source mip level to copy from.
  38878. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  38879. */
  38880. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  38881. this._textures.updateTexture( srcTexture );
  38882. this._textures.updateTexture( dstTexture );
  38883. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, srcLevel, dstLevel );
  38884. }
  38885. /**
  38886. * Reads pixel data from the given render target.
  38887. *
  38888. * @async
  38889. * @param {RenderTarget} renderTarget - The render target to read from.
  38890. * @param {number} x - The `x` coordinate of the copy region's origin.
  38891. * @param {number} y - The `y` coordinate of the copy region's origin.
  38892. * @param {number} width - The width of the copy region.
  38893. * @param {number} height - The height of the copy region.
  38894. * @param {number} [textureIndex=0] - The texture index of a MRT render target.
  38895. * @param {number} [faceIndex=0] - The active cube face index.
  38896. * @return {Promise<TypedArray>} A Promise that resolves when the read has been finished. The resolve provides the read data as a typed array.
  38897. */
  38898. async readRenderTargetPixelsAsync( renderTarget, x, y, width, height, textureIndex = 0, faceIndex = 0 ) {
  38899. return this.backend.copyTextureToBuffer( renderTarget.textures[ textureIndex ], x, y, width, height, faceIndex );
  38900. }
  38901. /**
  38902. * Analyzes the given 3D object's hierarchy and builds render lists from the
  38903. * processed hierarchy.
  38904. *
  38905. * @param {Object3D} object - The 3D object to process (usually a scene).
  38906. * @param {Camera} camera - The camera the object is rendered with.
  38907. * @param {number} groupOrder - The group order is derived from the `renderOrder` of groups and is used to group 3D objects within groups.
  38908. * @param {RenderList} renderList - The current render list.
  38909. * @param {ClippingContext} clippingContext - The current clipping context.
  38910. */
  38911. _projectObject( object, camera, groupOrder, renderList, clippingContext ) {
  38912. if ( object.visible === false ) return;
  38913. const visible = object.layers.test( camera.layers );
  38914. if ( visible ) {
  38915. if ( object.isGroup ) {
  38916. groupOrder = object.renderOrder;
  38917. if ( object.isClippingGroup && object.enabled ) clippingContext = clippingContext.getGroupContext( object );
  38918. } else if ( object.isLOD ) {
  38919. if ( object.autoUpdate === true ) object.update( camera );
  38920. } else if ( object.isLight ) {
  38921. renderList.pushLight( object );
  38922. } else if ( object.isSprite ) {
  38923. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  38924. if ( ! object.frustumCulled || frustum.intersectsSprite( object, camera ) ) {
  38925. if ( this.sortObjects === true ) {
  38926. _vector4.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  38927. }
  38928. const { geometry, material } = object;
  38929. if ( material.visible ) {
  38930. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  38931. }
  38932. }
  38933. } else if ( object.isLineLoop ) {
  38934. console.error( 'THREE.Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  38935. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  38936. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  38937. if ( ! object.frustumCulled || frustum.intersectsObject( object, camera ) ) {
  38938. const { geometry, material } = object;
  38939. if ( this.sortObjects === true ) {
  38940. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  38941. _vector4
  38942. .copy( geometry.boundingSphere.center )
  38943. .applyMatrix4( object.matrixWorld )
  38944. .applyMatrix4( _projScreenMatrix );
  38945. }
  38946. if ( Array.isArray( material ) ) {
  38947. const groups = geometry.groups;
  38948. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  38949. const group = groups[ i ];
  38950. const groupMaterial = material[ group.materialIndex ];
  38951. if ( groupMaterial && groupMaterial.visible ) {
  38952. renderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group, clippingContext );
  38953. }
  38954. }
  38955. } else if ( material.visible ) {
  38956. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  38957. }
  38958. }
  38959. }
  38960. }
  38961. if ( object.isBundleGroup === true && this.backend.beginBundle !== undefined ) {
  38962. const baseRenderList = renderList;
  38963. // replace render list
  38964. renderList = this._renderLists.get( object, camera );
  38965. renderList.begin();
  38966. baseRenderList.pushBundle( {
  38967. bundleGroup: object,
  38968. camera,
  38969. renderList,
  38970. } );
  38971. renderList.finish();
  38972. }
  38973. const children = object.children;
  38974. for ( let i = 0, l = children.length; i < l; i ++ ) {
  38975. this._projectObject( children[ i ], camera, groupOrder, renderList, clippingContext );
  38976. }
  38977. }
  38978. /**
  38979. * Renders the given render bundles.
  38980. *
  38981. * @private
  38982. * @param {Array<Object>} bundles - Array with render bundle data.
  38983. * @param {Scene} sceneRef - The scene the render bundles belong to.
  38984. * @param {LightsNode} lightsNode - The current lights node.
  38985. */
  38986. _renderBundles( bundles, sceneRef, lightsNode ) {
  38987. for ( const bundle of bundles ) {
  38988. this._renderBundle( bundle, sceneRef, lightsNode );
  38989. }
  38990. }
  38991. /**
  38992. * Renders the transparent objects from the given render lists.
  38993. *
  38994. * @private
  38995. * @param {Array<Object>} renderList - The transparent render list.
  38996. * @param {Array<Object>} doublePassList - The list of transparent objects which require a double pass (e.g. because of transmission).
  38997. * @param {Camera} camera - The camera the render list should be rendered with.
  38998. * @param {Scene} scene - The scene the render list belongs to.
  38999. * @param {LightsNode} lightsNode - The current lights node.
  39000. */
  39001. _renderTransparents( renderList, doublePassList, camera, scene, lightsNode ) {
  39002. if ( doublePassList.length > 0 ) {
  39003. // render back side
  39004. for ( const { material } of doublePassList ) {
  39005. material.side = BackSide;
  39006. }
  39007. this._renderObjects( doublePassList, camera, scene, lightsNode, 'backSide' );
  39008. // render front side
  39009. for ( const { material } of doublePassList ) {
  39010. material.side = FrontSide;
  39011. }
  39012. this._renderObjects( renderList, camera, scene, lightsNode );
  39013. // restore
  39014. for ( const { material } of doublePassList ) {
  39015. material.side = DoubleSide;
  39016. }
  39017. } else {
  39018. this._renderObjects( renderList, camera, scene, lightsNode );
  39019. }
  39020. }
  39021. /**
  39022. * Renders the objects from the given render list.
  39023. *
  39024. * @private
  39025. * @param {Array<Object>} renderList - The render list.
  39026. * @param {Camera} camera - The camera the render list should be rendered with.
  39027. * @param {Scene} scene - The scene the render list belongs to.
  39028. * @param {LightsNode} lightsNode - The current lights node.
  39029. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  39030. */
  39031. _renderObjects( renderList, camera, scene, lightsNode, passId = null ) {
  39032. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  39033. const { object, geometry, material, group, clippingContext } = renderList[ i ];
  39034. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode, clippingContext, passId );
  39035. }
  39036. }
  39037. /**
  39038. * This method represents the default render object function that manages the render lifecycle
  39039. * of the object.
  39040. *
  39041. * @param {Object3D} object - The 3D object.
  39042. * @param {Scene} scene - The scene the 3D object belongs to.
  39043. * @param {Camera} camera - The camera the object should be rendered with.
  39044. * @param {BufferGeometry} geometry - The object's geometry.
  39045. * @param {Material} material - The object's material.
  39046. * @param {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  39047. * @param {LightsNode} lightsNode - The current lights node.
  39048. * @param {?ClippingContext} clippingContext - The clipping context.
  39049. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  39050. */
  39051. renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext = null, passId = null ) {
  39052. let overridePositionNode;
  39053. let overrideColorNode;
  39054. let overrideDepthNode;
  39055. //
  39056. object.onBeforeRender( this, scene, camera, geometry, material, group );
  39057. //
  39058. if ( material.allowOverride === true && scene.overrideMaterial !== null ) {
  39059. const overrideMaterial = scene.overrideMaterial;
  39060. if ( material.positionNode && material.positionNode.isNode ) {
  39061. overridePositionNode = overrideMaterial.positionNode;
  39062. overrideMaterial.positionNode = material.positionNode;
  39063. }
  39064. overrideMaterial.alphaTest = material.alphaTest;
  39065. overrideMaterial.alphaMap = material.alphaMap;
  39066. overrideMaterial.transparent = material.transparent || material.transmission > 0;
  39067. if ( overrideMaterial.isShadowPassMaterial ) {
  39068. overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide;
  39069. if ( material.depthNode && material.depthNode.isNode ) {
  39070. overrideDepthNode = overrideMaterial.depthNode;
  39071. overrideMaterial.depthNode = material.depthNode;
  39072. }
  39073. if ( material.castShadowNode && material.castShadowNode.isNode ) {
  39074. overrideColorNode = overrideMaterial.colorNode;
  39075. overrideMaterial.colorNode = material.castShadowNode;
  39076. }
  39077. if ( material.castShadowPositionNode && material.castShadowPositionNode.isNode ) {
  39078. overridePositionNode = overrideMaterial.positionNode;
  39079. overrideMaterial.positionNode = material.castShadowPositionNode;
  39080. }
  39081. }
  39082. material = overrideMaterial;
  39083. }
  39084. //
  39085. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  39086. material.side = BackSide;
  39087. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, 'backSide' ); // create backSide pass id
  39088. material.side = FrontSide;
  39089. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId ); // use default pass id
  39090. material.side = DoubleSide;
  39091. } else {
  39092. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId );
  39093. }
  39094. //
  39095. if ( overridePositionNode !== undefined ) {
  39096. scene.overrideMaterial.positionNode = overridePositionNode;
  39097. }
  39098. if ( overrideDepthNode !== undefined ) {
  39099. scene.overrideMaterial.depthNode = overrideDepthNode;
  39100. }
  39101. if ( overrideColorNode !== undefined ) {
  39102. scene.overrideMaterial.colorNode = overrideColorNode;
  39103. }
  39104. //
  39105. object.onAfterRender( this, scene, camera, geometry, material, group );
  39106. }
  39107. /**
  39108. * This method represents the default `_handleObjectFunction` implementation which creates
  39109. * a render object from the given data and performs the draw command with the selected backend.
  39110. *
  39111. * @private
  39112. * @param {Object3D} object - The 3D object.
  39113. * @param {Material} material - The object's material.
  39114. * @param {Scene} scene - The scene the 3D object belongs to.
  39115. * @param {Camera} camera - The camera the object should be rendered with.
  39116. * @param {LightsNode} lightsNode - The current lights node.
  39117. * @param {?{start: number, count: number}} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  39118. * @param {ClippingContext} clippingContext - The clipping context.
  39119. * @param {string} [passId] - An optional ID for identifying the pass.
  39120. */
  39121. _renderObjectDirect( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  39122. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  39123. renderObject.drawRange = object.geometry.drawRange;
  39124. renderObject.group = group;
  39125. //
  39126. const needsRefresh = this._nodes.needsRefresh( renderObject );
  39127. if ( needsRefresh ) {
  39128. this._nodes.updateBefore( renderObject );
  39129. this._geometries.updateForRender( renderObject );
  39130. this._nodes.updateForRender( renderObject );
  39131. this._bindings.updateForRender( renderObject );
  39132. }
  39133. this._pipelines.updateForRender( renderObject );
  39134. //
  39135. if ( this._currentRenderBundle !== null ) {
  39136. const renderBundleData = this.backend.get( this._currentRenderBundle );
  39137. renderBundleData.renderObjects.push( renderObject );
  39138. renderObject.bundle = this._currentRenderBundle.bundleGroup;
  39139. }
  39140. this.backend.draw( renderObject, this.info );
  39141. if ( needsRefresh ) this._nodes.updateAfter( renderObject );
  39142. }
  39143. /**
  39144. * A different implementation for `_handleObjectFunction` which only makes sure the object is ready for rendering.
  39145. * Used in `compileAsync()`.
  39146. *
  39147. * @private
  39148. * @param {Object3D} object - The 3D object.
  39149. * @param {Material} material - The object's material.
  39150. * @param {Scene} scene - The scene the 3D object belongs to.
  39151. * @param {Camera} camera - The camera the object should be rendered with.
  39152. * @param {LightsNode} lightsNode - The current lights node.
  39153. * @param {?{start: number, count: number}} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  39154. * @param {ClippingContext} clippingContext - The clipping context.
  39155. * @param {string} [passId] - An optional ID for identifying the pass.
  39156. */
  39157. _createObjectPipeline( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  39158. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  39159. renderObject.drawRange = object.geometry.drawRange;
  39160. renderObject.group = group;
  39161. //
  39162. this._nodes.updateBefore( renderObject );
  39163. this._geometries.updateForRender( renderObject );
  39164. this._nodes.updateForRender( renderObject );
  39165. this._bindings.updateForRender( renderObject );
  39166. this._pipelines.getForRender( renderObject, this._compilationPromises );
  39167. this._nodes.updateAfter( renderObject );
  39168. }
  39169. /**
  39170. * Alias for `compileAsync()`.
  39171. *
  39172. * @method
  39173. * @param {Object3D} scene - The scene or 3D object to precompile.
  39174. * @param {Camera} camera - The camera that is used to render the scene.
  39175. * @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.
  39176. * @return {function(Object3D, Camera, ?Scene): Promise|undefined} A Promise that resolves when the compile has been finished.
  39177. */
  39178. get compile() {
  39179. return this.compileAsync;
  39180. }
  39181. }
  39182. /**
  39183. * A binding represents the connection between a resource (like a texture, sampler
  39184. * or uniform buffer) and the resource definition in a shader stage.
  39185. *
  39186. * This module is an abstract base class for all concrete bindings types.
  39187. *
  39188. * @abstract
  39189. * @private
  39190. */
  39191. class Binding {
  39192. /**
  39193. * Constructs a new binding.
  39194. *
  39195. * @param {string} [name=''] - The binding's name.
  39196. */
  39197. constructor( name = '' ) {
  39198. /**
  39199. * The binding's name.
  39200. *
  39201. * @type {string}
  39202. */
  39203. this.name = name;
  39204. /**
  39205. * A bitmask that defines in what shader stages the
  39206. * binding's resource is accessible.
  39207. *
  39208. * @type {number}
  39209. */
  39210. this.visibility = 0;
  39211. }
  39212. /**
  39213. * Makes sure binding's resource is visible for the given shader stage.
  39214. *
  39215. * @param {number} visibility - The shader stage.
  39216. */
  39217. setVisibility( visibility ) {
  39218. this.visibility |= visibility;
  39219. }
  39220. /**
  39221. * Clones the binding.
  39222. *
  39223. * @return {Binding} The cloned binding.
  39224. */
  39225. clone() {
  39226. return Object.assign( new this.constructor(), this );
  39227. }
  39228. }
  39229. /**
  39230. * This function is usually called with the length in bytes of an array buffer.
  39231. * It returns an padded value which ensure chunk size alignment according to STD140 layout.
  39232. *
  39233. * @function
  39234. * @param {number} floatLength - The buffer length.
  39235. * @return {number} The padded length.
  39236. */
  39237. function getFloatLength( floatLength ) {
  39238. // ensure chunk size alignment (STD140 layout)
  39239. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  39240. }
  39241. /**
  39242. * Represents a buffer binding type.
  39243. *
  39244. * @private
  39245. * @abstract
  39246. * @augments Binding
  39247. */
  39248. class Buffer extends Binding {
  39249. /**
  39250. * Constructs a new buffer.
  39251. *
  39252. * @param {string} name - The buffer's name.
  39253. * @param {TypedArray} [buffer=null] - The buffer.
  39254. */
  39255. constructor( name, buffer = null ) {
  39256. super( name );
  39257. /**
  39258. * This flag can be used for type testing.
  39259. *
  39260. * @type {boolean}
  39261. * @readonly
  39262. * @default true
  39263. */
  39264. this.isBuffer = true;
  39265. /**
  39266. * The bytes per element.
  39267. *
  39268. * @type {number}
  39269. */
  39270. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  39271. /**
  39272. * A reference to the internal buffer.
  39273. *
  39274. * @private
  39275. * @type {TypedArray}
  39276. */
  39277. this._buffer = buffer;
  39278. }
  39279. /**
  39280. * The buffer's byte length.
  39281. *
  39282. * @type {number}
  39283. * @readonly
  39284. */
  39285. get byteLength() {
  39286. return getFloatLength( this._buffer.byteLength );
  39287. }
  39288. /**
  39289. * A reference to the internal buffer.
  39290. *
  39291. * @type {Float32Array}
  39292. * @readonly
  39293. */
  39294. get buffer() {
  39295. return this._buffer;
  39296. }
  39297. /**
  39298. * Updates the binding.
  39299. *
  39300. * @return {boolean} Whether the buffer has been updated and must be
  39301. * uploaded to the GPU.
  39302. */
  39303. update() {
  39304. return true;
  39305. }
  39306. }
  39307. /**
  39308. * Represents a uniform buffer binding type.
  39309. *
  39310. * @private
  39311. * @augments Buffer
  39312. */
  39313. class UniformBuffer extends Buffer {
  39314. /**
  39315. * Constructs a new uniform buffer.
  39316. *
  39317. * @param {string} name - The buffer's name.
  39318. * @param {TypedArray} [buffer=null] - The buffer.
  39319. */
  39320. constructor( name, buffer = null ) {
  39321. super( name, buffer );
  39322. /**
  39323. * This flag can be used for type testing.
  39324. *
  39325. * @type {boolean}
  39326. * @readonly
  39327. * @default true
  39328. */
  39329. this.isUniformBuffer = true;
  39330. }
  39331. }
  39332. let _id$4 = 0;
  39333. /**
  39334. * A special form of uniform buffer binding type.
  39335. * It's buffer value is managed by a node object.
  39336. *
  39337. * @private
  39338. * @augments UniformBuffer
  39339. */
  39340. class NodeUniformBuffer extends UniformBuffer {
  39341. /**
  39342. * Constructs a new node-based uniform buffer.
  39343. *
  39344. * @param {BufferNode} nodeUniform - The uniform buffer node.
  39345. * @param {UniformGroupNode} groupNode - The uniform group node.
  39346. */
  39347. constructor( nodeUniform, groupNode ) {
  39348. super( 'UniformBuffer_' + _id$4 ++, nodeUniform ? nodeUniform.value : null );
  39349. /**
  39350. * The uniform buffer node.
  39351. *
  39352. * @type {BufferNode}
  39353. */
  39354. this.nodeUniform = nodeUniform;
  39355. /**
  39356. * The uniform group node.
  39357. *
  39358. * @type {UniformGroupNode}
  39359. */
  39360. this.groupNode = groupNode;
  39361. }
  39362. /**
  39363. * The uniform buffer.
  39364. *
  39365. * @type {Float32Array}
  39366. */
  39367. get buffer() {
  39368. return this.nodeUniform.value;
  39369. }
  39370. }
  39371. /**
  39372. * This class represents a uniform buffer binding but with
  39373. * an API that allows to maintain individual uniform objects.
  39374. *
  39375. * @private
  39376. * @augments UniformBuffer
  39377. */
  39378. class UniformsGroup extends UniformBuffer {
  39379. /**
  39380. * Constructs a new uniforms group.
  39381. *
  39382. * @param {string} name - The group's name.
  39383. */
  39384. constructor( name ) {
  39385. super( name );
  39386. /**
  39387. * This flag can be used for type testing.
  39388. *
  39389. * @type {boolean}
  39390. * @readonly
  39391. * @default true
  39392. */
  39393. this.isUniformsGroup = true;
  39394. /**
  39395. * An array with the raw uniform values.
  39396. *
  39397. * @private
  39398. * @type {?Array<number>}
  39399. * @default null
  39400. */
  39401. this._values = null;
  39402. /**
  39403. * An array of uniform objects.
  39404. *
  39405. * The order of uniforms in this array must match the order of uniforms in the shader.
  39406. *
  39407. * @type {Array<Uniform>}
  39408. */
  39409. this.uniforms = [];
  39410. }
  39411. /**
  39412. * Adds a uniform to this group.
  39413. *
  39414. * @param {Uniform} uniform - The uniform to add.
  39415. * @return {UniformsGroup} A reference to this group.
  39416. */
  39417. addUniform( uniform ) {
  39418. this.uniforms.push( uniform );
  39419. return this;
  39420. }
  39421. /**
  39422. * Removes a uniform from this group.
  39423. *
  39424. * @param {Uniform} uniform - The uniform to remove.
  39425. * @return {UniformsGroup} A reference to this group.
  39426. */
  39427. removeUniform( uniform ) {
  39428. const index = this.uniforms.indexOf( uniform );
  39429. if ( index !== -1 ) {
  39430. this.uniforms.splice( index, 1 );
  39431. }
  39432. return this;
  39433. }
  39434. /**
  39435. * An array with the raw uniform values.
  39436. *
  39437. * @type {Array<number>}
  39438. */
  39439. get values() {
  39440. if ( this._values === null ) {
  39441. this._values = Array.from( this.buffer );
  39442. }
  39443. return this._values;
  39444. }
  39445. /**
  39446. * A Float32 array buffer with the uniform values.
  39447. *
  39448. * @type {Float32Array}
  39449. */
  39450. get buffer() {
  39451. let buffer = this._buffer;
  39452. if ( buffer === null ) {
  39453. const byteLength = this.byteLength;
  39454. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  39455. this._buffer = buffer;
  39456. }
  39457. return buffer;
  39458. }
  39459. /**
  39460. * The byte length of the buffer with correct buffer alignment.
  39461. *
  39462. * @type {number}
  39463. */
  39464. get byteLength() {
  39465. const bytesPerElement = this.bytesPerElement;
  39466. let offset = 0; // global buffer offset in bytes
  39467. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  39468. const uniform = this.uniforms[ i ];
  39469. const boundary = uniform.boundary;
  39470. const itemSize = uniform.itemSize * bytesPerElement; // size of the uniform in bytes
  39471. const chunkOffset = offset % GPU_CHUNK_BYTES; // offset in the current chunk
  39472. const chunkPadding = chunkOffset % boundary; // required padding to match boundary
  39473. const chunkStart = chunkOffset + chunkPadding; // start position in the current chunk for the data
  39474. offset += chunkPadding;
  39475. // Check for chunk overflow
  39476. if ( chunkStart !== 0 && ( GPU_CHUNK_BYTES - chunkStart ) < itemSize ) {
  39477. // Add padding to the end of the chunk
  39478. offset += ( GPU_CHUNK_BYTES - chunkStart );
  39479. }
  39480. uniform.offset = offset / bytesPerElement;
  39481. offset += itemSize;
  39482. }
  39483. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  39484. }
  39485. /**
  39486. * Updates this group by updating each uniform object of
  39487. * the internal uniform list. The uniform objects check if their
  39488. * values has actually changed so this method only returns
  39489. * `true` if there is a real value change.
  39490. *
  39491. * @return {boolean} Whether the uniforms have been updated and
  39492. * must be uploaded to the GPU.
  39493. */
  39494. update() {
  39495. let updated = false;
  39496. for ( const uniform of this.uniforms ) {
  39497. if ( this.updateByType( uniform ) === true ) {
  39498. updated = true;
  39499. }
  39500. }
  39501. return updated;
  39502. }
  39503. /**
  39504. * Updates a given uniform by calling an update method matching
  39505. * the uniforms type.
  39506. *
  39507. * @param {Uniform} uniform - The uniform to update.
  39508. * @return {boolean} Whether the uniform has been updated or not.
  39509. */
  39510. updateByType( uniform ) {
  39511. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  39512. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  39513. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  39514. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  39515. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  39516. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  39517. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  39518. console.error( 'THREE.WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  39519. }
  39520. /**
  39521. * Updates a given Number uniform.
  39522. *
  39523. * @param {NumberUniform} uniform - The Number uniform.
  39524. * @return {boolean} Whether the uniform has been updated or not.
  39525. */
  39526. updateNumber( uniform ) {
  39527. let updated = false;
  39528. const a = this.values;
  39529. const v = uniform.getValue();
  39530. const offset = uniform.offset;
  39531. const type = uniform.getType();
  39532. if ( a[ offset ] !== v ) {
  39533. const b = this._getBufferForType( type );
  39534. b[ offset ] = a[ offset ] = v;
  39535. updated = true;
  39536. }
  39537. return updated;
  39538. }
  39539. /**
  39540. * Updates a given Vector2 uniform.
  39541. *
  39542. * @param {Vector2Uniform} uniform - The Vector2 uniform.
  39543. * @return {boolean} Whether the uniform has been updated or not.
  39544. */
  39545. updateVector2( uniform ) {
  39546. let updated = false;
  39547. const a = this.values;
  39548. const v = uniform.getValue();
  39549. const offset = uniform.offset;
  39550. const type = uniform.getType();
  39551. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  39552. const b = this._getBufferForType( type );
  39553. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  39554. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  39555. updated = true;
  39556. }
  39557. return updated;
  39558. }
  39559. /**
  39560. * Updates a given Vector3 uniform.
  39561. *
  39562. * @param {Vector3Uniform} uniform - The Vector3 uniform.
  39563. * @return {boolean} Whether the uniform has been updated or not.
  39564. */
  39565. updateVector3( uniform ) {
  39566. let updated = false;
  39567. const a = this.values;
  39568. const v = uniform.getValue();
  39569. const offset = uniform.offset;
  39570. const type = uniform.getType();
  39571. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  39572. const b = this._getBufferForType( type );
  39573. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  39574. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  39575. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  39576. updated = true;
  39577. }
  39578. return updated;
  39579. }
  39580. /**
  39581. * Updates a given Vector4 uniform.
  39582. *
  39583. * @param {Vector4Uniform} uniform - The Vector4 uniform.
  39584. * @return {boolean} Whether the uniform has been updated or not.
  39585. */
  39586. updateVector4( uniform ) {
  39587. let updated = false;
  39588. const a = this.values;
  39589. const v = uniform.getValue();
  39590. const offset = uniform.offset;
  39591. const type = uniform.getType();
  39592. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 4 ] !== v.w ) {
  39593. const b = this._getBufferForType( type );
  39594. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  39595. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  39596. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  39597. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  39598. updated = true;
  39599. }
  39600. return updated;
  39601. }
  39602. /**
  39603. * Updates a given Color uniform.
  39604. *
  39605. * @param {ColorUniform} uniform - The Color uniform.
  39606. * @return {boolean} Whether the uniform has been updated or not.
  39607. */
  39608. updateColor( uniform ) {
  39609. let updated = false;
  39610. const a = this.values;
  39611. const c = uniform.getValue();
  39612. const offset = uniform.offset;
  39613. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  39614. const b = this.buffer;
  39615. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  39616. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  39617. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  39618. updated = true;
  39619. }
  39620. return updated;
  39621. }
  39622. /**
  39623. * Updates a given Matrix3 uniform.
  39624. *
  39625. * @param {Matrix3Uniform} uniform - The Matrix3 uniform.
  39626. * @return {boolean} Whether the uniform has been updated or not.
  39627. */
  39628. updateMatrix3( uniform ) {
  39629. let updated = false;
  39630. const a = this.values;
  39631. const e = uniform.getValue().elements;
  39632. const offset = uniform.offset;
  39633. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  39634. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  39635. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  39636. const b = this.buffer;
  39637. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  39638. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  39639. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  39640. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  39641. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  39642. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  39643. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  39644. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  39645. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  39646. updated = true;
  39647. }
  39648. return updated;
  39649. }
  39650. /**
  39651. * Updates a given Matrix4 uniform.
  39652. *
  39653. * @param {Matrix4Uniform} uniform - The Matrix4 uniform.
  39654. * @return {boolean} Whether the uniform has been updated or not.
  39655. */
  39656. updateMatrix4( uniform ) {
  39657. let updated = false;
  39658. const a = this.values;
  39659. const e = uniform.getValue().elements;
  39660. const offset = uniform.offset;
  39661. if ( arraysEqual( a, e, offset ) === false ) {
  39662. const b = this.buffer;
  39663. b.set( e, offset );
  39664. setArray( a, e, offset );
  39665. updated = true;
  39666. }
  39667. return updated;
  39668. }
  39669. /**
  39670. * Returns a typed array that matches the given data type.
  39671. *
  39672. * @param {string} type - The data type.
  39673. * @return {TypedArray} The typed array.
  39674. */
  39675. _getBufferForType( type ) {
  39676. if ( type === 'int' || type === 'ivec2' || type === 'ivec3' || type === 'ivec4' ) return new Int32Array( this.buffer.buffer );
  39677. if ( type === 'uint' || type === 'uvec2' || type === 'uvec3' || type === 'uvec4' ) return new Uint32Array( this.buffer.buffer );
  39678. return this.buffer;
  39679. }
  39680. }
  39681. /**
  39682. * Sets the values of the second array to the first array.
  39683. *
  39684. * @private
  39685. * @param {TypedArray} a - The first array.
  39686. * @param {TypedArray} b - The second array.
  39687. * @param {number} offset - An index offset for the first array.
  39688. */
  39689. function setArray( a, b, offset ) {
  39690. for ( let i = 0, l = b.length; i < l; i ++ ) {
  39691. a[ offset + i ] = b[ i ];
  39692. }
  39693. }
  39694. /**
  39695. * Returns `true` if the given arrays are equal.
  39696. *
  39697. * @private
  39698. * @param {TypedArray} a - The first array.
  39699. * @param {TypedArray} b - The second array.
  39700. * @param {number} offset - An index offset for the first array.
  39701. * @return {boolean} Whether the given arrays are equal or not.
  39702. */
  39703. function arraysEqual( a, b, offset ) {
  39704. for ( let i = 0, l = b.length; i < l; i ++ ) {
  39705. if ( a[ offset + i ] !== b[ i ] ) return false;
  39706. }
  39707. return true;
  39708. }
  39709. let _id$3 = 0;
  39710. /**
  39711. * A special form of uniforms group that represents
  39712. * the individual uniforms as node-based uniforms.
  39713. *
  39714. * @private
  39715. * @augments UniformsGroup
  39716. */
  39717. class NodeUniformsGroup extends UniformsGroup {
  39718. /**
  39719. * Constructs a new node-based uniforms group.
  39720. *
  39721. * @param {string} name - The group's name.
  39722. * @param {UniformGroupNode} groupNode - The uniform group node.
  39723. */
  39724. constructor( name, groupNode ) {
  39725. super( name );
  39726. /**
  39727. * The group's ID.
  39728. *
  39729. * @type {number}
  39730. */
  39731. this.id = _id$3 ++;
  39732. /**
  39733. * The uniform group node.
  39734. *
  39735. * @type {UniformGroupNode}
  39736. */
  39737. this.groupNode = groupNode;
  39738. /**
  39739. * This flag can be used for type testing.
  39740. *
  39741. * @type {boolean}
  39742. * @readonly
  39743. * @default true
  39744. */
  39745. this.isNodeUniformsGroup = true;
  39746. }
  39747. }
  39748. let _id$2 = 0;
  39749. /**
  39750. * Represents a sampled texture binding type.
  39751. *
  39752. * @private
  39753. * @augments Binding
  39754. */
  39755. class SampledTexture extends Binding {
  39756. /**
  39757. * Constructs a new sampled texture.
  39758. *
  39759. * @param {string} name - The sampled texture's name.
  39760. * @param {?Texture} texture - The texture this binding is referring to.
  39761. */
  39762. constructor( name, texture ) {
  39763. super( name );
  39764. /**
  39765. * This identifier.
  39766. *
  39767. * @type {number}
  39768. */
  39769. this.id = _id$2 ++;
  39770. /**
  39771. * The texture this binding is referring to.
  39772. *
  39773. * @type {?Texture}
  39774. */
  39775. this.texture = texture;
  39776. /**
  39777. * The binding's version.
  39778. *
  39779. * @type {number}
  39780. */
  39781. this.version = texture ? texture.version : 0;
  39782. /**
  39783. * Whether the texture is a storage texture or not.
  39784. *
  39785. * @type {boolean}
  39786. * @default false
  39787. */
  39788. this.store = false;
  39789. /**
  39790. * The binding's generation which is an additional version
  39791. * qualifier.
  39792. *
  39793. * @type {?number}
  39794. * @default null
  39795. */
  39796. this.generation = null;
  39797. /**
  39798. * This flag can be used for type testing.
  39799. *
  39800. * @type {boolean}
  39801. * @readonly
  39802. * @default true
  39803. */
  39804. this.isSampledTexture = true;
  39805. }
  39806. /**
  39807. * Returns `true` whether this binding requires an update for the
  39808. * given generation.
  39809. *
  39810. * @param {number} generation - The generation.
  39811. * @return {boolean} Whether an update is required or not.
  39812. */
  39813. needsBindingsUpdate( generation ) {
  39814. if ( generation !== this.generation ) {
  39815. this.generation = generation;
  39816. return true;
  39817. }
  39818. return false;
  39819. }
  39820. /**
  39821. * Updates the binding.
  39822. *
  39823. * @return {boolean} Whether the texture has been updated and must be
  39824. * uploaded to the GPU.
  39825. */
  39826. update() {
  39827. const { texture, version } = this;
  39828. if ( version !== texture.version ) {
  39829. this.version = texture.version;
  39830. return true;
  39831. }
  39832. return false;
  39833. }
  39834. }
  39835. /**
  39836. * A special form of sampled texture binding type.
  39837. * It's texture value is managed by a node object.
  39838. *
  39839. * @private
  39840. * @augments SampledTexture
  39841. */
  39842. class NodeSampledTexture extends SampledTexture {
  39843. /**
  39844. * Constructs a new node-based sampled texture.
  39845. *
  39846. * @param {string} name - The textures's name.
  39847. * @param {TextureNode} textureNode - The texture node.
  39848. * @param {UniformGroupNode} groupNode - The uniform group node.
  39849. * @param {?string} [access=null] - The access type.
  39850. */
  39851. constructor( name, textureNode, groupNode, access = null ) {
  39852. super( name, textureNode ? textureNode.value : null );
  39853. /**
  39854. * The texture node.
  39855. *
  39856. * @type {TextureNode}
  39857. */
  39858. this.textureNode = textureNode;
  39859. /**
  39860. * The uniform group node.
  39861. *
  39862. * @type {UniformGroupNode}
  39863. */
  39864. this.groupNode = groupNode;
  39865. /**
  39866. * The access type.
  39867. *
  39868. * @type {?string}
  39869. * @default null
  39870. */
  39871. this.access = access;
  39872. }
  39873. /**
  39874. * Overwrites the default to additionally check if the node value has changed.
  39875. *
  39876. * @param {number} generation - The generation.
  39877. * @return {boolean} Whether an update is required or not.
  39878. */
  39879. needsBindingsUpdate( generation ) {
  39880. return this.textureNode.value !== this.texture || super.needsBindingsUpdate( generation );
  39881. }
  39882. /**
  39883. * Updates the binding.
  39884. *
  39885. * @return {boolean} Whether the texture has been updated and must be
  39886. * uploaded to the GPU.
  39887. */
  39888. update() {
  39889. const { textureNode } = this;
  39890. if ( this.texture !== textureNode.value ) {
  39891. this.texture = textureNode.value;
  39892. return true;
  39893. }
  39894. return super.update();
  39895. }
  39896. }
  39897. /**
  39898. * A special form of sampled cube texture binding type.
  39899. * It's texture value is managed by a node object.
  39900. *
  39901. * @private
  39902. * @augments NodeSampledTexture
  39903. */
  39904. class NodeSampledCubeTexture extends NodeSampledTexture {
  39905. /**
  39906. * Constructs a new node-based sampled cube texture.
  39907. *
  39908. * @param {string} name - The textures's name.
  39909. * @param {TextureNode} textureNode - The texture node.
  39910. * @param {UniformGroupNode} groupNode - The uniform group node.
  39911. * @param {?string} [access=null] - The access type.
  39912. */
  39913. constructor( name, textureNode, groupNode, access = null ) {
  39914. super( name, textureNode, groupNode, access );
  39915. /**
  39916. * This flag can be used for type testing.
  39917. *
  39918. * @type {boolean}
  39919. * @readonly
  39920. * @default true
  39921. */
  39922. this.isSampledCubeTexture = true;
  39923. }
  39924. }
  39925. /**
  39926. * A special form of sampled 3D texture binding type.
  39927. * It's texture value is managed by a node object.
  39928. *
  39929. * @private
  39930. * @augments NodeSampledTexture
  39931. */
  39932. class NodeSampledTexture3D extends NodeSampledTexture {
  39933. /**
  39934. * Constructs a new node-based sampled 3D texture.
  39935. *
  39936. * @param {string} name - The textures's name.
  39937. * @param {TextureNode} textureNode - The texture node.
  39938. * @param {UniformGroupNode} groupNode - The uniform group node.
  39939. * @param {?string} [access=null] - The access type.
  39940. */
  39941. constructor( name, textureNode, groupNode, access = null ) {
  39942. super( name, textureNode, groupNode, access );
  39943. /**
  39944. * This flag can be used for type testing.
  39945. *
  39946. * @type {boolean}
  39947. * @readonly
  39948. * @default true
  39949. */
  39950. this.isSampledTexture3D = true;
  39951. }
  39952. }
  39953. const glslMethods = {
  39954. textureDimensions: 'textureSize',
  39955. equals: 'equal'
  39956. };
  39957. const precisionLib = {
  39958. low: 'lowp',
  39959. medium: 'mediump',
  39960. high: 'highp'
  39961. };
  39962. const supports$1 = {
  39963. swizzleAssign: true,
  39964. storageBuffer: false
  39965. };
  39966. const interpolationTypeMap = {
  39967. perspective: 'smooth',
  39968. linear: 'noperspective'
  39969. };
  39970. const interpolationModeMap = {
  39971. 'centroid': 'centroid'
  39972. };
  39973. const defaultPrecisions = `
  39974. precision highp float;
  39975. precision highp int;
  39976. precision highp sampler2D;
  39977. precision highp sampler3D;
  39978. precision highp samplerCube;
  39979. precision highp sampler2DArray;
  39980. precision highp usampler2D;
  39981. precision highp usampler3D;
  39982. precision highp usamplerCube;
  39983. precision highp usampler2DArray;
  39984. precision highp isampler2D;
  39985. precision highp isampler3D;
  39986. precision highp isamplerCube;
  39987. precision highp isampler2DArray;
  39988. precision lowp sampler2DShadow;
  39989. precision lowp sampler2DArrayShadow;
  39990. precision lowp samplerCubeShadow;
  39991. `;
  39992. /**
  39993. * A node builder targeting GLSL.
  39994. *
  39995. * This module generates GLSL shader code from node materials and also
  39996. * generates the respective bindings and vertex buffer definitions. These
  39997. * data are later used by the renderer to create render and compute pipelines
  39998. * for render objects.
  39999. *
  40000. * @augments NodeBuilder
  40001. */
  40002. class GLSLNodeBuilder extends NodeBuilder {
  40003. /**
  40004. * Constructs a new GLSL node builder renderer.
  40005. *
  40006. * @param {Object3D} object - The 3D object.
  40007. * @param {Renderer} renderer - The renderer.
  40008. */
  40009. constructor( object, renderer ) {
  40010. super( object, renderer, new GLSLNodeParser() );
  40011. /**
  40012. * A dictionary holds for each shader stage ('vertex', 'fragment', 'compute')
  40013. * another dictionary which manages UBOs per group ('render','frame','object').
  40014. *
  40015. * @type {Object<string,Object<string,NodeUniformsGroup>>}
  40016. */
  40017. this.uniformGroups = {};
  40018. /**
  40019. * An array that holds objects defining the varying and attribute data in
  40020. * context of Transform Feedback.
  40021. *
  40022. * @type {Array<Object<string,AttributeNode|string>>}
  40023. */
  40024. this.transforms = [];
  40025. /**
  40026. * A dictionary that holds for each shader stage a Map of used extensions.
  40027. *
  40028. * @type {Object<string,Map<string,Object>>}
  40029. */
  40030. this.extensions = {};
  40031. /**
  40032. * A dictionary that holds for each shader stage an Array of used builtins.
  40033. *
  40034. * @type {Object<string,Array<string>>}
  40035. */
  40036. this.builtins = { vertex: [], fragment: [], compute: [] };
  40037. }
  40038. /**
  40039. * Checks if the given texture requires a manual conversion to the working color space.
  40040. *
  40041. * @param {Texture} texture - The texture to check.
  40042. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  40043. */
  40044. needsToWorkingColorSpace( texture ) {
  40045. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  40046. }
  40047. /**
  40048. * Returns the native shader method name for a given generic name.
  40049. *
  40050. * @param {string} method - The method name to resolve.
  40051. * @return {string} The resolved GLSL method name.
  40052. */
  40053. getMethod( method ) {
  40054. return glslMethods[ method ] || method;
  40055. }
  40056. /**
  40057. * Returns the output struct name. Not relevant for GLSL.
  40058. *
  40059. * @return {string}
  40060. */
  40061. getOutputStructName() {
  40062. return '';
  40063. }
  40064. /**
  40065. * Builds the given shader node.
  40066. *
  40067. * @param {ShaderNodeInternal} shaderNode - The shader node.
  40068. * @return {string} The GLSL function code.
  40069. */
  40070. buildFunctionCode( shaderNode ) {
  40071. const layout = shaderNode.layout;
  40072. const flowData = this.flowShaderNode( shaderNode );
  40073. const parameters = [];
  40074. for ( const input of layout.inputs ) {
  40075. parameters.push( this.getType( input.type ) + ' ' + input.name );
  40076. }
  40077. //
  40078. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  40079. ${ flowData.vars }
  40080. ${ flowData.code }
  40081. return ${ flowData.result };
  40082. }`;
  40083. //
  40084. return code;
  40085. }
  40086. /**
  40087. * Setups the Pixel Buffer Object (PBO) for the given storage
  40088. * buffer node.
  40089. *
  40090. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  40091. */
  40092. setupPBO( storageBufferNode ) {
  40093. const attribute = storageBufferNode.value;
  40094. if ( attribute.pbo === undefined ) {
  40095. const originalArray = attribute.array;
  40096. const numElements = attribute.count * attribute.itemSize;
  40097. const { itemSize } = attribute;
  40098. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  40099. let format = isInteger ? RedIntegerFormat : RedFormat;
  40100. if ( itemSize === 2 ) {
  40101. format = isInteger ? RGIntegerFormat : RGFormat;
  40102. } else if ( itemSize === 3 ) {
  40103. format = isInteger ? RGBIntegerFormat : RGBFormat;
  40104. } else if ( itemSize === 4 ) {
  40105. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  40106. }
  40107. const typeMap = {
  40108. Float32Array: FloatType,
  40109. Uint8Array: UnsignedByteType,
  40110. Uint16Array: UnsignedShortType,
  40111. Uint32Array: UnsignedIntType,
  40112. Int8Array: ByteType,
  40113. Int16Array: ShortType,
  40114. Int32Array: IntType,
  40115. Uint8ClampedArray: UnsignedByteType,
  40116. };
  40117. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  40118. let height = Math.ceil( ( numElements / itemSize ) / width );
  40119. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  40120. const newSize = width * height * itemSize;
  40121. const newArray = new originalArray.constructor( newSize );
  40122. newArray.set( originalArray, 0 );
  40123. attribute.array = newArray;
  40124. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  40125. pboTexture.needsUpdate = true;
  40126. pboTexture.isPBOTexture = true;
  40127. const pbo = new TextureNode( pboTexture, null, null );
  40128. pbo.setPrecision( 'high' );
  40129. attribute.pboNode = pbo;
  40130. attribute.pbo = pbo.value;
  40131. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  40132. }
  40133. }
  40134. /**
  40135. * Returns a GLSL snippet that represents the property name of the given node.
  40136. *
  40137. * @param {Node} node - The node.
  40138. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  40139. * @return {string} The property name.
  40140. */
  40141. getPropertyName( node, shaderStage = this.shaderStage ) {
  40142. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  40143. return shaderStage.charAt( 0 ) + '_' + node.name;
  40144. }
  40145. return super.getPropertyName( node, shaderStage );
  40146. }
  40147. /**
  40148. * Setups the Pixel Buffer Object (PBO) for the given storage
  40149. * buffer node.
  40150. *
  40151. * @param {StorageArrayElementNode} storageArrayElementNode - The storage array element node.
  40152. * @return {string} The property name.
  40153. */
  40154. generatePBO( storageArrayElementNode ) {
  40155. const { node, indexNode } = storageArrayElementNode;
  40156. const attribute = node.value;
  40157. if ( this.renderer.backend.has( attribute ) ) {
  40158. const attributeData = this.renderer.backend.get( attribute );
  40159. attributeData.pbo = attribute.pbo;
  40160. }
  40161. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  40162. const textureName = this.getPropertyName( nodeUniform );
  40163. this.increaseUsage( indexNode ); // force cache generate to be used as index in x,y
  40164. const indexSnippet = indexNode.build( this, 'uint' );
  40165. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  40166. let propertyName = elementNodeData.propertyName;
  40167. if ( propertyName === undefined ) {
  40168. // property element
  40169. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  40170. propertyName = this.getPropertyName( nodeVar );
  40171. // property size
  40172. const bufferNodeData = this.getDataFromNode( node );
  40173. let propertySizeName = bufferNodeData.propertySizeName;
  40174. if ( propertySizeName === undefined ) {
  40175. propertySizeName = propertyName + 'Size';
  40176. this.getVarFromNode( node, propertySizeName, 'uint' );
  40177. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )`, storageArrayElementNode );
  40178. bufferNodeData.propertySizeName = propertySizeName;
  40179. }
  40180. //
  40181. const { itemSize } = attribute;
  40182. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  40183. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  40184. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, null, '0' );
  40185. //
  40186. let prefix = 'vec4';
  40187. if ( attribute.pbo.type === UnsignedIntType ) {
  40188. prefix = 'uvec4';
  40189. } else if ( attribute.pbo.type === IntType ) {
  40190. prefix = 'ivec4';
  40191. }
  40192. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}`, storageArrayElementNode );
  40193. elementNodeData.propertyName = propertyName;
  40194. }
  40195. return propertyName;
  40196. }
  40197. /**
  40198. * Generates the GLSL snippet that reads a single texel from a texture without sampling or filtering.
  40199. *
  40200. * @param {Texture} texture - The texture.
  40201. * @param {string} textureProperty - The name of the texture uniform in the shader.
  40202. * @param {string} uvIndexSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  40203. * @param {?string} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  40204. * @param {string} [levelSnippet='0u'] - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  40205. * @return {string} The GLSL snippet.
  40206. */
  40207. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0' ) {
  40208. if ( depthSnippet ) {
  40209. return `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  40210. } else {
  40211. return `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  40212. }
  40213. }
  40214. /**
  40215. * Generates the GLSL snippet for sampling/loading the given texture.
  40216. *
  40217. * @param {Texture} texture - The texture.
  40218. * @param {string} textureProperty - The name of the texture uniform in the shader.
  40219. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  40220. * @param {?string} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  40221. * @return {string} The GLSL snippet.
  40222. */
  40223. generateTexture( texture, textureProperty, uvSnippet, depthSnippet ) {
  40224. if ( texture.isDepthTexture ) {
  40225. if ( depthSnippet ) uvSnippet = `vec4( ${ uvSnippet }, ${ depthSnippet } )`;
  40226. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  40227. } else {
  40228. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  40229. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  40230. }
  40231. }
  40232. /**
  40233. * Generates the GLSL snippet when sampling textures with explicit mip level.
  40234. *
  40235. * @param {Texture} texture - The texture.
  40236. * @param {string} textureProperty - The name of the texture uniform in the shader.
  40237. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  40238. * @param {string} levelSnippet - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  40239. * @return {string} The GLSL snippet.
  40240. */
  40241. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet ) {
  40242. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  40243. }
  40244. /**
  40245. * Generates the GLSL snippet when sampling textures with a bias to the mip level.
  40246. *
  40247. * @param {Texture} texture - The texture.
  40248. * @param {string} textureProperty - The name of the texture uniform in the shader.
  40249. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  40250. * @param {string} biasSnippet - A GLSL snippet that represents the bias to apply to the mip level before sampling.
  40251. * @return {string} The GLSL snippet.
  40252. */
  40253. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet ) {
  40254. return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
  40255. }
  40256. /**
  40257. * Generates the GLSL snippet for sampling/loading the given texture using explicit gradients.
  40258. *
  40259. * @param {Texture} texture - The texture.
  40260. * @param {string} textureProperty - The name of the texture uniform in the shader.
  40261. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  40262. * @param {Array<string>} gradSnippet - An array holding both gradient GLSL snippets.
  40263. * @return {string} The GLSL snippet.
  40264. */
  40265. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet ) {
  40266. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  40267. }
  40268. /**
  40269. * Generates the GLSL snippet for sampling a depth texture and comparing the sampled depth values
  40270. * against a reference value.
  40271. *
  40272. * @param {Texture} texture - The texture.
  40273. * @param {string} textureProperty - The name of the texture uniform in the shader.
  40274. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  40275. * @param {string} compareSnippet - A GLSL snippet that represents the reference value.
  40276. * @param {?string} depthSnippet - A GLSL snippet that represents 0-based texture array index to sample.
  40277. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  40278. * @return {string} The GLSL snippet.
  40279. */
  40280. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  40281. if ( shaderStage === 'fragment' ) {
  40282. if ( depthSnippet ) {
  40283. return `texture( ${ textureProperty }, vec4( ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } ) )`;
  40284. }
  40285. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  40286. } else {
  40287. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  40288. }
  40289. }
  40290. /**
  40291. * Returns the variables of the given shader stage as a GLSL string.
  40292. *
  40293. * @param {string} shaderStage - The shader stage.
  40294. * @return {string} The GLSL snippet that defines the variables.
  40295. */
  40296. getVars( shaderStage ) {
  40297. const snippets = [];
  40298. const vars = this.vars[ shaderStage ];
  40299. if ( vars !== undefined ) {
  40300. for ( const variable of vars ) {
  40301. snippets.push( `${ this.getVar( variable.type, variable.name, variable.count ) };` );
  40302. }
  40303. }
  40304. return snippets.join( '\n\t' );
  40305. }
  40306. /**
  40307. * Returns the uniforms of the given shader stage as a GLSL string.
  40308. *
  40309. * @param {string} shaderStage - The shader stage.
  40310. * @return {string} The GLSL snippet that defines the uniforms.
  40311. */
  40312. getUniforms( shaderStage ) {
  40313. const uniforms = this.uniforms[ shaderStage ];
  40314. const bindingSnippets = [];
  40315. const uniformGroups = {};
  40316. for ( const uniform of uniforms ) {
  40317. let snippet = null;
  40318. let group = false;
  40319. if ( uniform.type === 'texture' || uniform.type === 'texture3D' ) {
  40320. const texture = uniform.node.value;
  40321. let typePrefix = '';
  40322. if ( texture.isDataTexture === true || texture.isData3DTexture === true ) {
  40323. if ( texture.type === UnsignedIntType ) {
  40324. typePrefix = 'u';
  40325. } else if ( texture.type === IntType ) {
  40326. typePrefix = 'i';
  40327. }
  40328. }
  40329. if ( uniform.type === 'texture3D' && texture.isArrayTexture === false ) {
  40330. snippet = `${typePrefix}sampler3D ${ uniform.name };`;
  40331. } else if ( texture.compareFunction ) {
  40332. if ( texture.isArrayTexture === true ) {
  40333. snippet = `sampler2DArrayShadow ${ uniform.name };`;
  40334. } else {
  40335. snippet = `sampler2DShadow ${ uniform.name };`;
  40336. }
  40337. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  40338. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  40339. } else {
  40340. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  40341. }
  40342. } else if ( uniform.type === 'cubeTexture' ) {
  40343. snippet = `samplerCube ${ uniform.name };`;
  40344. } else if ( uniform.type === 'buffer' ) {
  40345. const bufferNode = uniform.node;
  40346. const bufferType = this.getType( bufferNode.bufferType );
  40347. const bufferCount = bufferNode.bufferCount;
  40348. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  40349. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  40350. } else {
  40351. const vectorType = this.getVectorType( uniform.type );
  40352. snippet = `${ vectorType } ${ this.getPropertyName( uniform, shaderStage ) };`;
  40353. group = true;
  40354. }
  40355. const precision = uniform.node.precision;
  40356. if ( precision !== null ) {
  40357. snippet = precisionLib[ precision ] + ' ' + snippet;
  40358. }
  40359. if ( group ) {
  40360. snippet = '\t' + snippet;
  40361. const groupName = uniform.groupNode.name;
  40362. const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
  40363. groupSnippets.push( snippet );
  40364. } else {
  40365. snippet = 'uniform ' + snippet;
  40366. bindingSnippets.push( snippet );
  40367. }
  40368. }
  40369. let output = '';
  40370. for ( const name in uniformGroups ) {
  40371. const groupSnippets = uniformGroups[ name ];
  40372. output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
  40373. }
  40374. output += bindingSnippets.join( '\n' );
  40375. return output;
  40376. }
  40377. /**
  40378. * Returns the type for a given buffer attribute.
  40379. *
  40380. * @param {BufferAttribute} attribute - The buffer attribute.
  40381. * @return {string} The type.
  40382. */
  40383. getTypeFromAttribute( attribute ) {
  40384. let nodeType = super.getTypeFromAttribute( attribute );
  40385. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  40386. let dataAttribute = attribute;
  40387. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  40388. const array = dataAttribute.array;
  40389. if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
  40390. nodeType = nodeType.slice( 1 );
  40391. }
  40392. }
  40393. return nodeType;
  40394. }
  40395. /**
  40396. * Returns the shader attributes of the given shader stage as a GLSL string.
  40397. *
  40398. * @param {string} shaderStage - The shader stage.
  40399. * @return {string} The GLSL snippet that defines the shader attributes.
  40400. */
  40401. getAttributes( shaderStage ) {
  40402. let snippet = '';
  40403. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  40404. const attributes = this.getAttributesArray();
  40405. let location = 0;
  40406. for ( const attribute of attributes ) {
  40407. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  40408. }
  40409. }
  40410. return snippet;
  40411. }
  40412. /**
  40413. * Returns the members of the given struct type node as a GLSL string.
  40414. *
  40415. * @param {StructTypeNode} struct - The struct type node.
  40416. * @return {string} The GLSL snippet that defines the struct members.
  40417. */
  40418. getStructMembers( struct ) {
  40419. const snippets = [];
  40420. for ( const member of struct.members ) {
  40421. snippets.push( `\t${ member.type } ${ member.name };` );
  40422. }
  40423. return snippets.join( '\n' );
  40424. }
  40425. /**
  40426. * Returns the structs of the given shader stage as a GLSL string.
  40427. *
  40428. * @param {string} shaderStage - The shader stage.
  40429. * @return {string} The GLSL snippet that defines the structs.
  40430. */
  40431. getStructs( shaderStage ) {
  40432. const snippets = [];
  40433. const structs = this.structs[ shaderStage ];
  40434. const outputSnippet = [];
  40435. for ( const struct of structs ) {
  40436. if ( struct.output ) {
  40437. for ( const member of struct.members ) {
  40438. outputSnippet.push( `layout( location = ${ member.index } ) out ${ member.type } ${ member.name };` );
  40439. }
  40440. } else {
  40441. let snippet = 'struct ' + struct.name + ' {\n';
  40442. snippet += this.getStructMembers( struct );
  40443. snippet += '\n};\n';
  40444. snippets.push( snippet );
  40445. }
  40446. }
  40447. if ( outputSnippet.length === 0 ) {
  40448. outputSnippet.push( 'layout( location = 0 ) out vec4 fragColor;' );
  40449. }
  40450. return '\n' + outputSnippet.join( '\n' ) + '\n\n' + snippets.join( '\n' );
  40451. }
  40452. /**
  40453. * Returns the varyings of the given shader stage as a GLSL string.
  40454. *
  40455. * @param {string} shaderStage - The shader stage.
  40456. * @return {string} The GLSL snippet that defines the varyings.
  40457. */
  40458. getVaryings( shaderStage ) {
  40459. let snippet = '';
  40460. const varyings = this.varyings;
  40461. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  40462. for ( const varying of varyings ) {
  40463. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  40464. const type = this.getType( varying.type );
  40465. if ( varying.needsInterpolation ) {
  40466. if ( varying.interpolationType ) {
  40467. const interpolationType = interpolationTypeMap[ varying.interpolationType ] || varying.interpolationType;
  40468. const sampling = interpolationModeMap[ varying.interpolationSampling ] || '';
  40469. snippet += `${ interpolationType } ${ sampling } out ${ type } ${ varying.name };\n`;
  40470. } else {
  40471. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  40472. snippet += `${ flat }out ${ type } ${ varying.name };\n`;
  40473. }
  40474. } else {
  40475. snippet += `${type} ${varying.name};\n`; // generate variable (no varying required)
  40476. }
  40477. }
  40478. } else if ( shaderStage === 'fragment' ) {
  40479. for ( const varying of varyings ) {
  40480. if ( varying.needsInterpolation ) {
  40481. const type = this.getType( varying.type );
  40482. if ( varying.interpolationType ) {
  40483. const interpolationType = interpolationTypeMap[ varying.interpolationType ] || varying.interpolationType;
  40484. const sampling = interpolationModeMap[ varying.interpolationSampling ] || '';
  40485. snippet += `${ interpolationType } ${ sampling } in ${ type } ${ varying.name };\n`;
  40486. } else {
  40487. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  40488. snippet += `${ flat }in ${ type } ${ varying.name };\n`;
  40489. }
  40490. }
  40491. }
  40492. }
  40493. for ( const builtin of this.builtins[ shaderStage ] ) {
  40494. snippet += `${builtin};\n`;
  40495. }
  40496. return snippet;
  40497. }
  40498. /**
  40499. * Returns the vertex index builtin.
  40500. *
  40501. * @return {string} The vertex index.
  40502. */
  40503. getVertexIndex() {
  40504. return 'uint( gl_VertexID )';
  40505. }
  40506. /**
  40507. * Returns the instance index builtin.
  40508. *
  40509. * @return {string} The instance index.
  40510. */
  40511. getInstanceIndex() {
  40512. return 'uint( gl_InstanceID )';
  40513. }
  40514. /**
  40515. * Returns the invocation local index builtin.
  40516. *
  40517. * @return {string} The invocation local index.
  40518. */
  40519. getInvocationLocalIndex() {
  40520. const workgroupSize = this.object.workgroupSize;
  40521. const size = workgroupSize.reduce( ( acc, curr ) => acc * curr, 1 );
  40522. return `uint( gl_InstanceID ) % ${size}u`;
  40523. }
  40524. /**
  40525. * Returns the draw index builtin.
  40526. *
  40527. * @return {?string} The drawIndex shader string. Returns `null` if `WEBGL_multi_draw` isn't supported by the device.
  40528. */
  40529. getDrawIndex() {
  40530. const extensions = this.renderer.backend.extensions;
  40531. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  40532. return 'uint( gl_DrawID )';
  40533. }
  40534. return null;
  40535. }
  40536. /**
  40537. * Returns the front facing builtin.
  40538. *
  40539. * @return {string} The front facing builtin.
  40540. */
  40541. getFrontFacing() {
  40542. return 'gl_FrontFacing';
  40543. }
  40544. /**
  40545. * Returns the frag coord builtin.
  40546. *
  40547. * @return {string} The frag coord builtin.
  40548. */
  40549. getFragCoord() {
  40550. return 'gl_FragCoord.xy';
  40551. }
  40552. /**
  40553. * Returns the frag depth builtin.
  40554. *
  40555. * @return {string} The frag depth builtin.
  40556. */
  40557. getFragDepth() {
  40558. return 'gl_FragDepth';
  40559. }
  40560. /**
  40561. * Enables the given extension.
  40562. *
  40563. * @param {string} name - The extension name.
  40564. * @param {string} behavior - The extension behavior.
  40565. * @param {string} [shaderStage=this.shaderStage] - The shader stage.
  40566. */
  40567. enableExtension( name, behavior, shaderStage = this.shaderStage ) {
  40568. const map = this.extensions[ shaderStage ] || ( this.extensions[ shaderStage ] = new Map() );
  40569. if ( map.has( name ) === false ) {
  40570. map.set( name, {
  40571. name,
  40572. behavior
  40573. } );
  40574. }
  40575. }
  40576. /**
  40577. * Returns the enabled extensions of the given shader stage as a GLSL string.
  40578. *
  40579. * @param {string} shaderStage - The shader stage.
  40580. * @return {string} The GLSL snippet that defines the enabled extensions.
  40581. */
  40582. getExtensions( shaderStage ) {
  40583. const snippets = [];
  40584. if ( shaderStage === 'vertex' ) {
  40585. const ext = this.renderer.backend.extensions;
  40586. const isBatchedMesh = this.object.isBatchedMesh;
  40587. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  40588. this.enableExtension( 'GL_ANGLE_multi_draw', 'require', shaderStage );
  40589. }
  40590. }
  40591. const extensions = this.extensions[ shaderStage ];
  40592. if ( extensions !== undefined ) {
  40593. for ( const { name, behavior } of extensions.values() ) {
  40594. snippets.push( `#extension ${name} : ${behavior}` );
  40595. }
  40596. }
  40597. return snippets.join( '\n' );
  40598. }
  40599. /**
  40600. * Returns the clip distances builtin.
  40601. *
  40602. * @return {string} The clip distances builtin.
  40603. */
  40604. getClipDistance() {
  40605. return 'gl_ClipDistance';
  40606. }
  40607. /**
  40608. * Whether the requested feature is available or not.
  40609. *
  40610. * @param {string} name - The requested feature.
  40611. * @return {boolean} Whether the requested feature is supported or not.
  40612. */
  40613. isAvailable( name ) {
  40614. let result = supports$1[ name ];
  40615. if ( result === undefined ) {
  40616. let extensionName;
  40617. result = false;
  40618. switch ( name ) {
  40619. case 'float32Filterable':
  40620. extensionName = 'OES_texture_float_linear';
  40621. break;
  40622. case 'clipDistance':
  40623. extensionName = 'WEBGL_clip_cull_distance';
  40624. break;
  40625. }
  40626. if ( extensionName !== undefined ) {
  40627. const extensions = this.renderer.backend.extensions;
  40628. if ( extensions.has( extensionName ) ) {
  40629. extensions.get( extensionName );
  40630. result = true;
  40631. }
  40632. }
  40633. supports$1[ name ] = result;
  40634. }
  40635. return result;
  40636. }
  40637. /**
  40638. * Whether to flip texture data along its vertical axis or not.
  40639. *
  40640. * @return {boolean} Returns always `true` in context of GLSL.
  40641. */
  40642. isFlipY() {
  40643. return true;
  40644. }
  40645. /**
  40646. * Enables hardware clipping.
  40647. *
  40648. * @param {string} planeCount - The clipping plane count.
  40649. */
  40650. enableHardwareClipping( planeCount ) {
  40651. this.enableExtension( 'GL_ANGLE_clip_cull_distance', 'require' );
  40652. this.builtins[ 'vertex' ].push( `out float gl_ClipDistance[ ${ planeCount } ]` );
  40653. }
  40654. /**
  40655. * Enables multiview.
  40656. */
  40657. enableMultiview() {
  40658. this.enableExtension( 'GL_OVR_multiview2', 'require', 'fragment' );
  40659. this.enableExtension( 'GL_OVR_multiview2', 'require', 'vertex' );
  40660. this.builtins[ 'vertex' ].push( 'layout(num_views = 2) in' );
  40661. }
  40662. /**
  40663. * Registers a transform in context of Transform Feedback.
  40664. *
  40665. * @param {string} varyingName - The varying name.
  40666. * @param {AttributeNode} attributeNode - The attribute node.
  40667. */
  40668. registerTransform( varyingName, attributeNode ) {
  40669. this.transforms.push( { varyingName, attributeNode } );
  40670. }
  40671. /**
  40672. * Returns the transforms of the given shader stage as a GLSL string.
  40673. *
  40674. * @param {string} shaderStage - The shader stage.
  40675. * @return {string} The GLSL snippet that defines the transforms.
  40676. */
  40677. getTransforms( /* shaderStage */ ) {
  40678. const transforms = this.transforms;
  40679. let snippet = '';
  40680. for ( let i = 0; i < transforms.length; i ++ ) {
  40681. const transform = transforms[ i ];
  40682. const attributeName = this.getPropertyName( transform.attributeNode );
  40683. if ( attributeName ) snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  40684. }
  40685. return snippet;
  40686. }
  40687. /**
  40688. * Returns a GLSL struct based on the given name and variables.
  40689. *
  40690. * @private
  40691. * @param {string} name - The struct name.
  40692. * @param {string} vars - The struct variables.
  40693. * @return {string} The GLSL snippet representing a struct.
  40694. */
  40695. _getGLSLUniformStruct( name, vars ) {
  40696. return `
  40697. layout( std140 ) uniform ${name} {
  40698. ${vars}
  40699. };`;
  40700. }
  40701. /**
  40702. * Returns a GLSL vertex shader based on the given shader data.
  40703. *
  40704. * @private
  40705. * @param {Object} shaderData - The shader data.
  40706. * @return {string} The vertex shader.
  40707. */
  40708. _getGLSLVertexCode( shaderData ) {
  40709. return `#version 300 es
  40710. ${ this.getSignature() }
  40711. // extensions
  40712. ${shaderData.extensions}
  40713. // precision
  40714. ${ defaultPrecisions }
  40715. // uniforms
  40716. ${shaderData.uniforms}
  40717. // varyings
  40718. ${shaderData.varyings}
  40719. // attributes
  40720. ${shaderData.attributes}
  40721. // codes
  40722. ${shaderData.codes}
  40723. void main() {
  40724. // vars
  40725. ${shaderData.vars}
  40726. // transforms
  40727. ${shaderData.transforms}
  40728. // flow
  40729. ${shaderData.flow}
  40730. gl_PointSize = 1.0;
  40731. }
  40732. `;
  40733. }
  40734. /**
  40735. * Returns a GLSL fragment shader based on the given shader data.
  40736. *
  40737. * @private
  40738. * @param {Object} shaderData - The shader data.
  40739. * @return {string} The vertex shader.
  40740. */
  40741. _getGLSLFragmentCode( shaderData ) {
  40742. return `#version 300 es
  40743. ${ this.getSignature() }
  40744. // extensions
  40745. ${shaderData.extensions}
  40746. // precision
  40747. ${ defaultPrecisions }
  40748. // uniforms
  40749. ${shaderData.uniforms}
  40750. // varyings
  40751. ${shaderData.varyings}
  40752. // codes
  40753. ${shaderData.codes}
  40754. // structs
  40755. ${shaderData.structs}
  40756. void main() {
  40757. // vars
  40758. ${shaderData.vars}
  40759. // flow
  40760. ${shaderData.flow}
  40761. }
  40762. `;
  40763. }
  40764. /**
  40765. * Controls the code build of the shader stages.
  40766. */
  40767. buildCode() {
  40768. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  40769. this.sortBindingGroups();
  40770. for ( const shaderStage in shadersData ) {
  40771. let flow = '// code\n\n';
  40772. flow += this.flowCode[ shaderStage ];
  40773. const flowNodes = this.flowNodes[ shaderStage ];
  40774. const mainNode = flowNodes[ flowNodes.length - 1 ];
  40775. for ( const node of flowNodes ) {
  40776. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  40777. const slotName = node.name;
  40778. if ( slotName ) {
  40779. if ( flow.length > 0 ) flow += '\n';
  40780. flow += `\t// flow -> ${ slotName }\n\t`;
  40781. }
  40782. flow += `${ flowSlotData.code }\n\t`;
  40783. if ( node === mainNode && shaderStage !== 'compute' ) {
  40784. flow += '// result\n\t';
  40785. if ( shaderStage === 'vertex' ) {
  40786. flow += 'gl_Position = ';
  40787. flow += `${ flowSlotData.result };`;
  40788. } else if ( shaderStage === 'fragment' ) {
  40789. if ( ! node.outputNode.isOutputStructNode ) {
  40790. flow += 'fragColor = ';
  40791. flow += `${ flowSlotData.result };`;
  40792. }
  40793. }
  40794. }
  40795. }
  40796. const stageData = shadersData[ shaderStage ];
  40797. stageData.extensions = this.getExtensions( shaderStage );
  40798. stageData.uniforms = this.getUniforms( shaderStage );
  40799. stageData.attributes = this.getAttributes( shaderStage );
  40800. stageData.varyings = this.getVaryings( shaderStage );
  40801. stageData.vars = this.getVars( shaderStage );
  40802. stageData.structs = this.getStructs( shaderStage );
  40803. stageData.codes = this.getCodes( shaderStage );
  40804. stageData.transforms = this.getTransforms( shaderStage );
  40805. stageData.flow = flow;
  40806. }
  40807. if ( this.material !== null ) {
  40808. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  40809. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  40810. } else {
  40811. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  40812. }
  40813. }
  40814. /**
  40815. * This method is one of the more important ones since it's responsible
  40816. * for generating a matching binding instance for the given uniform node.
  40817. *
  40818. * These bindings are later used in the renderer to create bind groups
  40819. * and layouts.
  40820. *
  40821. * @param {UniformNode} node - The uniform node.
  40822. * @param {string} type - The node data type.
  40823. * @param {string} shaderStage - The shader stage.
  40824. * @param {?string} [name=null] - An optional uniform name.
  40825. * @return {NodeUniform} The node uniform object.
  40826. */
  40827. getUniformFromNode( node, type, shaderStage, name = null ) {
  40828. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  40829. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  40830. let uniformGPU = nodeData.uniformGPU;
  40831. if ( uniformGPU === undefined ) {
  40832. const group = node.groupNode;
  40833. const groupName = group.name;
  40834. const bindings = this.getBindGroupArray( groupName, shaderStage );
  40835. if ( type === 'texture' ) {
  40836. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  40837. bindings.push( uniformGPU );
  40838. } else if ( type === 'cubeTexture' ) {
  40839. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  40840. bindings.push( uniformGPU );
  40841. } else if ( type === 'texture3D' ) {
  40842. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  40843. bindings.push( uniformGPU );
  40844. } else if ( type === 'buffer' ) {
  40845. node.name = `NodeBuffer_${ node.id }`;
  40846. uniformNode.name = `buffer${ node.id }`;
  40847. const buffer = new NodeUniformBuffer( node, group );
  40848. buffer.name = node.name;
  40849. bindings.push( buffer );
  40850. uniformGPU = buffer;
  40851. } else {
  40852. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  40853. let uniformsGroup = uniformsStage[ groupName ];
  40854. if ( uniformsGroup === undefined ) {
  40855. uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
  40856. //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  40857. uniformsStage[ groupName ] = uniformsGroup;
  40858. bindings.push( uniformsGroup );
  40859. }
  40860. uniformGPU = this.getNodeUniform( uniformNode, type );
  40861. uniformsGroup.addUniform( uniformGPU );
  40862. }
  40863. nodeData.uniformGPU = uniformGPU;
  40864. }
  40865. return uniformNode;
  40866. }
  40867. }
  40868. let _vector2 = null;
  40869. let _color4 = null;
  40870. /**
  40871. * Most of the rendering related logic is implemented in the
  40872. * {@link Renderer} module and related management components.
  40873. * Sometimes it is required though to execute commands which are
  40874. * specific to the current 3D backend (which is WebGPU or WebGL 2).
  40875. * This abstract base class defines an interface that encapsulates
  40876. * all backend-related logic. Derived classes for each backend must
  40877. * implement the interface.
  40878. *
  40879. * @abstract
  40880. * @private
  40881. */
  40882. class Backend {
  40883. /**
  40884. * Constructs a new backend.
  40885. *
  40886. * @param {Object} parameters - An object holding parameters for the backend.
  40887. */
  40888. constructor( parameters = {} ) {
  40889. /**
  40890. * The parameters of the backend.
  40891. *
  40892. * @type {Object}
  40893. */
  40894. this.parameters = Object.assign( {}, parameters );
  40895. /**
  40896. * This weak map holds backend-specific data of objects
  40897. * like textures, attributes or render targets.
  40898. *
  40899. * @type {WeakMap}
  40900. */
  40901. this.data = new WeakMap();
  40902. /**
  40903. * A reference to the renderer.
  40904. *
  40905. * @type {?Renderer}
  40906. * @default null
  40907. */
  40908. this.renderer = null;
  40909. /**
  40910. * A reference to the canvas element the renderer is drawing to.
  40911. *
  40912. * @type {?(HTMLCanvasElement|OffscreenCanvas)}
  40913. * @default null
  40914. */
  40915. this.domElement = null;
  40916. /**
  40917. * A reference to the timestamp query pool.
  40918. *
  40919. * @type {{render: ?TimestampQueryPool, compute: ?TimestampQueryPool}}
  40920. */
  40921. this.timestampQueryPool = {
  40922. 'render': null,
  40923. 'compute': null
  40924. };
  40925. /**
  40926. * Whether to track timestamps with a Timestamp Query API or not.
  40927. *
  40928. * @type {boolean}
  40929. * @default false
  40930. */
  40931. this.trackTimestamp = ( parameters.trackTimestamp === true );
  40932. }
  40933. /**
  40934. * Initializes the backend so it is ready for usage. Concrete backends
  40935. * are supposed to implement their rendering context creation and related
  40936. * operations in this method.
  40937. *
  40938. * @async
  40939. * @param {Renderer} renderer - The renderer.
  40940. * @return {Promise} A Promise that resolves when the backend has been initialized.
  40941. */
  40942. async init( renderer ) {
  40943. this.renderer = renderer;
  40944. }
  40945. /**
  40946. * The coordinate system of the backend.
  40947. *
  40948. * @abstract
  40949. * @type {number}
  40950. * @readonly
  40951. */
  40952. get coordinateSystem() {}
  40953. // render context
  40954. /**
  40955. * This method is executed at the beginning of a render call and
  40956. * can be used by the backend to prepare the state for upcoming
  40957. * draw calls.
  40958. *
  40959. * @abstract
  40960. * @param {RenderContext} renderContext - The render context.
  40961. */
  40962. beginRender( /*renderContext*/ ) {}
  40963. /**
  40964. * This method is executed at the end of a render call and
  40965. * can be used by the backend to finalize work after draw
  40966. * calls.
  40967. *
  40968. * @abstract
  40969. * @param {RenderContext} renderContext - The render context.
  40970. */
  40971. finishRender( /*renderContext*/ ) {}
  40972. /**
  40973. * This method is executed at the beginning of a compute call and
  40974. * can be used by the backend to prepare the state for upcoming
  40975. * compute tasks.
  40976. *
  40977. * @abstract
  40978. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  40979. */
  40980. beginCompute( /*computeGroup*/ ) {}
  40981. /**
  40982. * This method is executed at the end of a compute call and
  40983. * can be used by the backend to finalize work after compute
  40984. * tasks.
  40985. *
  40986. * @abstract
  40987. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  40988. */
  40989. finishCompute( /*computeGroup*/ ) {}
  40990. // render object
  40991. /**
  40992. * Executes a draw command for the given render object.
  40993. *
  40994. * @abstract
  40995. * @param {RenderObject} renderObject - The render object to draw.
  40996. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  40997. */
  40998. draw( /*renderObject, info*/ ) { }
  40999. // compute node
  41000. /**
  41001. * Executes a compute command for the given compute node.
  41002. *
  41003. * @abstract
  41004. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  41005. * @param {Node} computeNode - The compute node.
  41006. * @param {Array<BindGroup>} bindings - The bindings.
  41007. * @param {ComputePipeline} computePipeline - The compute pipeline.
  41008. */
  41009. compute( /*computeGroup, computeNode, computeBindings, computePipeline*/ ) { }
  41010. // program
  41011. /**
  41012. * Creates a shader program from the given programmable stage.
  41013. *
  41014. * @abstract
  41015. * @param {ProgrammableStage} program - The programmable stage.
  41016. */
  41017. createProgram( /*program*/ ) { }
  41018. /**
  41019. * Destroys the shader program of the given programmable stage.
  41020. *
  41021. * @abstract
  41022. * @param {ProgrammableStage} program - The programmable stage.
  41023. */
  41024. destroyProgram( /*program*/ ) { }
  41025. // bindings
  41026. /**
  41027. * Creates bindings from the given bind group definition.
  41028. *
  41029. * @abstract
  41030. * @param {BindGroup} bindGroup - The bind group.
  41031. * @param {Array<BindGroup>} bindings - Array of bind groups.
  41032. * @param {number} cacheIndex - The cache index.
  41033. * @param {number} version - The version.
  41034. */
  41035. createBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  41036. /**
  41037. * Updates the given bind group definition.
  41038. *
  41039. * @abstract
  41040. * @param {BindGroup} bindGroup - The bind group.
  41041. * @param {Array<BindGroup>} bindings - Array of bind groups.
  41042. * @param {number} cacheIndex - The cache index.
  41043. * @param {number} version - The version.
  41044. */
  41045. updateBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  41046. /**
  41047. * Updates a buffer binding.
  41048. *
  41049. * @abstract
  41050. * @param {Buffer} binding - The buffer binding to update.
  41051. */
  41052. updateBinding( /*binding*/ ) { }
  41053. // pipeline
  41054. /**
  41055. * Creates a render pipeline for the given render object.
  41056. *
  41057. * @abstract
  41058. * @param {RenderObject} renderObject - The render object.
  41059. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  41060. */
  41061. createRenderPipeline( /*renderObject, promises*/ ) { }
  41062. /**
  41063. * Creates a compute pipeline for the given compute node.
  41064. *
  41065. * @abstract
  41066. * @param {ComputePipeline} computePipeline - The compute pipeline.
  41067. * @param {Array<BindGroup>} bindings - The bindings.
  41068. */
  41069. createComputePipeline( /*computePipeline, bindings*/ ) { }
  41070. // cache key
  41071. /**
  41072. * Returns `true` if the render pipeline requires an update.
  41073. *
  41074. * @abstract
  41075. * @param {RenderObject} renderObject - The render object.
  41076. * @return {boolean} Whether the render pipeline requires an update or not.
  41077. */
  41078. needsRenderUpdate( /*renderObject*/ ) { }
  41079. /**
  41080. * Returns a cache key that is used to identify render pipelines.
  41081. *
  41082. * @abstract
  41083. * @param {RenderObject} renderObject - The render object.
  41084. * @return {string} The cache key.
  41085. */
  41086. getRenderCacheKey( /*renderObject*/ ) { }
  41087. // node builder
  41088. /**
  41089. * Returns a node builder for the given render object.
  41090. *
  41091. * @abstract
  41092. * @param {RenderObject} renderObject - The render object.
  41093. * @param {Renderer} renderer - The renderer.
  41094. * @return {NodeBuilder} The node builder.
  41095. */
  41096. createNodeBuilder( /*renderObject, renderer*/ ) { }
  41097. // textures
  41098. /**
  41099. * Creates a GPU sampler for the given texture.
  41100. *
  41101. * @abstract
  41102. * @param {Texture} texture - The texture to create the sampler for.
  41103. */
  41104. createSampler( /*texture*/ ) { }
  41105. /**
  41106. * Destroys the GPU sampler for the given texture.
  41107. *
  41108. * @abstract
  41109. * @param {Texture} texture - The texture to destroy the sampler for.
  41110. */
  41111. destroySampler( /*texture*/ ) {}
  41112. /**
  41113. * Creates a default texture for the given texture that can be used
  41114. * as a placeholder until the actual texture is ready for usage.
  41115. *
  41116. * @abstract
  41117. * @param {Texture} texture - The texture to create a default texture for.
  41118. */
  41119. createDefaultTexture( /*texture*/ ) { }
  41120. /**
  41121. * Defines a texture on the GPU for the given texture object.
  41122. *
  41123. * @abstract
  41124. * @param {Texture} texture - The texture.
  41125. * @param {Object} [options={}] - Optional configuration parameter.
  41126. */
  41127. createTexture( /*texture, options={}*/ ) { }
  41128. /**
  41129. * Uploads the updated texture data to the GPU.
  41130. *
  41131. * @abstract
  41132. * @param {Texture} texture - The texture.
  41133. * @param {Object} [options={}] - Optional configuration parameter.
  41134. */
  41135. updateTexture( /*texture, options = {}*/ ) { }
  41136. /**
  41137. * Generates mipmaps for the given texture.
  41138. *
  41139. * @abstract
  41140. * @param {Texture} texture - The texture.
  41141. */
  41142. generateMipmaps( /*texture*/ ) { }
  41143. /**
  41144. * Destroys the GPU data for the given texture object.
  41145. *
  41146. * @abstract
  41147. * @param {Texture} texture - The texture.
  41148. */
  41149. destroyTexture( /*texture*/ ) { }
  41150. /**
  41151. * Returns texture data as a typed array.
  41152. *
  41153. * @abstract
  41154. * @async
  41155. * @param {Texture} texture - The texture to copy.
  41156. * @param {number} x - The x coordinate of the copy origin.
  41157. * @param {number} y - The y coordinate of the copy origin.
  41158. * @param {number} width - The width of the copy.
  41159. * @param {number} height - The height of the copy.
  41160. * @param {number} faceIndex - The face index.
  41161. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  41162. */
  41163. async copyTextureToBuffer( /*texture, x, y, width, height, faceIndex*/ ) {}
  41164. /**
  41165. * Copies data of the given source texture to the given destination texture.
  41166. *
  41167. * @abstract
  41168. * @param {Texture} srcTexture - The source texture.
  41169. * @param {Texture} dstTexture - The destination texture.
  41170. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  41171. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  41172. * @param {number} [srcLevel=0] - The source mip level to copy from.
  41173. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  41174. */
  41175. copyTextureToTexture( /*srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0*/ ) {}
  41176. /**
  41177. * Copies the current bound framebuffer to the given texture.
  41178. *
  41179. * @abstract
  41180. * @param {Texture} texture - The destination texture.
  41181. * @param {RenderContext} renderContext - The render context.
  41182. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  41183. */
  41184. copyFramebufferToTexture( /*texture, renderContext, rectangle*/ ) {}
  41185. // attributes
  41186. /**
  41187. * Creates the GPU buffer of a shader attribute.
  41188. *
  41189. * @abstract
  41190. * @param {BufferAttribute} attribute - The buffer attribute.
  41191. */
  41192. createAttribute( /*attribute*/ ) { }
  41193. /**
  41194. * Creates the GPU buffer of an indexed shader attribute.
  41195. *
  41196. * @abstract
  41197. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  41198. */
  41199. createIndexAttribute( /*attribute*/ ) { }
  41200. /**
  41201. * Creates the GPU buffer of a storage attribute.
  41202. *
  41203. * @abstract
  41204. * @param {BufferAttribute} attribute - The buffer attribute.
  41205. */
  41206. createStorageAttribute( /*attribute*/ ) { }
  41207. /**
  41208. * Updates the GPU buffer of a shader attribute.
  41209. *
  41210. * @abstract
  41211. * @param {BufferAttribute} attribute - The buffer attribute to update.
  41212. */
  41213. updateAttribute( /*attribute*/ ) { }
  41214. /**
  41215. * Destroys the GPU buffer of a shader attribute.
  41216. *
  41217. * @abstract
  41218. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  41219. */
  41220. destroyAttribute( /*attribute*/ ) { }
  41221. // canvas
  41222. /**
  41223. * Returns the backend's rendering context.
  41224. *
  41225. * @abstract
  41226. * @return {Object} The rendering context.
  41227. */
  41228. getContext() { }
  41229. /**
  41230. * Backends can use this method if they have to run
  41231. * logic when the renderer gets resized.
  41232. *
  41233. * @abstract
  41234. */
  41235. updateSize() { }
  41236. /**
  41237. * Updates the viewport with the values from the given render context.
  41238. *
  41239. * @abstract
  41240. * @param {RenderContext} renderContext - The render context.
  41241. */
  41242. updateViewport( /*renderContext*/ ) {}
  41243. // utils
  41244. /**
  41245. * Returns `true` if the given 3D object is fully occluded by other
  41246. * 3D objects in the scene. Backends must implement this method by using
  41247. * a Occlusion Query API.
  41248. *
  41249. * @abstract
  41250. * @param {RenderContext} renderContext - The render context.
  41251. * @param {Object3D} object - The 3D object to test.
  41252. * @return {boolean} Whether the 3D object is fully occluded or not.
  41253. */
  41254. isOccluded( /*renderContext, object*/ ) {}
  41255. /**
  41256. * Resolves the time stamp for the given render context and type.
  41257. *
  41258. * @async
  41259. * @abstract
  41260. * @param {string} [type='render'] - The type of the time stamp.
  41261. * @return {Promise<number>} A Promise that resolves with the time stamp.
  41262. */
  41263. async resolveTimestampsAsync( type = 'render' ) {
  41264. if ( ! this.trackTimestamp ) {
  41265. warnOnce( 'WebGPURenderer: Timestamp tracking is disabled.' );
  41266. return;
  41267. }
  41268. const queryPool = this.timestampQueryPool[ type ];
  41269. if ( ! queryPool ) {
  41270. warnOnce( `WebGPURenderer: No timestamp query pool for type '${type}' found.` );
  41271. return;
  41272. }
  41273. const duration = await queryPool.resolveQueriesAsync();
  41274. this.renderer.info[ type ].timestamp = duration;
  41275. return duration;
  41276. }
  41277. /**
  41278. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  41279. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  41280. *
  41281. * @async
  41282. * @abstract
  41283. * @return {Promise} A Promise that resolves when synchronization has been finished.
  41284. */
  41285. async waitForGPU() {}
  41286. /**
  41287. * This method performs a readback operation by moving buffer data from
  41288. * a storage buffer attribute from the GPU to the CPU.
  41289. *
  41290. * @async
  41291. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  41292. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  41293. */
  41294. async getArrayBufferAsync( /* attribute */ ) {}
  41295. /**
  41296. * Checks if the given feature is supported by the backend.
  41297. *
  41298. * @async
  41299. * @abstract
  41300. * @param {string} name - The feature's name.
  41301. * @return {Promise<boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  41302. */
  41303. async hasFeatureAsync( /*name*/ ) { }
  41304. /**
  41305. * Checks if the given feature is supported by the backend.
  41306. *
  41307. * @abstract
  41308. * @param {string} name - The feature's name.
  41309. * @return {boolean} Whether the feature is supported or not.
  41310. */
  41311. hasFeature( /*name*/ ) {}
  41312. /**
  41313. * Returns the maximum anisotropy texture filtering value.
  41314. *
  41315. * @abstract
  41316. * @return {number} The maximum anisotropy texture filtering value.
  41317. */
  41318. getMaxAnisotropy() {}
  41319. /**
  41320. * Returns the drawing buffer size.
  41321. *
  41322. * @return {Vector2} The drawing buffer size.
  41323. */
  41324. getDrawingBufferSize() {
  41325. _vector2 = _vector2 || new Vector2();
  41326. return this.renderer.getDrawingBufferSize( _vector2 );
  41327. }
  41328. /**
  41329. * Defines the scissor test.
  41330. *
  41331. * @abstract
  41332. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  41333. */
  41334. setScissorTest( /*boolean*/ ) { }
  41335. /**
  41336. * Returns the clear color and alpha into a single
  41337. * color object.
  41338. *
  41339. * @return {Color4} The clear color.
  41340. */
  41341. getClearColor() {
  41342. const renderer = this.renderer;
  41343. _color4 = _color4 || new Color4();
  41344. renderer.getClearColor( _color4 );
  41345. _color4.getRGB( _color4 );
  41346. return _color4;
  41347. }
  41348. /**
  41349. * Returns the DOM element. If no DOM element exists, the backend
  41350. * creates a new one.
  41351. *
  41352. * @return {HTMLCanvasElement} The DOM element.
  41353. */
  41354. getDomElement() {
  41355. let domElement = this.domElement;
  41356. if ( domElement === null ) {
  41357. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  41358. // OffscreenCanvas does not have setAttribute, see #22811
  41359. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  41360. this.domElement = domElement;
  41361. }
  41362. return domElement;
  41363. }
  41364. /**
  41365. * Sets a dictionary for the given object into the
  41366. * internal data structure.
  41367. *
  41368. * @param {Object} object - The object.
  41369. * @param {Object} value - The dictionary to set.
  41370. */
  41371. set( object, value ) {
  41372. this.data.set( object, value );
  41373. }
  41374. /**
  41375. * Returns the dictionary for the given object.
  41376. *
  41377. * @param {Object} object - The object.
  41378. * @return {Object} The object's dictionary.
  41379. */
  41380. get( object ) {
  41381. let map = this.data.get( object );
  41382. if ( map === undefined ) {
  41383. map = {};
  41384. this.data.set( object, map );
  41385. }
  41386. return map;
  41387. }
  41388. /**
  41389. * Checks if the given object has a dictionary
  41390. * with data defined.
  41391. *
  41392. * @param {Object} object - The object.
  41393. * @return {boolean} Whether a dictionary for the given object as been defined or not.
  41394. */
  41395. has( object ) {
  41396. return this.data.has( object );
  41397. }
  41398. /**
  41399. * Deletes an object from the internal data structure.
  41400. *
  41401. * @param {Object} object - The object to delete.
  41402. */
  41403. delete( object ) {
  41404. this.data.delete( object );
  41405. }
  41406. /**
  41407. * Frees internal resources.
  41408. *
  41409. * @abstract
  41410. */
  41411. dispose() { }
  41412. }
  41413. let _id$1 = 0;
  41414. /**
  41415. * This module is internally used in context of compute shaders.
  41416. * This type of shader is not natively supported in WebGL 2 and
  41417. * thus implemented via Transform Feedback. `DualAttributeData`
  41418. * manages the related data.
  41419. *
  41420. * @private
  41421. */
  41422. class DualAttributeData {
  41423. constructor( attributeData, dualBuffer ) {
  41424. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  41425. this.type = attributeData.type;
  41426. this.bufferType = attributeData.bufferType;
  41427. this.pbo = attributeData.pbo;
  41428. this.byteLength = attributeData.byteLength;
  41429. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  41430. this.version = attributeData.version;
  41431. this.isInteger = attributeData.isInteger;
  41432. this.activeBufferIndex = 0;
  41433. this.baseId = attributeData.id;
  41434. }
  41435. get id() {
  41436. return `${ this.baseId }|${ this.activeBufferIndex }`;
  41437. }
  41438. get bufferGPU() {
  41439. return this.buffers[ this.activeBufferIndex ];
  41440. }
  41441. get transformBuffer() {
  41442. return this.buffers[ this.activeBufferIndex ^ 1 ];
  41443. }
  41444. switchBuffers() {
  41445. this.activeBufferIndex ^= 1;
  41446. }
  41447. }
  41448. /**
  41449. * A WebGL 2 backend utility module for managing shader attributes.
  41450. *
  41451. * @private
  41452. */
  41453. class WebGLAttributeUtils {
  41454. /**
  41455. * Constructs a new utility object.
  41456. *
  41457. * @param {WebGLBackend} backend - The WebGL 2 backend.
  41458. */
  41459. constructor( backend ) {
  41460. /**
  41461. * A reference to the WebGL 2 backend.
  41462. *
  41463. * @type {WebGLBackend}
  41464. */
  41465. this.backend = backend;
  41466. }
  41467. /**
  41468. * Creates the GPU buffer for the given buffer attribute.
  41469. *
  41470. * @param {BufferAttribute} attribute - The buffer attribute.
  41471. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  41472. */
  41473. createAttribute( attribute, bufferType ) {
  41474. const backend = this.backend;
  41475. const { gl } = backend;
  41476. const array = attribute.array;
  41477. const usage = attribute.usage || gl.STATIC_DRAW;
  41478. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  41479. const bufferData = backend.get( bufferAttribute );
  41480. let bufferGPU = bufferData.bufferGPU;
  41481. if ( bufferGPU === undefined ) {
  41482. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  41483. bufferData.bufferGPU = bufferGPU;
  41484. bufferData.bufferType = bufferType;
  41485. bufferData.version = bufferAttribute.version;
  41486. }
  41487. //attribute.onUploadCallback();
  41488. let type;
  41489. if ( array instanceof Float32Array ) {
  41490. type = gl.FLOAT;
  41491. } else if ( typeof Float16Array !== 'undefined' && array instanceof Float16Array ) {
  41492. type = gl.HALF_FLOAT;
  41493. } else if ( array instanceof Uint16Array ) {
  41494. if ( attribute.isFloat16BufferAttribute ) {
  41495. type = gl.HALF_FLOAT;
  41496. } else {
  41497. type = gl.UNSIGNED_SHORT;
  41498. }
  41499. } else if ( array instanceof Int16Array ) {
  41500. type = gl.SHORT;
  41501. } else if ( array instanceof Uint32Array ) {
  41502. type = gl.UNSIGNED_INT;
  41503. } else if ( array instanceof Int32Array ) {
  41504. type = gl.INT;
  41505. } else if ( array instanceof Int8Array ) {
  41506. type = gl.BYTE;
  41507. } else if ( array instanceof Uint8Array ) {
  41508. type = gl.UNSIGNED_BYTE;
  41509. } else if ( array instanceof Uint8ClampedArray ) {
  41510. type = gl.UNSIGNED_BYTE;
  41511. } else {
  41512. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  41513. }
  41514. let attributeData = {
  41515. bufferGPU,
  41516. bufferType,
  41517. type,
  41518. byteLength: array.byteLength,
  41519. bytesPerElement: array.BYTES_PER_ELEMENT,
  41520. version: attribute.version,
  41521. pbo: attribute.pbo,
  41522. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType,
  41523. id: _id$1 ++
  41524. };
  41525. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  41526. // create buffer for transform feedback use
  41527. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  41528. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  41529. }
  41530. backend.set( attribute, attributeData );
  41531. }
  41532. /**
  41533. * Updates the GPU buffer of the given buffer attribute.
  41534. *
  41535. * @param {BufferAttribute} attribute - The buffer attribute.
  41536. */
  41537. updateAttribute( attribute ) {
  41538. const backend = this.backend;
  41539. const { gl } = backend;
  41540. const array = attribute.array;
  41541. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  41542. const bufferData = backend.get( bufferAttribute );
  41543. const bufferType = bufferData.bufferType;
  41544. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  41545. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  41546. if ( updateRanges.length === 0 ) {
  41547. // Not using update ranges
  41548. gl.bufferSubData( bufferType, 0, array );
  41549. } else {
  41550. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  41551. const range = updateRanges[ i ];
  41552. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  41553. array, range.start, range.count );
  41554. }
  41555. bufferAttribute.clearUpdateRanges();
  41556. }
  41557. gl.bindBuffer( bufferType, null );
  41558. bufferData.version = bufferAttribute.version;
  41559. }
  41560. /**
  41561. * Destroys the GPU buffer of the given buffer attribute.
  41562. *
  41563. * @param {BufferAttribute} attribute - The buffer attribute.
  41564. */
  41565. destroyAttribute( attribute ) {
  41566. const backend = this.backend;
  41567. const { gl } = backend;
  41568. if ( attribute.isInterleavedBufferAttribute ) {
  41569. backend.delete( attribute.data );
  41570. }
  41571. const attributeData = backend.get( attribute );
  41572. gl.deleteBuffer( attributeData.bufferGPU );
  41573. backend.delete( attribute );
  41574. }
  41575. /**
  41576. * This method performs a readback operation by moving buffer data from
  41577. * a storage buffer attribute from the GPU to the CPU.
  41578. *
  41579. * @async
  41580. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  41581. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  41582. */
  41583. async getArrayBufferAsync( attribute ) {
  41584. const backend = this.backend;
  41585. const { gl } = backend;
  41586. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  41587. const { bufferGPU } = backend.get( bufferAttribute );
  41588. const array = attribute.array;
  41589. const byteLength = array.byteLength;
  41590. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  41591. const writeBuffer = gl.createBuffer();
  41592. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  41593. gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ );
  41594. gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength );
  41595. await backend.utils._clientWaitAsync();
  41596. const dstBuffer = new attribute.array.constructor( array.length );
  41597. // Ensure the buffer is bound before reading
  41598. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  41599. gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer );
  41600. gl.deleteBuffer( writeBuffer );
  41601. gl.bindBuffer( gl.COPY_READ_BUFFER, null );
  41602. gl.bindBuffer( gl.COPY_WRITE_BUFFER, null );
  41603. return dstBuffer.buffer;
  41604. }
  41605. /**
  41606. * Creates a WebGL buffer with the given data.
  41607. *
  41608. * @private
  41609. * @param {WebGL2RenderingContext} gl - The rendering context.
  41610. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  41611. * @param {TypedArray} array - The array of the buffer attribute.
  41612. * @param {GLenum} usage - The usage.
  41613. * @return {WebGLBuffer} The WebGL buffer.
  41614. */
  41615. _createBuffer( gl, bufferType, array, usage ) {
  41616. const bufferGPU = gl.createBuffer();
  41617. gl.bindBuffer( bufferType, bufferGPU );
  41618. gl.bufferData( bufferType, array, usage );
  41619. gl.bindBuffer( bufferType, null );
  41620. return bufferGPU;
  41621. }
  41622. }
  41623. let equationToGL, factorToGL;
  41624. /**
  41625. * A WebGL 2 backend utility module for managing the WebGL state.
  41626. *
  41627. * The major goal of this module is to reduce the number of state changes
  41628. * by caching the WEbGL state with a series of variables. In this way, the
  41629. * renderer only executes state change commands when necessary which
  41630. * improves the overall performance.
  41631. *
  41632. * @private
  41633. */
  41634. class WebGLState {
  41635. /**
  41636. * Constructs a new utility object.
  41637. *
  41638. * @param {WebGLBackend} backend - The WebGL 2 backend.
  41639. */
  41640. constructor( backend ) {
  41641. /**
  41642. * A reference to the WebGL 2 backend.
  41643. *
  41644. * @type {WebGLBackend}
  41645. */
  41646. this.backend = backend;
  41647. /**
  41648. * A reference to the rendering context.
  41649. *
  41650. * @type {WebGL2RenderingContext}
  41651. */
  41652. this.gl = this.backend.gl;
  41653. // Below properties are intended to cache
  41654. // the WebGL state and are not explicitly
  41655. // documented for convenience reasons.
  41656. this.enabled = {};
  41657. this.currentFlipSided = null;
  41658. this.currentCullFace = null;
  41659. this.currentProgram = null;
  41660. this.currentBlendingEnabled = false;
  41661. this.currentBlending = null;
  41662. this.currentBlendSrc = null;
  41663. this.currentBlendDst = null;
  41664. this.currentBlendSrcAlpha = null;
  41665. this.currentBlendDstAlpha = null;
  41666. this.currentPremultipledAlpha = null;
  41667. this.currentPolygonOffsetFactor = null;
  41668. this.currentPolygonOffsetUnits = null;
  41669. this.currentColorMask = null;
  41670. this.currentDepthFunc = null;
  41671. this.currentDepthMask = null;
  41672. this.currentStencilFunc = null;
  41673. this.currentStencilRef = null;
  41674. this.currentStencilFuncMask = null;
  41675. this.currentStencilFail = null;
  41676. this.currentStencilZFail = null;
  41677. this.currentStencilZPass = null;
  41678. this.currentStencilMask = null;
  41679. this.currentLineWidth = null;
  41680. this.currentClippingPlanes = 0;
  41681. this.currentVAO = null;
  41682. this.currentIndex = null;
  41683. this.currentBoundFramebuffers = {};
  41684. this.currentDrawbuffers = new WeakMap();
  41685. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  41686. this.currentTextureSlot = null;
  41687. this.currentBoundTextures = {};
  41688. this.currentBoundBufferBases = {};
  41689. this._init();
  41690. }
  41691. /**
  41692. * Inits the state of the utility.
  41693. *
  41694. * @private
  41695. */
  41696. _init() {
  41697. const gl = this.gl;
  41698. // Store only WebGL constants here.
  41699. equationToGL = {
  41700. [ AddEquation ]: gl.FUNC_ADD,
  41701. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  41702. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  41703. };
  41704. factorToGL = {
  41705. [ ZeroFactor ]: gl.ZERO,
  41706. [ OneFactor ]: gl.ONE,
  41707. [ SrcColorFactor ]: gl.SRC_COLOR,
  41708. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  41709. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  41710. [ DstColorFactor ]: gl.DST_COLOR,
  41711. [ DstAlphaFactor ]: gl.DST_ALPHA,
  41712. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  41713. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  41714. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  41715. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  41716. };
  41717. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  41718. const viewportParam = gl.getParameter( gl.VIEWPORT );
  41719. this.currentScissor = new Vector4().fromArray( scissorParam );
  41720. this.currentViewport = new Vector4().fromArray( viewportParam );
  41721. this._tempVec4 = new Vector4();
  41722. }
  41723. /**
  41724. * Enables the given WebGL capability.
  41725. *
  41726. * This method caches the capability state so
  41727. * `gl.enable()` is only called when necessary.
  41728. *
  41729. * @param {GLenum} id - The capability to enable.
  41730. */
  41731. enable( id ) {
  41732. const { enabled } = this;
  41733. if ( enabled[ id ] !== true ) {
  41734. this.gl.enable( id );
  41735. enabled[ id ] = true;
  41736. }
  41737. }
  41738. /**
  41739. * Disables the given WebGL capability.
  41740. *
  41741. * This method caches the capability state so
  41742. * `gl.disable()` is only called when necessary.
  41743. *
  41744. * @param {GLenum} id - The capability to enable.
  41745. */
  41746. disable( id ) {
  41747. const { enabled } = this;
  41748. if ( enabled[ id ] !== false ) {
  41749. this.gl.disable( id );
  41750. enabled[ id ] = false;
  41751. }
  41752. }
  41753. /**
  41754. * Specifies whether polygons are front- or back-facing
  41755. * by setting the winding orientation.
  41756. *
  41757. * This method caches the state so `gl.frontFace()` is only
  41758. * called when necessary.
  41759. *
  41760. * @param {boolean} flipSided - Whether triangles flipped their sides or not.
  41761. */
  41762. setFlipSided( flipSided ) {
  41763. if ( this.currentFlipSided !== flipSided ) {
  41764. const { gl } = this;
  41765. if ( flipSided ) {
  41766. gl.frontFace( gl.CW );
  41767. } else {
  41768. gl.frontFace( gl.CCW );
  41769. }
  41770. this.currentFlipSided = flipSided;
  41771. }
  41772. }
  41773. /**
  41774. * Specifies whether or not front- and/or back-facing
  41775. * polygons can be culled.
  41776. *
  41777. * This method caches the state so `gl.cullFace()` is only
  41778. * called when necessary.
  41779. *
  41780. * @param {number} cullFace - Defines which polygons are candidates for culling.
  41781. */
  41782. setCullFace( cullFace ) {
  41783. const { gl } = this;
  41784. if ( cullFace !== CullFaceNone ) {
  41785. this.enable( gl.CULL_FACE );
  41786. if ( cullFace !== this.currentCullFace ) {
  41787. if ( cullFace === CullFaceBack ) {
  41788. gl.cullFace( gl.BACK );
  41789. } else if ( cullFace === CullFaceFront ) {
  41790. gl.cullFace( gl.FRONT );
  41791. } else {
  41792. gl.cullFace( gl.FRONT_AND_BACK );
  41793. }
  41794. }
  41795. } else {
  41796. this.disable( gl.CULL_FACE );
  41797. }
  41798. this.currentCullFace = cullFace;
  41799. }
  41800. /**
  41801. * Specifies the width of line primitives.
  41802. *
  41803. * This method caches the state so `gl.lineWidth()` is only
  41804. * called when necessary.
  41805. *
  41806. * @param {number} width - The line width.
  41807. */
  41808. setLineWidth( width ) {
  41809. const { currentLineWidth, gl } = this;
  41810. if ( width !== currentLineWidth ) {
  41811. gl.lineWidth( width );
  41812. this.currentLineWidth = width;
  41813. }
  41814. }
  41815. /**
  41816. * Defines the blending.
  41817. *
  41818. * This method caches the state so `gl.blendEquation()`, `gl.blendEquationSeparate()`,
  41819. * `gl.blendFunc()` and `gl.blendFuncSeparate()` are only called when necessary.
  41820. *
  41821. * @param {number} blending - The blending type.
  41822. * @param {number} blendEquation - The blending equation.
  41823. * @param {number} blendSrc - Only relevant for custom blending. The RGB source blending factor.
  41824. * @param {number} blendDst - Only relevant for custom blending. The RGB destination blending factor.
  41825. * @param {number} blendEquationAlpha - Only relevant for custom blending. The blending equation for alpha.
  41826. * @param {number} blendSrcAlpha - Only relevant for custom blending. The alpha source blending factor.
  41827. * @param {number} blendDstAlpha - Only relevant for custom blending. The alpha destination blending factor.
  41828. * @param {boolean} premultipliedAlpha - Whether premultiplied alpha is enabled or not.
  41829. */
  41830. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  41831. const { gl } = this;
  41832. if ( blending === NoBlending ) {
  41833. if ( this.currentBlendingEnabled === true ) {
  41834. this.disable( gl.BLEND );
  41835. this.currentBlendingEnabled = false;
  41836. }
  41837. return;
  41838. }
  41839. if ( this.currentBlendingEnabled === false ) {
  41840. this.enable( gl.BLEND );
  41841. this.currentBlendingEnabled = true;
  41842. }
  41843. if ( blending !== CustomBlending ) {
  41844. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  41845. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  41846. gl.blendEquation( gl.FUNC_ADD );
  41847. this.currentBlendEquation = AddEquation;
  41848. this.currentBlendEquationAlpha = AddEquation;
  41849. }
  41850. if ( premultipliedAlpha ) {
  41851. switch ( blending ) {
  41852. case NormalBlending:
  41853. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  41854. break;
  41855. case AdditiveBlending:
  41856. gl.blendFunc( gl.ONE, gl.ONE );
  41857. break;
  41858. case SubtractiveBlending:
  41859. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  41860. break;
  41861. case MultiplyBlending:
  41862. gl.blendFuncSeparate( gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ZERO, gl.ONE );
  41863. break;
  41864. default:
  41865. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  41866. break;
  41867. }
  41868. } else {
  41869. switch ( blending ) {
  41870. case NormalBlending:
  41871. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  41872. break;
  41873. case AdditiveBlending:
  41874. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE, gl.ONE, gl.ONE );
  41875. break;
  41876. case SubtractiveBlending:
  41877. console.error( 'THREE.WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true' );
  41878. break;
  41879. case MultiplyBlending:
  41880. console.error( 'THREE.WebGLState: MultiplyBlending requires material.premultipliedAlpha = true' );
  41881. break;
  41882. default:
  41883. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  41884. break;
  41885. }
  41886. }
  41887. this.currentBlendSrc = null;
  41888. this.currentBlendDst = null;
  41889. this.currentBlendSrcAlpha = null;
  41890. this.currentBlendDstAlpha = null;
  41891. this.currentBlending = blending;
  41892. this.currentPremultipledAlpha = premultipliedAlpha;
  41893. }
  41894. return;
  41895. }
  41896. // custom blending
  41897. blendEquationAlpha = blendEquationAlpha || blendEquation;
  41898. blendSrcAlpha = blendSrcAlpha || blendSrc;
  41899. blendDstAlpha = blendDstAlpha || blendDst;
  41900. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  41901. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  41902. this.currentBlendEquation = blendEquation;
  41903. this.currentBlendEquationAlpha = blendEquationAlpha;
  41904. }
  41905. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  41906. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  41907. this.currentBlendSrc = blendSrc;
  41908. this.currentBlendDst = blendDst;
  41909. this.currentBlendSrcAlpha = blendSrcAlpha;
  41910. this.currentBlendDstAlpha = blendDstAlpha;
  41911. }
  41912. this.currentBlending = blending;
  41913. this.currentPremultipledAlpha = false;
  41914. }
  41915. /**
  41916. * Specifies whether colors can be written when rendering
  41917. * into a framebuffer or not.
  41918. *
  41919. * This method caches the state so `gl.colorMask()` is only
  41920. * called when necessary.
  41921. *
  41922. * @param {boolean} colorMask - The color mask.
  41923. */
  41924. setColorMask( colorMask ) {
  41925. if ( this.currentColorMask !== colorMask ) {
  41926. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  41927. this.currentColorMask = colorMask;
  41928. }
  41929. }
  41930. /**
  41931. * Specifies whether the depth test is enabled or not.
  41932. *
  41933. * @param {boolean} depthTest - Whether the depth test is enabled or not.
  41934. */
  41935. setDepthTest( depthTest ) {
  41936. const { gl } = this;
  41937. if ( depthTest ) {
  41938. this.enable( gl.DEPTH_TEST );
  41939. } else {
  41940. this.disable( gl.DEPTH_TEST );
  41941. }
  41942. }
  41943. /**
  41944. * Specifies whether depth values can be written when rendering
  41945. * into a framebuffer or not.
  41946. *
  41947. * This method caches the state so `gl.depthMask()` is only
  41948. * called when necessary.
  41949. *
  41950. * @param {boolean} depthMask - The depth mask.
  41951. */
  41952. setDepthMask( depthMask ) {
  41953. if ( this.currentDepthMask !== depthMask ) {
  41954. this.gl.depthMask( depthMask );
  41955. this.currentDepthMask = depthMask;
  41956. }
  41957. }
  41958. /**
  41959. * Specifies the depth compare function.
  41960. *
  41961. * This method caches the state so `gl.depthFunc()` is only
  41962. * called when necessary.
  41963. *
  41964. * @param {number} depthFunc - The depth compare function.
  41965. */
  41966. setDepthFunc( depthFunc ) {
  41967. if ( this.currentDepthFunc !== depthFunc ) {
  41968. const { gl } = this;
  41969. switch ( depthFunc ) {
  41970. case NeverDepth:
  41971. gl.depthFunc( gl.NEVER );
  41972. break;
  41973. case AlwaysDepth:
  41974. gl.depthFunc( gl.ALWAYS );
  41975. break;
  41976. case LessDepth:
  41977. gl.depthFunc( gl.LESS );
  41978. break;
  41979. case LessEqualDepth:
  41980. gl.depthFunc( gl.LEQUAL );
  41981. break;
  41982. case EqualDepth:
  41983. gl.depthFunc( gl.EQUAL );
  41984. break;
  41985. case GreaterEqualDepth:
  41986. gl.depthFunc( gl.GEQUAL );
  41987. break;
  41988. case GreaterDepth:
  41989. gl.depthFunc( gl.GREATER );
  41990. break;
  41991. case NotEqualDepth:
  41992. gl.depthFunc( gl.NOTEQUAL );
  41993. break;
  41994. default:
  41995. gl.depthFunc( gl.LEQUAL );
  41996. }
  41997. this.currentDepthFunc = depthFunc;
  41998. }
  41999. }
  42000. /**
  42001. * Specifies the scissor box.
  42002. *
  42003. * @param {number} x - The x-coordinate of the lower left corner of the viewport.
  42004. * @param {number} y - The y-coordinate of the lower left corner of the viewport.
  42005. * @param {number} width - The width of the viewport.
  42006. * @param {number} height - The height of the viewport.
  42007. *
  42008. */
  42009. scissor( x, y, width, height ) {
  42010. const scissor = this._tempVec4.set( x, y, width, height );
  42011. if ( this.currentScissor.equals( scissor ) === false ) {
  42012. const { gl } = this;
  42013. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  42014. this.currentScissor.copy( scissor );
  42015. }
  42016. }
  42017. /**
  42018. * Specifies the viewport.
  42019. *
  42020. * @param {number} x - The x-coordinate of the lower left corner of the viewport.
  42021. * @param {number} y - The y-coordinate of the lower left corner of the viewport.
  42022. * @param {number} width - The width of the viewport.
  42023. * @param {number} height - The height of the viewport.
  42024. *
  42025. */
  42026. viewport( x, y, width, height ) {
  42027. const viewport = this._tempVec4.set( x, y, width, height );
  42028. if ( this.currentViewport.equals( viewport ) === false ) {
  42029. const { gl } = this;
  42030. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  42031. this.currentViewport.copy( viewport );
  42032. }
  42033. }
  42034. /**
  42035. * Defines the scissor test.
  42036. *
  42037. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  42038. */
  42039. setScissorTest( boolean ) {
  42040. const gl = this.gl;
  42041. if ( boolean ) {
  42042. gl.enable( gl.SCISSOR_TEST );
  42043. } else {
  42044. gl.disable( gl.SCISSOR_TEST );
  42045. }
  42046. }
  42047. /**
  42048. * Specifies whether the stencil test is enabled or not.
  42049. *
  42050. * @param {boolean} stencilTest - Whether the stencil test is enabled or not.
  42051. */
  42052. setStencilTest( stencilTest ) {
  42053. const { gl } = this;
  42054. if ( stencilTest ) {
  42055. this.enable( gl.STENCIL_TEST );
  42056. } else {
  42057. this.disable( gl.STENCIL_TEST );
  42058. }
  42059. }
  42060. /**
  42061. * Specifies whether stencil values can be written when rendering
  42062. * into a framebuffer or not.
  42063. *
  42064. * This method caches the state so `gl.stencilMask()` is only
  42065. * called when necessary.
  42066. *
  42067. * @param {boolean} stencilMask - The stencil mask.
  42068. */
  42069. setStencilMask( stencilMask ) {
  42070. if ( this.currentStencilMask !== stencilMask ) {
  42071. this.gl.stencilMask( stencilMask );
  42072. this.currentStencilMask = stencilMask;
  42073. }
  42074. }
  42075. /**
  42076. * Specifies whether the stencil test functions.
  42077. *
  42078. * This method caches the state so `gl.stencilFunc()` is only
  42079. * called when necessary.
  42080. *
  42081. * @param {number} stencilFunc - The stencil compare function.
  42082. * @param {number} stencilRef - The reference value for the stencil test.
  42083. * @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.
  42084. */
  42085. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  42086. if ( this.currentStencilFunc !== stencilFunc ||
  42087. this.currentStencilRef !== stencilRef ||
  42088. this.currentStencilFuncMask !== stencilMask ) {
  42089. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  42090. this.currentStencilFunc = stencilFunc;
  42091. this.currentStencilRef = stencilRef;
  42092. this.currentStencilFuncMask = stencilMask;
  42093. }
  42094. }
  42095. /**
  42096. * Specifies whether the stencil test operation.
  42097. *
  42098. * This method caches the state so `gl.stencilOp()` is only
  42099. * called when necessary.
  42100. *
  42101. * @param {number} stencilFail - The function to use when the stencil test fails.
  42102. * @param {number} stencilZFail - The function to use when the stencil test passes, but the depth test fail.
  42103. * @param {number} stencilZPass - The function to use when both the stencil test and the depth test pass,
  42104. * or when the stencil test passes and there is no depth buffer or depth testing is disabled.
  42105. */
  42106. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  42107. if ( this.currentStencilFail !== stencilFail ||
  42108. this.currentStencilZFail !== stencilZFail ||
  42109. this.currentStencilZPass !== stencilZPass ) {
  42110. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  42111. this.currentStencilFail = stencilFail;
  42112. this.currentStencilZFail = stencilZFail;
  42113. this.currentStencilZPass = stencilZPass;
  42114. }
  42115. }
  42116. /**
  42117. * Configures the WebGL state for the given material.
  42118. *
  42119. * @param {Material} material - The material to configure the state for.
  42120. * @param {number} frontFaceCW - Whether the front faces are counter-clockwise or not.
  42121. * @param {number} hardwareClippingPlanes - The number of hardware clipping planes.
  42122. */
  42123. setMaterial( material, frontFaceCW, hardwareClippingPlanes ) {
  42124. const { gl } = this;
  42125. material.side === DoubleSide
  42126. ? this.disable( gl.CULL_FACE )
  42127. : this.enable( gl.CULL_FACE );
  42128. let flipSided = ( material.side === BackSide );
  42129. if ( frontFaceCW ) flipSided = ! flipSided;
  42130. this.setFlipSided( flipSided );
  42131. ( material.blending === NormalBlending && material.transparent === false )
  42132. ? this.setBlending( NoBlending )
  42133. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  42134. this.setDepthFunc( material.depthFunc );
  42135. this.setDepthTest( material.depthTest );
  42136. this.setDepthMask( material.depthWrite );
  42137. this.setColorMask( material.colorWrite );
  42138. const stencilWrite = material.stencilWrite;
  42139. this.setStencilTest( stencilWrite );
  42140. if ( stencilWrite ) {
  42141. this.setStencilMask( material.stencilWriteMask );
  42142. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  42143. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  42144. }
  42145. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  42146. material.alphaToCoverage === true && this.backend.renderer.samples > 1
  42147. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  42148. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  42149. if ( hardwareClippingPlanes > 0 ) {
  42150. if ( this.currentClippingPlanes !== hardwareClippingPlanes ) {
  42151. const CLIP_DISTANCE0_WEBGL = 0x3000;
  42152. for ( let i = 0; i < 8; i ++ ) {
  42153. if ( i < hardwareClippingPlanes ) {
  42154. this.enable( CLIP_DISTANCE0_WEBGL + i );
  42155. } else {
  42156. this.disable( CLIP_DISTANCE0_WEBGL + i );
  42157. }
  42158. }
  42159. }
  42160. }
  42161. }
  42162. /**
  42163. * Specifies the polygon offset.
  42164. *
  42165. * This method caches the state so `gl.polygonOffset()` is only
  42166. * called when necessary.
  42167. *
  42168. * @param {boolean} polygonOffset - Whether polygon offset is enabled or not.
  42169. * @param {number} factor - The scale factor for the variable depth offset for each polygon.
  42170. * @param {number} units - The multiplier by which an implementation-specific value is multiplied with to create a constant depth offset.
  42171. */
  42172. setPolygonOffset( polygonOffset, factor, units ) {
  42173. const { gl } = this;
  42174. if ( polygonOffset ) {
  42175. this.enable( gl.POLYGON_OFFSET_FILL );
  42176. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  42177. gl.polygonOffset( factor, units );
  42178. this.currentPolygonOffsetFactor = factor;
  42179. this.currentPolygonOffsetUnits = units;
  42180. }
  42181. } else {
  42182. this.disable( gl.POLYGON_OFFSET_FILL );
  42183. }
  42184. }
  42185. /**
  42186. * Defines the usage of the given WebGL program.
  42187. *
  42188. * This method caches the state so `gl.useProgram()` is only
  42189. * called when necessary.
  42190. *
  42191. * @param {WebGLProgram} program - The WebGL program to use.
  42192. * @return {boolean} Whether a program change has been executed or not.
  42193. */
  42194. useProgram( program ) {
  42195. if ( this.currentProgram !== program ) {
  42196. this.gl.useProgram( program );
  42197. this.currentProgram = program;
  42198. return true;
  42199. }
  42200. return false;
  42201. }
  42202. /**
  42203. * Sets the vertex state by binding the given VAO and element buffer.
  42204. *
  42205. * @param {WebGLVertexArrayObject} vao - The VAO.
  42206. * @param {WebGLBuffer} indexBuffer - The index buffer.
  42207. * @return {boolean} Whether a vertex state has been changed or not.
  42208. */
  42209. setVertexState( vao, indexBuffer = null ) {
  42210. const gl = this.gl;
  42211. if ( this.currentVAO !== vao || this.currentIndex !== indexBuffer ) {
  42212. gl.bindVertexArray( vao );
  42213. if ( indexBuffer !== null ) {
  42214. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexBuffer );
  42215. }
  42216. this.currentVAO = vao;
  42217. this.currentIndex = indexBuffer;
  42218. return true;
  42219. }
  42220. return false;
  42221. }
  42222. /**
  42223. * Resets the vertex array state by resetting the VAO and element buffer.
  42224. */
  42225. resetVertexState() {
  42226. const gl = this.gl;
  42227. gl.bindVertexArray( null );
  42228. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, null );
  42229. this.currentVAO = null;
  42230. this.currentIndex = null;
  42231. }
  42232. // framebuffer
  42233. /**
  42234. * Binds the given framebuffer.
  42235. *
  42236. * This method caches the state so `gl.bindFramebuffer()` is only
  42237. * called when necessary.
  42238. *
  42239. * @param {number} target - The binding point (target).
  42240. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer to bind.
  42241. * @return {boolean} Whether a bind has been executed or not.
  42242. */
  42243. bindFramebuffer( target, framebuffer ) {
  42244. const { gl, currentBoundFramebuffers } = this;
  42245. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  42246. gl.bindFramebuffer( target, framebuffer );
  42247. currentBoundFramebuffers[ target ] = framebuffer;
  42248. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  42249. if ( target === gl.DRAW_FRAMEBUFFER ) {
  42250. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  42251. }
  42252. if ( target === gl.FRAMEBUFFER ) {
  42253. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  42254. }
  42255. return true;
  42256. }
  42257. return false;
  42258. }
  42259. /**
  42260. * Defines draw buffers to which fragment colors are written into.
  42261. * Configures the MRT setup of custom framebuffers.
  42262. *
  42263. * This method caches the state so `gl.drawBuffers()` is only
  42264. * called when necessary.
  42265. *
  42266. * @param {RenderContext} renderContext - The render context.
  42267. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer.
  42268. */
  42269. drawBuffers( renderContext, framebuffer ) {
  42270. const { gl } = this;
  42271. let drawBuffers = [];
  42272. let needsUpdate = false;
  42273. if ( renderContext.textures !== null ) {
  42274. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  42275. if ( drawBuffers === undefined ) {
  42276. drawBuffers = [];
  42277. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  42278. }
  42279. const textures = renderContext.textures;
  42280. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  42281. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  42282. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  42283. }
  42284. drawBuffers.length = textures.length;
  42285. needsUpdate = true;
  42286. }
  42287. } else {
  42288. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  42289. drawBuffers[ 0 ] = gl.BACK;
  42290. needsUpdate = true;
  42291. }
  42292. }
  42293. if ( needsUpdate ) {
  42294. gl.drawBuffers( drawBuffers );
  42295. }
  42296. }
  42297. // texture
  42298. /**
  42299. * Makes the given texture unit active.
  42300. *
  42301. * This method caches the state so `gl.activeTexture()` is only
  42302. * called when necessary.
  42303. *
  42304. * @param {number} webglSlot - The texture unit to make active.
  42305. */
  42306. activeTexture( webglSlot ) {
  42307. const { gl, currentTextureSlot, maxTextures } = this;
  42308. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  42309. if ( currentTextureSlot !== webglSlot ) {
  42310. gl.activeTexture( webglSlot );
  42311. this.currentTextureSlot = webglSlot;
  42312. }
  42313. }
  42314. /**
  42315. * Binds the given WebGL texture to a target.
  42316. *
  42317. * This method caches the state so `gl.bindTexture()` is only
  42318. * called when necessary.
  42319. *
  42320. * @param {number} webglType - The binding point (target).
  42321. * @param {WebGLTexture} webglTexture - The WebGL texture to bind.
  42322. * @param {number} webglSlot - The texture.
  42323. */
  42324. bindTexture( webglType, webglTexture, webglSlot ) {
  42325. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  42326. if ( webglSlot === undefined ) {
  42327. if ( currentTextureSlot === null ) {
  42328. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  42329. } else {
  42330. webglSlot = currentTextureSlot;
  42331. }
  42332. }
  42333. let boundTexture = currentBoundTextures[ webglSlot ];
  42334. if ( boundTexture === undefined ) {
  42335. boundTexture = { type: undefined, texture: undefined };
  42336. currentBoundTextures[ webglSlot ] = boundTexture;
  42337. }
  42338. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  42339. if ( currentTextureSlot !== webglSlot ) {
  42340. gl.activeTexture( webglSlot );
  42341. this.currentTextureSlot = webglSlot;
  42342. }
  42343. gl.bindTexture( webglType, webglTexture );
  42344. boundTexture.type = webglType;
  42345. boundTexture.texture = webglTexture;
  42346. }
  42347. }
  42348. /**
  42349. * Binds a given WebGL buffer to a given binding point (target) at a given index.
  42350. *
  42351. * This method caches the state so `gl.bindBufferBase()` is only
  42352. * called when necessary.
  42353. *
  42354. * @param {number} target - The target for the bind operation.
  42355. * @param {number} index - The index of the target.
  42356. * @param {WebGLBuffer} buffer - The WebGL buffer.
  42357. * @return {boolean} Whether a bind has been executed or not.
  42358. */
  42359. bindBufferBase( target, index, buffer ) {
  42360. const { gl } = this;
  42361. const key = `${target}-${index}`;
  42362. if ( this.currentBoundBufferBases[ key ] !== buffer ) {
  42363. gl.bindBufferBase( target, index, buffer );
  42364. this.currentBoundBufferBases[ key ] = buffer;
  42365. return true;
  42366. }
  42367. return false;
  42368. }
  42369. /**
  42370. * Unbinds the current bound texture.
  42371. *
  42372. * This method caches the state so `gl.bindTexture()` is only
  42373. * called when necessary.
  42374. */
  42375. unbindTexture() {
  42376. const { gl, currentTextureSlot, currentBoundTextures } = this;
  42377. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  42378. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  42379. gl.bindTexture( boundTexture.type, null );
  42380. boundTexture.type = undefined;
  42381. boundTexture.texture = undefined;
  42382. }
  42383. }
  42384. }
  42385. /**
  42386. * A WebGL 2 backend utility module with common helpers.
  42387. *
  42388. * @private
  42389. */
  42390. class WebGLUtils {
  42391. /**
  42392. * Constructs a new utility object.
  42393. *
  42394. * @param {WebGLBackend} backend - The WebGL 2 backend.
  42395. */
  42396. constructor( backend ) {
  42397. /**
  42398. * A reference to the WebGL 2 backend.
  42399. *
  42400. * @type {WebGLBackend}
  42401. */
  42402. this.backend = backend;
  42403. /**
  42404. * A reference to the rendering context.
  42405. *
  42406. * @type {WebGL2RenderingContext}
  42407. */
  42408. this.gl = this.backend.gl;
  42409. /**
  42410. * A reference to a backend module holding extension-related
  42411. * utility functions.
  42412. *
  42413. * @type {WebGLExtensions}
  42414. */
  42415. this.extensions = backend.extensions;
  42416. }
  42417. /**
  42418. * Converts the given three.js constant into a WebGL constant.
  42419. * The method currently supports the conversion of texture formats
  42420. * and types.
  42421. *
  42422. * @param {number} p - The three.js constant.
  42423. * @param {string} [colorSpace=NoColorSpace] - The color space.
  42424. * @return {?number} The corresponding WebGL constant.
  42425. */
  42426. convert( p, colorSpace = NoColorSpace ) {
  42427. const { gl, extensions } = this;
  42428. let extension;
  42429. const transfer = ColorManagement.getTransfer( colorSpace );
  42430. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  42431. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  42432. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  42433. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  42434. if ( p === ByteType ) return gl.BYTE;
  42435. if ( p === ShortType ) return gl.SHORT;
  42436. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  42437. if ( p === IntType ) return gl.INT;
  42438. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  42439. if ( p === FloatType ) return gl.FLOAT;
  42440. if ( p === HalfFloatType ) {
  42441. return gl.HALF_FLOAT;
  42442. }
  42443. if ( p === AlphaFormat ) return gl.ALPHA;
  42444. if ( p === RGBFormat ) return gl.RGB;
  42445. if ( p === RGBAFormat ) return gl.RGBA;
  42446. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  42447. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  42448. // WebGL2 formats.
  42449. if ( p === RedFormat ) return gl.RED;
  42450. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  42451. if ( p === RGFormat ) return gl.RG;
  42452. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  42453. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  42454. // S3TC
  42455. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  42456. if ( transfer === SRGBTransfer ) {
  42457. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  42458. if ( extension !== null ) {
  42459. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  42460. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  42461. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  42462. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  42463. } else {
  42464. return null;
  42465. }
  42466. } else {
  42467. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  42468. if ( extension !== null ) {
  42469. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  42470. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  42471. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  42472. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  42473. } else {
  42474. return null;
  42475. }
  42476. }
  42477. }
  42478. // PVRTC
  42479. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  42480. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  42481. if ( extension !== null ) {
  42482. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  42483. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  42484. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  42485. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  42486. } else {
  42487. return null;
  42488. }
  42489. }
  42490. // ETC
  42491. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  42492. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  42493. if ( extension !== null ) {
  42494. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  42495. if ( p === RGBA_ETC2_EAC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  42496. } else {
  42497. return null;
  42498. }
  42499. }
  42500. // ASTC
  42501. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  42502. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  42503. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  42504. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  42505. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  42506. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  42507. if ( extension !== null ) {
  42508. if ( p === RGBA_ASTC_4x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  42509. if ( p === RGBA_ASTC_5x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  42510. if ( p === RGBA_ASTC_5x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  42511. if ( p === RGBA_ASTC_6x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  42512. if ( p === RGBA_ASTC_6x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  42513. if ( p === RGBA_ASTC_8x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  42514. if ( p === RGBA_ASTC_8x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  42515. if ( p === RGBA_ASTC_8x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  42516. if ( p === RGBA_ASTC_10x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  42517. if ( p === RGBA_ASTC_10x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  42518. if ( p === RGBA_ASTC_10x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  42519. if ( p === RGBA_ASTC_10x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  42520. if ( p === RGBA_ASTC_12x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  42521. if ( p === RGBA_ASTC_12x12_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  42522. } else {
  42523. return null;
  42524. }
  42525. }
  42526. // BPTC
  42527. if ( p === RGBA_BPTC_Format ) {
  42528. extension = extensions.get( 'EXT_texture_compression_bptc' );
  42529. if ( extension !== null ) {
  42530. if ( p === RGBA_BPTC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  42531. } else {
  42532. return null;
  42533. }
  42534. }
  42535. // RGTC
  42536. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  42537. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  42538. if ( extension !== null ) {
  42539. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  42540. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  42541. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  42542. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  42543. } else {
  42544. return null;
  42545. }
  42546. }
  42547. //
  42548. if ( p === UnsignedInt248Type ) {
  42549. return gl.UNSIGNED_INT_24_8;
  42550. }
  42551. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  42552. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  42553. }
  42554. /**
  42555. * This method can be used to synchronize the CPU with the GPU by waiting until
  42556. * ongoing GPU commands have been completed.
  42557. *
  42558. * @private
  42559. * @return {Promise} A promise that resolves when all ongoing GPU commands have been completed.
  42560. */
  42561. _clientWaitAsync() {
  42562. const { gl } = this;
  42563. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  42564. gl.flush();
  42565. return new Promise( ( resolve, reject ) => {
  42566. function test() {
  42567. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  42568. if ( res === gl.WAIT_FAILED ) {
  42569. gl.deleteSync( sync );
  42570. reject();
  42571. return;
  42572. }
  42573. if ( res === gl.TIMEOUT_EXPIRED ) {
  42574. requestAnimationFrame( test );
  42575. return;
  42576. }
  42577. gl.deleteSync( sync );
  42578. resolve();
  42579. }
  42580. test();
  42581. } );
  42582. }
  42583. }
  42584. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  42585. /**
  42586. * A WebGL 2 backend utility module for managing textures.
  42587. *
  42588. * @private
  42589. */
  42590. class WebGLTextureUtils {
  42591. /**
  42592. * Constructs a new utility object.
  42593. *
  42594. * @param {WebGLBackend} backend - The WebGL 2 backend.
  42595. */
  42596. constructor( backend ) {
  42597. /**
  42598. * A reference to the WebGL 2 backend.
  42599. *
  42600. * @type {WebGLBackend}
  42601. */
  42602. this.backend = backend;
  42603. /**
  42604. * A reference to the rendering context.
  42605. *
  42606. * @type {WebGL2RenderingContext}
  42607. */
  42608. this.gl = backend.gl;
  42609. /**
  42610. * A reference to a backend module holding extension-related
  42611. * utility functions.
  42612. *
  42613. * @type {WebGLExtensions}
  42614. */
  42615. this.extensions = backend.extensions;
  42616. /**
  42617. * A dictionary for managing default textures. The key
  42618. * is the binding point (target), the value the WEbGL texture object.
  42619. *
  42620. * @type {Object<GLenum,WebGLTexture>}
  42621. */
  42622. this.defaultTextures = {};
  42623. if ( initialized === false ) {
  42624. this._init();
  42625. initialized = true;
  42626. }
  42627. }
  42628. /**
  42629. * Inits the state of the utility.
  42630. *
  42631. * @private
  42632. */
  42633. _init() {
  42634. const gl = this.gl;
  42635. // Store only WebGL constants here.
  42636. wrappingToGL = {
  42637. [ RepeatWrapping ]: gl.REPEAT,
  42638. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  42639. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  42640. };
  42641. filterToGL = {
  42642. [ NearestFilter ]: gl.NEAREST,
  42643. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  42644. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  42645. [ LinearFilter ]: gl.LINEAR,
  42646. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  42647. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  42648. };
  42649. compareToGL = {
  42650. [ NeverCompare ]: gl.NEVER,
  42651. [ AlwaysCompare ]: gl.ALWAYS,
  42652. [ LessCompare ]: gl.LESS,
  42653. [ LessEqualCompare ]: gl.LEQUAL,
  42654. [ EqualCompare ]: gl.EQUAL,
  42655. [ GreaterEqualCompare ]: gl.GEQUAL,
  42656. [ GreaterCompare ]: gl.GREATER,
  42657. [ NotEqualCompare ]: gl.NOTEQUAL
  42658. };
  42659. }
  42660. /**
  42661. * Returns the native texture type for the given texture.
  42662. *
  42663. * @param {Texture} texture - The texture.
  42664. * @return {GLenum} The native texture type.
  42665. */
  42666. getGLTextureType( texture ) {
  42667. const { gl } = this;
  42668. let glTextureType;
  42669. if ( texture.isCubeTexture === true ) {
  42670. glTextureType = gl.TEXTURE_CUBE_MAP;
  42671. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  42672. glTextureType = gl.TEXTURE_2D_ARRAY;
  42673. } else if ( texture.isData3DTexture === true ) { // TODO: isCompressed3DTexture, wait for #26642
  42674. glTextureType = gl.TEXTURE_3D;
  42675. } else {
  42676. glTextureType = gl.TEXTURE_2D;
  42677. }
  42678. return glTextureType;
  42679. }
  42680. /**
  42681. * Returns the native texture type for the given texture.
  42682. *
  42683. * @param {?string} internalFormatName - The internal format name. When `null`, the internal format is derived from the subsequent parameters.
  42684. * @param {GLenum} glFormat - The WebGL format.
  42685. * @param {GLenum} glType - The WebGL type.
  42686. * @param {string} colorSpace - The texture's color space.
  42687. * @param {boolean} [forceLinearTransfer=false] - Whether to force a linear transfer or not.
  42688. * @return {GLenum} The internal format.
  42689. */
  42690. getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  42691. const { gl, extensions } = this;
  42692. if ( internalFormatName !== null ) {
  42693. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  42694. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  42695. }
  42696. let internalFormat = glFormat;
  42697. if ( glFormat === gl.RED ) {
  42698. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  42699. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  42700. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  42701. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16;
  42702. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  42703. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  42704. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  42705. if ( glType === gl.INT ) internalFormat = gl.R32I;
  42706. }
  42707. if ( glFormat === gl.RED_INTEGER ) {
  42708. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  42709. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  42710. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  42711. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  42712. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  42713. if ( glType === gl.INT ) internalFormat = gl.R32I;
  42714. }
  42715. if ( glFormat === gl.RG ) {
  42716. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  42717. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  42718. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  42719. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16;
  42720. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  42721. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  42722. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  42723. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  42724. }
  42725. if ( glFormat === gl.RG_INTEGER ) {
  42726. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  42727. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  42728. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  42729. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  42730. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  42731. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  42732. }
  42733. if ( glFormat === gl.RGB ) {
  42734. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  42735. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  42736. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  42737. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8;
  42738. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16;
  42739. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  42740. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  42741. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  42742. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  42743. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? gl.SRGB8 : gl.RGB8;
  42744. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  42745. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  42746. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  42747. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  42748. }
  42749. if ( glFormat === gl.RGB_INTEGER ) {
  42750. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  42751. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  42752. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  42753. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  42754. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  42755. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  42756. }
  42757. if ( glFormat === gl.RGBA ) {
  42758. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  42759. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  42760. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  42761. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8;
  42762. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16;
  42763. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  42764. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  42765. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  42766. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  42767. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  42768. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  42769. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  42770. }
  42771. if ( glFormat === gl.RGBA_INTEGER ) {
  42772. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  42773. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  42774. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  42775. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  42776. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  42777. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  42778. }
  42779. if ( glFormat === gl.DEPTH_COMPONENT ) {
  42780. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.DEPTH_COMPONENT16;
  42781. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH_COMPONENT24;
  42782. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  42783. }
  42784. if ( glFormat === gl.DEPTH_STENCIL ) {
  42785. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  42786. }
  42787. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  42788. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  42789. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  42790. extensions.get( 'EXT_color_buffer_float' );
  42791. }
  42792. return internalFormat;
  42793. }
  42794. /**
  42795. * Sets the texture parameters for the given texture.
  42796. *
  42797. * @param {GLenum} textureType - The texture type.
  42798. * @param {Texture} texture - The texture.
  42799. */
  42800. setTextureParameters( textureType, texture ) {
  42801. const { gl, extensions, backend } = this;
  42802. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  42803. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  42804. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? gl.NONE : gl.BROWSER_DEFAULT_WEBGL;
  42805. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  42806. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  42807. gl.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  42808. gl.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  42809. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  42810. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  42811. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  42812. // WebGL 2 does not support wrapping for depth 2D array textures
  42813. if ( ! texture.isArrayTexture ) {
  42814. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  42815. }
  42816. }
  42817. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  42818. const hasMipmaps = texture.mipmaps !== undefined && texture.mipmaps.length > 0;
  42819. // follow WebGPU backend mapping for texture filtering
  42820. const minFilter = texture.minFilter === LinearFilter && hasMipmaps ? LinearMipmapLinearFilter : texture.minFilter;
  42821. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  42822. if ( texture.compareFunction ) {
  42823. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  42824. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  42825. }
  42826. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  42827. if ( texture.magFilter === NearestFilter ) return;
  42828. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  42829. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  42830. if ( texture.anisotropy > 1 ) {
  42831. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  42832. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) );
  42833. }
  42834. }
  42835. }
  42836. /**
  42837. * Creates a default texture for the given texture that can be used
  42838. * as a placeholder until the actual texture is ready for usage.
  42839. *
  42840. * @param {Texture} texture - The texture to create a default texture for.
  42841. */
  42842. createDefaultTexture( texture ) {
  42843. const { gl, backend, defaultTextures } = this;
  42844. const glTextureType = this.getGLTextureType( texture );
  42845. let textureGPU = defaultTextures[ glTextureType ];
  42846. if ( textureGPU === undefined ) {
  42847. textureGPU = gl.createTexture();
  42848. backend.state.bindTexture( glTextureType, textureGPU );
  42849. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  42850. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  42851. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  42852. defaultTextures[ glTextureType ] = textureGPU;
  42853. }
  42854. backend.set( texture, {
  42855. textureGPU,
  42856. glTextureType,
  42857. isDefault: true
  42858. } );
  42859. }
  42860. /**
  42861. * Defines a texture on the GPU for the given texture object.
  42862. *
  42863. * @param {Texture} texture - The texture.
  42864. * @param {Object} [options={}] - Optional configuration parameter.
  42865. * @return {undefined}
  42866. */
  42867. createTexture( texture, options ) {
  42868. const { gl, backend } = this;
  42869. const { levels, width, height, depth } = options;
  42870. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  42871. const glType = backend.utils.convert( texture.type );
  42872. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  42873. const textureGPU = gl.createTexture();
  42874. const glTextureType = this.getGLTextureType( texture );
  42875. backend.state.bindTexture( glTextureType, textureGPU );
  42876. this.setTextureParameters( glTextureType, texture );
  42877. if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  42878. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  42879. } else if ( texture.isData3DTexture ) {
  42880. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  42881. } else if ( ! texture.isVideoTexture ) {
  42882. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  42883. }
  42884. backend.set( texture, {
  42885. textureGPU,
  42886. glTextureType,
  42887. glFormat,
  42888. glType,
  42889. glInternalFormat
  42890. } );
  42891. }
  42892. /**
  42893. * Uploads texture buffer data to the GPU memory.
  42894. *
  42895. * @param {WebGLBuffer} buffer - The buffer data.
  42896. * @param {Texture} texture - The texture,
  42897. */
  42898. copyBufferToTexture( buffer, texture ) {
  42899. const { gl, backend } = this;
  42900. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  42901. const { width, height } = texture.source.data;
  42902. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  42903. backend.state.bindTexture( glTextureType, textureGPU );
  42904. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  42905. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  42906. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  42907. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  42908. backend.state.unbindTexture();
  42909. // debug
  42910. // const framebuffer = gl.createFramebuffer();
  42911. // gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  42912. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  42913. // const readout = new Float32Array( width * height * 4 );
  42914. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  42915. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  42916. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  42917. // gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  42918. // console.log( readout );
  42919. }
  42920. /**
  42921. * Uploads the updated texture data to the GPU.
  42922. *
  42923. * @param {Texture} texture - The texture.
  42924. * @param {Object} [options={}] - Optional configuration parameter.
  42925. */
  42926. updateTexture( texture, options ) {
  42927. const { gl } = this;
  42928. const { width, height } = options;
  42929. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  42930. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  42931. return;
  42932. this.backend.state.bindTexture( glTextureType, textureGPU );
  42933. this.setTextureParameters( glTextureType, texture );
  42934. if ( texture.isCompressedTexture ) {
  42935. const mipmaps = texture.mipmaps;
  42936. const image = options.image;
  42937. for ( let i = 0; i < mipmaps.length; i ++ ) {
  42938. const mipmap = mipmaps[ i ];
  42939. if ( texture.isCompressedArrayTexture ) {
  42940. if ( texture.format !== gl.RGBA ) {
  42941. if ( glFormat !== null ) {
  42942. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  42943. } else {
  42944. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  42945. }
  42946. } else {
  42947. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  42948. }
  42949. } else {
  42950. if ( glFormat !== null ) {
  42951. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  42952. } else {
  42953. console.warn( 'Unsupported compressed texture format' );
  42954. }
  42955. }
  42956. }
  42957. } else if ( texture.isCubeTexture ) {
  42958. const images = options.images;
  42959. for ( let i = 0; i < 6; i ++ ) {
  42960. const image = getImage( images[ i ] );
  42961. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  42962. }
  42963. } else if ( texture.isDataArrayTexture || texture.isArrayTexture ) {
  42964. const image = options.image;
  42965. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  42966. } else if ( texture.isData3DTexture ) {
  42967. const image = options.image;
  42968. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  42969. } else if ( texture.isVideoTexture ) {
  42970. texture.update();
  42971. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  42972. } else {
  42973. const image = getImage( options.image );
  42974. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  42975. }
  42976. }
  42977. /**
  42978. * Generates mipmaps for the given texture.
  42979. *
  42980. * @param {Texture} texture - The texture.
  42981. */
  42982. generateMipmaps( texture ) {
  42983. const { gl, backend } = this;
  42984. const { textureGPU, glTextureType } = backend.get( texture );
  42985. backend.state.bindTexture( glTextureType, textureGPU );
  42986. gl.generateMipmap( glTextureType );
  42987. }
  42988. /**
  42989. * Deallocates the render buffers of the given render target.
  42990. *
  42991. * @param {RenderTarget} renderTarget - The render target.
  42992. */
  42993. deallocateRenderBuffers( renderTarget ) {
  42994. const { gl, backend } = this;
  42995. // remove framebuffer reference
  42996. if ( renderTarget ) {
  42997. const renderContextData = backend.get( renderTarget );
  42998. renderContextData.renderBufferStorageSetup = undefined;
  42999. if ( renderContextData.framebuffers ) {
  43000. for ( const cacheKey in renderContextData.framebuffers ) {
  43001. gl.deleteFramebuffer( renderContextData.framebuffers[ cacheKey ] );
  43002. }
  43003. delete renderContextData.framebuffers;
  43004. }
  43005. if ( renderContextData.depthRenderbuffer ) {
  43006. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  43007. delete renderContextData.depthRenderbuffer;
  43008. }
  43009. if ( renderContextData.stencilRenderbuffer ) {
  43010. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  43011. delete renderContextData.stencilRenderbuffer;
  43012. }
  43013. if ( renderContextData.msaaFrameBuffer ) {
  43014. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  43015. delete renderContextData.msaaFrameBuffer;
  43016. }
  43017. if ( renderContextData.msaaRenderbuffers ) {
  43018. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  43019. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  43020. }
  43021. delete renderContextData.msaaRenderbuffers;
  43022. }
  43023. }
  43024. }
  43025. /**
  43026. * Destroys the GPU data for the given texture object.
  43027. *
  43028. * @param {Texture} texture - The texture.
  43029. */
  43030. destroyTexture( texture ) {
  43031. const { gl, backend } = this;
  43032. const { textureGPU, renderTarget } = backend.get( texture );
  43033. this.deallocateRenderBuffers( renderTarget );
  43034. gl.deleteTexture( textureGPU );
  43035. backend.delete( texture );
  43036. }
  43037. /**
  43038. * Copies data of the given source texture to the given destination texture.
  43039. *
  43040. * @param {Texture} srcTexture - The source texture.
  43041. * @param {Texture} dstTexture - The destination texture.
  43042. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  43043. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  43044. * @param {number} [srcLevel=0] - The source mip level to copy from.
  43045. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  43046. */
  43047. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  43048. const { gl, backend } = this;
  43049. const { state } = this.backend;
  43050. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  43051. state.bindTexture( glTextureType, dstTextureGPU );
  43052. // gather the necessary dimensions to copy
  43053. let width, height, depth, minX, minY, minZ;
  43054. let dstX, dstY, dstZ;
  43055. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ dstLevel ] : srcTexture.image;
  43056. if ( srcRegion !== null ) {
  43057. width = srcRegion.max.x - srcRegion.min.x;
  43058. height = srcRegion.max.y - srcRegion.min.y;
  43059. depth = srcRegion.isBox3 ? srcRegion.max.z - srcRegion.min.z : 1;
  43060. minX = srcRegion.min.x;
  43061. minY = srcRegion.min.y;
  43062. minZ = srcRegion.isBox3 ? srcRegion.min.z : 0;
  43063. } else {
  43064. const levelScale = Math.pow( 2, - srcLevel );
  43065. width = Math.floor( image.width * levelScale );
  43066. height = Math.floor( image.height * levelScale );
  43067. if ( srcTexture.isDataArrayTexture || srcTexture.isArrayTexture ) {
  43068. depth = image.depth;
  43069. } else if ( srcTexture.isData3DTexture ) {
  43070. depth = Math.floor( image.depth * levelScale );
  43071. } else {
  43072. depth = 1;
  43073. }
  43074. minX = 0;
  43075. minY = 0;
  43076. minZ = 0;
  43077. }
  43078. if ( dstPosition !== null ) {
  43079. dstX = dstPosition.x;
  43080. dstY = dstPosition.y;
  43081. dstZ = dstPosition.z;
  43082. } else {
  43083. dstX = 0;
  43084. dstY = 0;
  43085. dstZ = 0;
  43086. }
  43087. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  43088. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  43089. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  43090. // used for copying data from cpu
  43091. const currentUnpackRowLen = gl.getParameter( gl.UNPACK_ROW_LENGTH );
  43092. const currentUnpackImageHeight = gl.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  43093. const currentUnpackSkipPixels = gl.getParameter( gl.UNPACK_SKIP_PIXELS );
  43094. const currentUnpackSkipRows = gl.getParameter( gl.UNPACK_SKIP_ROWS );
  43095. const currentUnpackSkipImages = gl.getParameter( gl.UNPACK_SKIP_IMAGES );
  43096. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  43097. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  43098. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  43099. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  43100. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, minZ );
  43101. // set up the src texture
  43102. const isDst3D = dstTexture.isDataArrayTexture || dstTexture.isData3DTexture || dstTexture.isArrayTexture;
  43103. if ( srcTexture.isRenderTargetTexture || srcTexture.isDepthTexture ) {
  43104. const srcTextureData = backend.get( srcTexture );
  43105. const dstTextureData = backend.get( dstTexture );
  43106. const srcRenderContextData = backend.get( srcTextureData.renderTarget );
  43107. const dstRenderContextData = backend.get( dstTextureData.renderTarget );
  43108. const srcFramebuffer = srcRenderContextData.framebuffers[ srcTextureData.cacheKey ];
  43109. const dstFramebuffer = dstRenderContextData.framebuffers[ dstTextureData.cacheKey ];
  43110. state.bindFramebuffer( gl.READ_FRAMEBUFFER, srcFramebuffer );
  43111. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, dstFramebuffer );
  43112. let mask = gl.COLOR_BUFFER_BIT;
  43113. if ( srcTexture.isDepthTexture ) mask = gl.DEPTH_BUFFER_BIT;
  43114. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, mask, gl.NEAREST );
  43115. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  43116. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  43117. } else {
  43118. if ( isDst3D ) {
  43119. // copy data into the 3d texture
  43120. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  43121. gl.texSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image.data );
  43122. } else if ( dstTexture.isCompressedArrayTexture ) {
  43123. gl.compressedTexSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, image.data );
  43124. } else {
  43125. gl.texSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image );
  43126. }
  43127. } else {
  43128. // copy data into the 2d texture
  43129. if ( srcTexture.isDataTexture ) {
  43130. gl.texSubImage2D( glTextureType, dstLevel, dstX, dstY, width, height, glFormat, glType, image.data );
  43131. } else if ( srcTexture.isCompressedTexture ) {
  43132. gl.compressedTexSubImage2D( glTextureType, dstLevel, dstX, dstY, image.width, image.height, glFormat, image.data );
  43133. } else {
  43134. gl.texSubImage2D( glTextureType, dstLevel, dstX, dstY, width, height, glFormat, glType, image );
  43135. }
  43136. }
  43137. }
  43138. // reset values
  43139. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  43140. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  43141. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  43142. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  43143. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  43144. // Generate mipmaps only when copying level 0
  43145. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  43146. gl.generateMipmap( glTextureType );
  43147. }
  43148. state.unbindTexture();
  43149. }
  43150. /**
  43151. * Copies the current bound framebuffer to the given texture.
  43152. *
  43153. * @param {Texture} texture - The destination texture.
  43154. * @param {RenderContext} renderContext - The render context.
  43155. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  43156. */
  43157. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  43158. const { gl } = this;
  43159. const { state } = this.backend;
  43160. const { textureGPU } = this.backend.get( texture );
  43161. const { x, y, z: width, w: height } = rectangle;
  43162. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  43163. const srcHeight = renderContext.renderTarget ? renderContext.renderTarget.height : this.backend.getDrawingBufferSize().y;
  43164. if ( requireDrawFrameBuffer ) {
  43165. const partial = ( x !== 0 || y !== 0 );
  43166. let mask;
  43167. let attachment;
  43168. if ( texture.isDepthTexture === true ) {
  43169. mask = gl.DEPTH_BUFFER_BIT;
  43170. attachment = gl.DEPTH_ATTACHMENT;
  43171. if ( renderContext.stencil ) {
  43172. mask |= gl.STENCIL_BUFFER_BIT;
  43173. }
  43174. } else {
  43175. mask = gl.COLOR_BUFFER_BIT;
  43176. attachment = gl.COLOR_ATTACHMENT0;
  43177. }
  43178. if ( partial ) {
  43179. const renderTargetContextData = this.backend.get( renderContext.renderTarget );
  43180. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  43181. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  43182. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  43183. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  43184. const flippedY = srcHeight - y - height;
  43185. gl.blitFramebuffer( x, flippedY, x + width, flippedY + height, x, flippedY, x + width, flippedY + height, mask, gl.NEAREST );
  43186. state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  43187. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  43188. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, flippedY, width, height );
  43189. state.unbindTexture();
  43190. } else {
  43191. const fb = gl.createFramebuffer();
  43192. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  43193. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  43194. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  43195. gl.deleteFramebuffer( fb );
  43196. }
  43197. } else {
  43198. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  43199. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, srcHeight - height - y, width, height );
  43200. state.unbindTexture();
  43201. }
  43202. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  43203. this.backend._setFramebuffer( renderContext );
  43204. }
  43205. /**
  43206. * SetupS storage for internal depth/stencil buffers and bind to correct framebuffer.
  43207. *
  43208. * @param {WebGLRenderbuffer} renderbuffer - The render buffer.
  43209. * @param {RenderContext} renderContext - The render context.
  43210. * @param {number} samples - The MSAA sample count.
  43211. * @param {boolean} [useMultisampledRTT=false] - Whether to use WEBGL_multisampled_render_to_texture or not.
  43212. */
  43213. setupRenderBufferStorage( renderbuffer, renderContext, samples, useMultisampledRTT = false ) {
  43214. const { gl } = this;
  43215. const renderTarget = renderContext.renderTarget;
  43216. const { depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  43217. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  43218. if ( depthBuffer && ! stencilBuffer ) {
  43219. let glInternalFormat = gl.DEPTH_COMPONENT24;
  43220. if ( useMultisampledRTT === true ) {
  43221. const multisampledRTTExt = this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  43222. multisampledRTTExt.renderbufferStorageMultisampleEXT( gl.RENDERBUFFER, renderTarget.samples, glInternalFormat, width, height );
  43223. } else if ( samples > 0 ) {
  43224. if ( depthTexture && depthTexture.isDepthTexture ) {
  43225. if ( depthTexture.type === gl.FLOAT ) {
  43226. glInternalFormat = gl.DEPTH_COMPONENT32F;
  43227. }
  43228. }
  43229. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  43230. } else {
  43231. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  43232. }
  43233. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  43234. } else if ( depthBuffer && stencilBuffer ) {
  43235. if ( samples > 0 ) {
  43236. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  43237. } else {
  43238. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  43239. }
  43240. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  43241. }
  43242. gl.bindRenderbuffer( gl.RENDERBUFFER, null );
  43243. }
  43244. /**
  43245. * Returns texture data as a typed array.
  43246. *
  43247. * @async
  43248. * @param {Texture} texture - The texture to copy.
  43249. * @param {number} x - The x coordinate of the copy origin.
  43250. * @param {number} y - The y coordinate of the copy origin.
  43251. * @param {number} width - The width of the copy.
  43252. * @param {number} height - The height of the copy.
  43253. * @param {number} faceIndex - The face index.
  43254. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  43255. */
  43256. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  43257. const { backend, gl } = this;
  43258. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  43259. const fb = gl.createFramebuffer();
  43260. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  43261. const target = texture.isCubeTexture ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex : gl.TEXTURE_2D;
  43262. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, target, textureGPU, 0 );
  43263. const typedArrayType = this._getTypedArrayType( glType );
  43264. const bytesPerTexel = this._getBytesPerTexel( glType, glFormat );
  43265. const elementCount = width * height;
  43266. const byteLength = elementCount * bytesPerTexel;
  43267. const buffer = gl.createBuffer();
  43268. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  43269. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  43270. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  43271. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  43272. await backend.utils._clientWaitAsync();
  43273. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  43274. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  43275. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  43276. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  43277. gl.deleteFramebuffer( fb );
  43278. return dstBuffer;
  43279. }
  43280. /**
  43281. * Returns the corresponding typed array type for the given WebGL data type.
  43282. *
  43283. * @private
  43284. * @param {GLenum} glType - The WebGL data type.
  43285. * @return {TypedArray.constructor} The typed array type.
  43286. */
  43287. _getTypedArrayType( glType ) {
  43288. const { gl } = this;
  43289. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  43290. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  43291. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  43292. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  43293. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  43294. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  43295. if ( glType === gl.HALF_FLOAT ) return Uint16Array;
  43296. if ( glType === gl.FLOAT ) return Float32Array;
  43297. throw new Error( `Unsupported WebGL type: ${glType}` );
  43298. }
  43299. /**
  43300. * Returns the bytes-per-texel value for the given WebGL data type and texture format.
  43301. *
  43302. * @private
  43303. * @param {GLenum} glType - The WebGL data type.
  43304. * @param {GLenum} glFormat - The WebGL texture format.
  43305. * @return {number} The bytes-per-texel.
  43306. */
  43307. _getBytesPerTexel( glType, glFormat ) {
  43308. const { gl } = this;
  43309. let bytesPerComponent = 0;
  43310. if ( glType === gl.UNSIGNED_BYTE ) bytesPerComponent = 1;
  43311. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ||
  43312. glType === gl.UNSIGNED_SHORT_5_5_5_1 ||
  43313. glType === gl.UNSIGNED_SHORT_5_6_5 ||
  43314. glType === gl.UNSIGNED_SHORT ||
  43315. glType === gl.HALF_FLOAT ) bytesPerComponent = 2;
  43316. if ( glType === gl.UNSIGNED_INT ||
  43317. glType === gl.FLOAT ) bytesPerComponent = 4;
  43318. if ( glFormat === gl.RGBA ) return bytesPerComponent * 4;
  43319. if ( glFormat === gl.RGB ) return bytesPerComponent * 3;
  43320. if ( glFormat === gl.ALPHA ) return bytesPerComponent;
  43321. }
  43322. }
  43323. function getImage( source ) {
  43324. if ( source.isDataTexture ) {
  43325. return source.image.data;
  43326. } else if ( ( typeof HTMLImageElement !== 'undefined' && source instanceof HTMLImageElement ) ||
  43327. ( typeof HTMLCanvasElement !== 'undefined' && source instanceof HTMLCanvasElement ) ||
  43328. ( typeof ImageBitmap !== 'undefined' && source instanceof ImageBitmap ) ||
  43329. ( typeof OffscreenCanvas !== 'undefined' && source instanceof OffscreenCanvas ) ) {
  43330. return source;
  43331. }
  43332. return source.data;
  43333. }
  43334. /**
  43335. * A WebGL 2 backend utility module for managing extensions.
  43336. *
  43337. * @private
  43338. */
  43339. class WebGLExtensions {
  43340. /**
  43341. * Constructs a new utility object.
  43342. *
  43343. * @param {WebGLBackend} backend - The WebGL 2 backend.
  43344. */
  43345. constructor( backend ) {
  43346. /**
  43347. * A reference to the WebGL 2 backend.
  43348. *
  43349. * @type {WebGLBackend}
  43350. */
  43351. this.backend = backend;
  43352. /**
  43353. * A reference to the rendering context.
  43354. *
  43355. * @type {WebGL2RenderingContext}
  43356. */
  43357. this.gl = this.backend.gl;
  43358. /**
  43359. * A list with all the supported WebGL extensions.
  43360. *
  43361. * @type {Array<string>}
  43362. */
  43363. this.availableExtensions = this.gl.getSupportedExtensions();
  43364. /**
  43365. * A dictionary with requested WebGL extensions.
  43366. * The key is the name of the extension, the value
  43367. * the requested extension object.
  43368. *
  43369. * @type {Object<string,Object>}
  43370. */
  43371. this.extensions = {};
  43372. }
  43373. /**
  43374. * Returns the extension object for the given extension name.
  43375. *
  43376. * @param {string} name - The extension name.
  43377. * @return {Object} The extension object.
  43378. */
  43379. get( name ) {
  43380. let extension = this.extensions[ name ];
  43381. if ( extension === undefined ) {
  43382. extension = this.gl.getExtension( name );
  43383. this.extensions[ name ] = extension;
  43384. }
  43385. return extension;
  43386. }
  43387. /**
  43388. * Returns `true` if the requested extension is available.
  43389. *
  43390. * @param {string} name - The extension name.
  43391. * @return {boolean} Whether the given extension is available or not.
  43392. */
  43393. has( name ) {
  43394. return this.availableExtensions.includes( name );
  43395. }
  43396. }
  43397. /**
  43398. * A WebGL 2 backend utility module for managing the device's capabilities.
  43399. *
  43400. * @private
  43401. */
  43402. class WebGLCapabilities {
  43403. /**
  43404. * Constructs a new utility object.
  43405. *
  43406. * @param {WebGLBackend} backend - The WebGL 2 backend.
  43407. */
  43408. constructor( backend ) {
  43409. /**
  43410. * A reference to the WebGL 2 backend.
  43411. *
  43412. * @type {WebGLBackend}
  43413. */
  43414. this.backend = backend;
  43415. /**
  43416. * This value holds the cached max anisotropy value.
  43417. *
  43418. * @type {?number}
  43419. * @default null
  43420. */
  43421. this.maxAnisotropy = null;
  43422. }
  43423. /**
  43424. * Returns the maximum anisotropy texture filtering value. This value
  43425. * depends on the device and is reported by the `EXT_texture_filter_anisotropic`
  43426. * WebGL extension.
  43427. *
  43428. * @return {number} The maximum anisotropy texture filtering value.
  43429. */
  43430. getMaxAnisotropy() {
  43431. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  43432. const gl = this.backend.gl;
  43433. const extensions = this.backend.extensions;
  43434. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  43435. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  43436. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  43437. } else {
  43438. this.maxAnisotropy = 0;
  43439. }
  43440. return this.maxAnisotropy;
  43441. }
  43442. }
  43443. const GLFeatureName = {
  43444. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  43445. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  43446. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  43447. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  43448. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  43449. 'WEBKIT_WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  43450. 'WEBGL_compressed_texture_s3tc': 'texture-compression-bc',
  43451. 'EXT_texture_compression_bptc': 'texture-compression-bptc',
  43452. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  43453. 'OVR_multiview2': 'OVR_multiview2'
  43454. };
  43455. class WebGLBufferRenderer {
  43456. constructor( backend ) {
  43457. this.gl = backend.gl;
  43458. this.extensions = backend.extensions;
  43459. this.info = backend.renderer.info;
  43460. this.mode = null;
  43461. this.index = 0;
  43462. this.type = null;
  43463. this.object = null;
  43464. }
  43465. render( start, count ) {
  43466. const { gl, mode, object, type, info, index } = this;
  43467. if ( index !== 0 ) {
  43468. gl.drawElements( mode, count, type, start );
  43469. } else {
  43470. gl.drawArrays( mode, start, count );
  43471. }
  43472. info.update( object, count, 1 );
  43473. }
  43474. renderInstances( start, count, primcount ) {
  43475. const { gl, mode, type, index, object, info } = this;
  43476. if ( primcount === 0 ) return;
  43477. if ( index !== 0 ) {
  43478. gl.drawElementsInstanced( mode, count, type, start, primcount );
  43479. } else {
  43480. gl.drawArraysInstanced( mode, start, count, primcount );
  43481. }
  43482. info.update( object, count, primcount );
  43483. }
  43484. renderMultiDraw( starts, counts, drawCount ) {
  43485. const { extensions, mode, object, info } = this;
  43486. if ( drawCount === 0 ) return;
  43487. const extension = extensions.get( 'WEBGL_multi_draw' );
  43488. if ( extension === null ) {
  43489. for ( let i = 0; i < drawCount; i ++ ) {
  43490. this.render( starts[ i ], counts[ i ] );
  43491. }
  43492. } else {
  43493. if ( this.index !== 0 ) {
  43494. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  43495. } else {
  43496. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  43497. }
  43498. let elementCount = 0;
  43499. for ( let i = 0; i < drawCount; i ++ ) {
  43500. elementCount += counts[ i ];
  43501. }
  43502. info.update( object, elementCount, 1 );
  43503. }
  43504. }
  43505. renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  43506. const { extensions, mode, object, info } = this;
  43507. if ( drawCount === 0 ) return;
  43508. const extension = extensions.get( 'WEBGL_multi_draw' );
  43509. if ( extension === null ) {
  43510. for ( let i = 0; i < drawCount; i ++ ) {
  43511. this.renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  43512. }
  43513. } else {
  43514. if ( this.index !== 0 ) {
  43515. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, this.type, starts, 0, primcount, 0, drawCount );
  43516. } else {
  43517. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  43518. }
  43519. let elementCount = 0;
  43520. for ( let i = 0; i < drawCount; i ++ ) {
  43521. elementCount += counts[ i ] * primcount[ i ];
  43522. }
  43523. info.update( object, elementCount, 1 );
  43524. }
  43525. }
  43526. //
  43527. }
  43528. /**
  43529. * Abstract base class of a timestamp query pool.
  43530. *
  43531. * @abstract
  43532. */
  43533. class TimestampQueryPool {
  43534. /**
  43535. * Creates a new timestamp query pool.
  43536. *
  43537. * @param {number} [maxQueries=256] - Maximum number of queries this pool can hold.
  43538. */
  43539. constructor( maxQueries = 256 ) {
  43540. /**
  43541. * Whether to track timestamps or not.
  43542. *
  43543. * @type {boolean}
  43544. * @default true
  43545. */
  43546. this.trackTimestamp = true;
  43547. /**
  43548. * Maximum number of queries this pool can hold.
  43549. *
  43550. * @type {number}
  43551. * @default 256
  43552. */
  43553. this.maxQueries = maxQueries;
  43554. /**
  43555. * How many queries allocated so far.
  43556. *
  43557. * @type {number}
  43558. * @default 0
  43559. */
  43560. this.currentQueryIndex = 0;
  43561. /**
  43562. * Tracks offsets for different contexts.
  43563. *
  43564. * @type {Map<string, number>}
  43565. */
  43566. this.queryOffsets = new Map();
  43567. /**
  43568. * Whether the pool has been disposed or not.
  43569. *
  43570. * @type {boolean}
  43571. * @default false
  43572. */
  43573. this.isDisposed = false;
  43574. /**
  43575. * TODO
  43576. *
  43577. * @type {number}
  43578. * @default 0
  43579. */
  43580. this.lastValue = 0;
  43581. /**
  43582. * TODO
  43583. *
  43584. * @type {boolean}
  43585. * @default false
  43586. */
  43587. this.pendingResolve = false;
  43588. }
  43589. /**
  43590. * Allocate queries for a specific renderContext.
  43591. *
  43592. * @abstract
  43593. * @param {Object} renderContext - The render context to allocate queries for.
  43594. * @returns {?number}
  43595. */
  43596. allocateQueriesForContext( /* renderContext */ ) {}
  43597. /**
  43598. * Resolve all timestamps and return data (or process them).
  43599. *
  43600. * @abstract
  43601. * @async
  43602. * @returns {Promise<number>|number} The resolved timestamp value.
  43603. */
  43604. async resolveQueriesAsync() {}
  43605. /**
  43606. * Dispose of the query pool.
  43607. *
  43608. * @abstract
  43609. */
  43610. dispose() {}
  43611. }
  43612. /**
  43613. * Manages a pool of WebGL timestamp queries for performance measurement.
  43614. * Handles creation, execution, and resolution of timer queries using WebGL extensions.
  43615. *
  43616. * @augments TimestampQueryPool
  43617. */
  43618. class WebGLTimestampQueryPool extends TimestampQueryPool {
  43619. /**
  43620. * Creates a new WebGL timestamp query pool.
  43621. *
  43622. * @param {WebGLRenderingContext|WebGL2RenderingContext} gl - The WebGL context.
  43623. * @param {string} type - The type identifier for this query pool.
  43624. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  43625. */
  43626. constructor( gl, type, maxQueries = 2048 ) {
  43627. super( maxQueries );
  43628. this.gl = gl;
  43629. this.type = type;
  43630. // Check for timer query extensions
  43631. this.ext = gl.getExtension( 'EXT_disjoint_timer_query_webgl2' ) ||
  43632. gl.getExtension( 'EXT_disjoint_timer_query' );
  43633. if ( ! this.ext ) {
  43634. console.warn( 'EXT_disjoint_timer_query not supported; timestamps will be disabled.' );
  43635. this.trackTimestamp = false;
  43636. return;
  43637. }
  43638. // Create query objects
  43639. this.queries = [];
  43640. for ( let i = 0; i < this.maxQueries; i ++ ) {
  43641. this.queries.push( gl.createQuery() );
  43642. }
  43643. this.activeQuery = null;
  43644. this.queryStates = new Map(); // Track state of each query: 'inactive', 'started', 'ended'
  43645. }
  43646. /**
  43647. * Allocates a pair of queries for a given render context.
  43648. *
  43649. * @param {Object} renderContext - The render context to allocate queries for.
  43650. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  43651. */
  43652. allocateQueriesForContext( renderContext ) {
  43653. if ( ! this.trackTimestamp ) return null;
  43654. // Check if we have enough space for a new query pair
  43655. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  43656. 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() } ).` );
  43657. return null;
  43658. }
  43659. const baseOffset = this.currentQueryIndex;
  43660. this.currentQueryIndex += 2;
  43661. // Initialize query states
  43662. this.queryStates.set( baseOffset, 'inactive' );
  43663. this.queryOffsets.set( renderContext.id, baseOffset );
  43664. return baseOffset;
  43665. }
  43666. /**
  43667. * Begins a timestamp query for the specified render context.
  43668. *
  43669. * @param {Object} renderContext - The render context to begin timing for.
  43670. */
  43671. beginQuery( renderContext ) {
  43672. if ( ! this.trackTimestamp || this.isDisposed ) {
  43673. return;
  43674. }
  43675. const baseOffset = this.queryOffsets.get( renderContext.id );
  43676. if ( baseOffset == null ) {
  43677. return;
  43678. }
  43679. // Don't start a new query if there's an active one
  43680. if ( this.activeQuery !== null ) {
  43681. return;
  43682. }
  43683. const query = this.queries[ baseOffset ];
  43684. if ( ! query ) {
  43685. return;
  43686. }
  43687. try {
  43688. // Only begin if query is inactive
  43689. if ( this.queryStates.get( baseOffset ) === 'inactive' ) {
  43690. this.gl.beginQuery( this.ext.TIME_ELAPSED_EXT, query );
  43691. this.activeQuery = baseOffset;
  43692. this.queryStates.set( baseOffset, 'started' );
  43693. }
  43694. } catch ( error ) {
  43695. console.error( 'Error in beginQuery:', error );
  43696. this.activeQuery = null;
  43697. this.queryStates.set( baseOffset, 'inactive' );
  43698. }
  43699. }
  43700. /**
  43701. * Ends the active timestamp query for the specified render context.
  43702. *
  43703. * @param {Object} renderContext - The render context to end timing for.
  43704. * @param {string} renderContext.id - Unique identifier for the render context.
  43705. */
  43706. endQuery( renderContext ) {
  43707. if ( ! this.trackTimestamp || this.isDisposed ) {
  43708. return;
  43709. }
  43710. const baseOffset = this.queryOffsets.get( renderContext.id );
  43711. if ( baseOffset == null ) {
  43712. return;
  43713. }
  43714. // Only end if this is the active query
  43715. if ( this.activeQuery !== baseOffset ) {
  43716. return;
  43717. }
  43718. try {
  43719. this.gl.endQuery( this.ext.TIME_ELAPSED_EXT );
  43720. this.queryStates.set( baseOffset, 'ended' );
  43721. this.activeQuery = null;
  43722. } catch ( error ) {
  43723. console.error( 'Error in endQuery:', error );
  43724. // Reset state on error
  43725. this.queryStates.set( baseOffset, 'inactive' );
  43726. this.activeQuery = null;
  43727. }
  43728. }
  43729. /**
  43730. * Asynchronously resolves all completed queries and returns the total duration.
  43731. *
  43732. * @async
  43733. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  43734. */
  43735. async resolveQueriesAsync() {
  43736. if ( ! this.trackTimestamp || this.pendingResolve ) {
  43737. return this.lastValue;
  43738. }
  43739. this.pendingResolve = true;
  43740. try {
  43741. // Wait for all ended queries to complete
  43742. const resolvePromises = [];
  43743. for ( const [ baseOffset, state ] of this.queryStates ) {
  43744. if ( state === 'ended' ) {
  43745. const query = this.queries[ baseOffset ];
  43746. resolvePromises.push( this.resolveQuery( query ) );
  43747. }
  43748. }
  43749. if ( resolvePromises.length === 0 ) {
  43750. return this.lastValue;
  43751. }
  43752. const results = await Promise.all( resolvePromises );
  43753. const totalDuration = results.reduce( ( acc, val ) => acc + val, 0 );
  43754. // Store the last valid result
  43755. this.lastValue = totalDuration;
  43756. // Reset states
  43757. this.currentQueryIndex = 0;
  43758. this.queryOffsets.clear();
  43759. this.queryStates.clear();
  43760. this.activeQuery = null;
  43761. return totalDuration;
  43762. } catch ( error ) {
  43763. console.error( 'Error resolving queries:', error );
  43764. return this.lastValue;
  43765. } finally {
  43766. this.pendingResolve = false;
  43767. }
  43768. }
  43769. /**
  43770. * Resolves a single query, checking for completion and disjoint operation.
  43771. *
  43772. * @async
  43773. * @param {WebGLQuery} query - The query object to resolve.
  43774. * @returns {Promise<number>} The elapsed time in milliseconds.
  43775. */
  43776. async resolveQuery( query ) {
  43777. return new Promise( ( resolve ) => {
  43778. if ( this.isDisposed ) {
  43779. resolve( this.lastValue );
  43780. return;
  43781. }
  43782. let timeoutId;
  43783. let isResolved = false;
  43784. const cleanup = () => {
  43785. if ( timeoutId ) {
  43786. clearTimeout( timeoutId );
  43787. timeoutId = null;
  43788. }
  43789. };
  43790. const finalizeResolution = ( value ) => {
  43791. if ( ! isResolved ) {
  43792. isResolved = true;
  43793. cleanup();
  43794. resolve( value );
  43795. }
  43796. };
  43797. const checkQuery = () => {
  43798. if ( this.isDisposed ) {
  43799. finalizeResolution( this.lastValue );
  43800. return;
  43801. }
  43802. try {
  43803. // Check if the GPU timer was disjoint (i.e., timing was unreliable)
  43804. const disjoint = this.gl.getParameter( this.ext.GPU_DISJOINT_EXT );
  43805. if ( disjoint ) {
  43806. finalizeResolution( this.lastValue );
  43807. return;
  43808. }
  43809. const available = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT_AVAILABLE );
  43810. if ( ! available ) {
  43811. timeoutId = setTimeout( checkQuery, 1 );
  43812. return;
  43813. }
  43814. const elapsed = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT );
  43815. resolve( Number( elapsed ) / 1e6 ); // Convert nanoseconds to milliseconds
  43816. } catch ( error ) {
  43817. console.error( 'Error checking query:', error );
  43818. resolve( this.lastValue );
  43819. }
  43820. };
  43821. checkQuery();
  43822. } );
  43823. }
  43824. /**
  43825. * Releases all resources held by this query pool.
  43826. * This includes deleting all query objects and clearing internal state.
  43827. */
  43828. dispose() {
  43829. if ( this.isDisposed ) {
  43830. return;
  43831. }
  43832. this.isDisposed = true;
  43833. if ( ! this.trackTimestamp ) return;
  43834. for ( const query of this.queries ) {
  43835. this.gl.deleteQuery( query );
  43836. }
  43837. this.queries = [];
  43838. this.queryStates.clear();
  43839. this.queryOffsets.clear();
  43840. this.lastValue = 0;
  43841. this.activeQuery = null;
  43842. }
  43843. }
  43844. /**
  43845. * A backend implementation targeting WebGL 2.
  43846. *
  43847. * @private
  43848. * @augments Backend
  43849. */
  43850. class WebGLBackend extends Backend {
  43851. /**
  43852. * WebGLBackend options.
  43853. *
  43854. * @typedef {Object} WebGLBackend~Options
  43855. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  43856. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  43857. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  43858. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  43859. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  43860. * @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.
  43861. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  43862. * @property {WebGL2RenderingContext} [context=undefined] - A WebGL 2 rendering context.
  43863. */
  43864. /**
  43865. * Constructs a new WebGPU backend.
  43866. *
  43867. * @param {WebGLBackend~Options} [parameters] - The configuration parameter.
  43868. */
  43869. constructor( parameters = {} ) {
  43870. super( parameters );
  43871. /**
  43872. * This flag can be used for type testing.
  43873. *
  43874. * @type {boolean}
  43875. * @readonly
  43876. * @default true
  43877. */
  43878. this.isWebGLBackend = true;
  43879. /**
  43880. * A reference to a backend module holding shader attribute-related
  43881. * utility functions.
  43882. *
  43883. * @type {?WebGLAttributeUtils}
  43884. * @default null
  43885. */
  43886. this.attributeUtils = null;
  43887. /**
  43888. * A reference to a backend module holding extension-related
  43889. * utility functions.
  43890. *
  43891. * @type {?WebGLExtensions}
  43892. * @default null
  43893. */
  43894. this.extensions = null;
  43895. /**
  43896. * A reference to a backend module holding capability-related
  43897. * utility functions.
  43898. *
  43899. * @type {?WebGLCapabilities}
  43900. * @default null
  43901. */
  43902. this.capabilities = null;
  43903. /**
  43904. * A reference to a backend module holding texture-related
  43905. * utility functions.
  43906. *
  43907. * @type {?WebGLTextureUtils}
  43908. * @default null
  43909. */
  43910. this.textureUtils = null;
  43911. /**
  43912. * A reference to a backend module holding renderer-related
  43913. * utility functions.
  43914. *
  43915. * @type {?WebGLBufferRenderer}
  43916. * @default null
  43917. */
  43918. this.bufferRenderer = null;
  43919. /**
  43920. * A reference to the rendering context.
  43921. *
  43922. * @type {?WebGL2RenderingContext}
  43923. * @default null
  43924. */
  43925. this.gl = null;
  43926. /**
  43927. * A reference to a backend module holding state-related
  43928. * utility functions.
  43929. *
  43930. * @type {?WebGLState}
  43931. * @default null
  43932. */
  43933. this.state = null;
  43934. /**
  43935. * A reference to a backend module holding common
  43936. * utility functions.
  43937. *
  43938. * @type {?WebGLUtils}
  43939. * @default null
  43940. */
  43941. this.utils = null;
  43942. /**
  43943. * Dictionary for caching VAOs.
  43944. *
  43945. * @type {Object<string,WebGLVertexArrayObject>}
  43946. */
  43947. this.vaoCache = {};
  43948. /**
  43949. * Dictionary for caching transform feedback objects.
  43950. *
  43951. * @type {Object<string,WebGLTransformFeedback>}
  43952. */
  43953. this.transformFeedbackCache = {};
  43954. /**
  43955. * Controls if `gl.RASTERIZER_DISCARD` should be enabled or not.
  43956. * Only relevant when using compute shaders.
  43957. *
  43958. * @type {boolean}
  43959. * @default false
  43960. */
  43961. this.discard = false;
  43962. /**
  43963. * A reference to the `EXT_disjoint_timer_query_webgl2` extension. `null` if the
  43964. * device does not support the extension.
  43965. *
  43966. * @type {?EXTDisjointTimerQueryWebGL2}
  43967. * @default null
  43968. */
  43969. this.disjoint = null;
  43970. /**
  43971. * A reference to the `KHR_parallel_shader_compile` extension. `null` if the
  43972. * device does not support the extension.
  43973. *
  43974. * @type {?KHRParallelShaderCompile}
  43975. * @default null
  43976. */
  43977. this.parallel = null;
  43978. /**
  43979. * A reference to the current render context.
  43980. *
  43981. * @private
  43982. * @type {RenderContext}
  43983. * @default null
  43984. */
  43985. this._currentContext = null;
  43986. /**
  43987. * A unique collection of bindings.
  43988. *
  43989. * @private
  43990. * @type {WeakSet<Array<BindGroup>>}
  43991. */
  43992. this._knownBindings = new WeakSet();
  43993. /**
  43994. * Whether the device supports framebuffers invalidation or not.
  43995. *
  43996. * @private
  43997. * @type {boolean}
  43998. */
  43999. this._supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent );
  44000. /**
  44001. * The target framebuffer when rendering with
  44002. * the WebXR device API.
  44003. *
  44004. * @private
  44005. * @type {WebGLFramebuffer}
  44006. * @default null
  44007. */
  44008. this._xrFramebuffer = null;
  44009. }
  44010. /**
  44011. * Initializes the backend so it is ready for usage.
  44012. *
  44013. * @param {Renderer} renderer - The renderer.
  44014. */
  44015. init( renderer ) {
  44016. super.init( renderer );
  44017. //
  44018. const parameters = this.parameters;
  44019. const contextAttributes = {
  44020. antialias: renderer.samples > 0,
  44021. alpha: true, // always true for performance reasons
  44022. depth: renderer.depth,
  44023. stencil: renderer.stencil
  44024. };
  44025. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2', contextAttributes );
  44026. function onContextLost( event ) {
  44027. event.preventDefault();
  44028. const contextLossInfo = {
  44029. api: 'WebGL',
  44030. message: event.statusMessage || 'Unknown reason',
  44031. reason: null,
  44032. originalEvent: event
  44033. };
  44034. renderer.onDeviceLost( contextLossInfo );
  44035. }
  44036. this._onContextLost = onContextLost;
  44037. renderer.domElement.addEventListener( 'webglcontextlost', onContextLost, false );
  44038. this.gl = glContext;
  44039. this.extensions = new WebGLExtensions( this );
  44040. this.capabilities = new WebGLCapabilities( this );
  44041. this.attributeUtils = new WebGLAttributeUtils( this );
  44042. this.textureUtils = new WebGLTextureUtils( this );
  44043. this.bufferRenderer = new WebGLBufferRenderer( this );
  44044. this.state = new WebGLState( this );
  44045. this.utils = new WebGLUtils( this );
  44046. this.extensions.get( 'EXT_color_buffer_float' );
  44047. this.extensions.get( 'WEBGL_clip_cull_distance' );
  44048. this.extensions.get( 'OES_texture_float_linear' );
  44049. this.extensions.get( 'EXT_color_buffer_half_float' );
  44050. this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  44051. this.extensions.get( 'WEBGL_render_shared_exponent' );
  44052. this.extensions.get( 'WEBGL_multi_draw' );
  44053. this.extensions.get( 'OVR_multiview2' );
  44054. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  44055. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  44056. }
  44057. /**
  44058. * The coordinate system of the backend.
  44059. *
  44060. * @type {number}
  44061. * @readonly
  44062. */
  44063. get coordinateSystem() {
  44064. return WebGLCoordinateSystem;
  44065. }
  44066. /**
  44067. * This method performs a readback operation by moving buffer data from
  44068. * a storage buffer attribute from the GPU to the CPU.
  44069. *
  44070. * @async
  44071. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  44072. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  44073. */
  44074. async getArrayBufferAsync( attribute ) {
  44075. return await this.attributeUtils.getArrayBufferAsync( attribute );
  44076. }
  44077. /**
  44078. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  44079. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  44080. *
  44081. * @async
  44082. * @return {Promise} A Promise that resolves when synchronization has been finished.
  44083. */
  44084. async waitForGPU() {
  44085. await this.utils._clientWaitAsync();
  44086. }
  44087. /**
  44088. * Ensures the backend is XR compatible.
  44089. *
  44090. * @async
  44091. * @return {Promise} A Promise that resolve when the renderer is XR compatible.
  44092. */
  44093. async makeXRCompatible() {
  44094. const attributes = this.gl.getContextAttributes();
  44095. if ( attributes.xrCompatible !== true ) {
  44096. await this.gl.makeXRCompatible();
  44097. }
  44098. }
  44099. /**
  44100. * Sets the XR rendering destination.
  44101. *
  44102. * @param {WebGLFramebuffer} xrFramebuffer - The XR framebuffer.
  44103. */
  44104. setXRTarget( xrFramebuffer ) {
  44105. this._xrFramebuffer = xrFramebuffer;
  44106. }
  44107. /**
  44108. * Configures the given XR render target with external textures.
  44109. *
  44110. * This method is only relevant when using the WebXR Layers API.
  44111. *
  44112. * @param {XRRenderTarget} renderTarget - The XR render target.
  44113. * @param {WebGLTexture} colorTexture - A native color texture.
  44114. * @param {?WebGLTexture} [depthTexture=null] - A native depth texture.
  44115. */
  44116. setXRRenderTargetTextures( renderTarget, colorTexture, depthTexture = null ) {
  44117. const gl = this.gl;
  44118. this.set( renderTarget.texture, { textureGPU: colorTexture, glInternalFormat: gl.RGBA8 } ); // see #24698 why RGBA8 and not SRGB8_ALPHA8 is used
  44119. if ( depthTexture !== null ) {
  44120. const glInternalFormat = renderTarget.stencilBuffer ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  44121. this.set( renderTarget.depthTexture, { textureGPU: depthTexture, glInternalFormat: glInternalFormat } );
  44122. // The multisample_render_to_texture extension doesn't work properly if there
  44123. // are midframe flushes and an external depth texture.
  44124. if ( ( this.extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) && renderTarget._autoAllocateDepthBuffer === true && renderTarget.multiview === false ) {
  44125. console.warn( 'THREE.WebGLBackend: Render-to-texture extension was disabled because an external texture was provided' );
  44126. }
  44127. renderTarget._autoAllocateDepthBuffer = false;
  44128. }
  44129. }
  44130. /**
  44131. * Inits a time stamp query for the given render context.
  44132. *
  44133. * @param {RenderContext} renderContext - The render context.
  44134. */
  44135. initTimestampQuery( renderContext ) {
  44136. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  44137. const type = renderContext.isComputeNode ? 'compute' : 'render';
  44138. if ( ! this.timestampQueryPool[ type ] ) {
  44139. // TODO: Variable maxQueries?
  44140. this.timestampQueryPool[ type ] = new WebGLTimestampQueryPool( this.gl, type, 2048 );
  44141. }
  44142. const timestampQueryPool = this.timestampQueryPool[ type ];
  44143. const baseOffset = timestampQueryPool.allocateQueriesForContext( renderContext );
  44144. if ( baseOffset !== null ) {
  44145. timestampQueryPool.beginQuery( renderContext );
  44146. }
  44147. }
  44148. // timestamp utils
  44149. /**
  44150. * Prepares the timestamp buffer.
  44151. *
  44152. * @param {RenderContext} renderContext - The render context.
  44153. */
  44154. prepareTimestampBuffer( renderContext ) {
  44155. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  44156. const type = renderContext.isComputeNode ? 'compute' : 'render';
  44157. const timestampQueryPool = this.timestampQueryPool[ type ];
  44158. timestampQueryPool.endQuery( renderContext );
  44159. }
  44160. /**
  44161. * Returns the backend's rendering context.
  44162. *
  44163. * @return {WebGL2RenderingContext} The rendering context.
  44164. */
  44165. getContext() {
  44166. return this.gl;
  44167. }
  44168. /**
  44169. * This method is executed at the beginning of a render call and prepares
  44170. * the WebGL state for upcoming render calls
  44171. *
  44172. * @param {RenderContext} renderContext - The render context.
  44173. */
  44174. beginRender( renderContext ) {
  44175. const { state } = this;
  44176. const renderContextData = this.get( renderContext );
  44177. //
  44178. if ( renderContext.viewport ) {
  44179. this.updateViewport( renderContext );
  44180. } else {
  44181. const { width, height } = this.getDrawingBufferSize();
  44182. state.viewport( 0, 0, width, height );
  44183. }
  44184. if ( renderContext.scissor ) {
  44185. const { x, y, width, height } = renderContext.scissorValue;
  44186. state.scissor( x, renderContext.height - height - y, width, height );
  44187. }
  44188. //
  44189. this.initTimestampQuery( renderContext );
  44190. renderContextData.previousContext = this._currentContext;
  44191. this._currentContext = renderContext;
  44192. this._setFramebuffer( renderContext );
  44193. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  44194. const occlusionQueryCount = renderContext.occlusionQueryCount;
  44195. if ( occlusionQueryCount > 0 ) {
  44196. // Get a reference to the array of objects with queries. The renderContextData property
  44197. // can be changed by another render pass before the async reading of all previous queries complete
  44198. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  44199. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  44200. renderContextData.lastOcclusionObject = null;
  44201. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  44202. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  44203. renderContextData.occlusionQueryIndex = 0;
  44204. }
  44205. }
  44206. /**
  44207. * This method is executed at the end of a render call and finalizes work
  44208. * after draw calls.
  44209. *
  44210. * @param {RenderContext} renderContext - The render context.
  44211. */
  44212. finishRender( renderContext ) {
  44213. const { gl, state } = this;
  44214. const renderContextData = this.get( renderContext );
  44215. const previousContext = renderContextData.previousContext;
  44216. state.resetVertexState();
  44217. const occlusionQueryCount = renderContext.occlusionQueryCount;
  44218. if ( occlusionQueryCount > 0 ) {
  44219. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  44220. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  44221. }
  44222. this.resolveOccludedAsync( renderContext );
  44223. }
  44224. const textures = renderContext.textures;
  44225. if ( textures !== null ) {
  44226. for ( let i = 0; i < textures.length; i ++ ) {
  44227. const texture = textures[ i ];
  44228. if ( texture.generateMipmaps ) {
  44229. this.generateMipmaps( texture );
  44230. }
  44231. }
  44232. }
  44233. this._currentContext = previousContext;
  44234. const renderTarget = renderContext.renderTarget;
  44235. if ( renderContext.textures !== null && renderTarget ) {
  44236. const renderTargetContextData = this.get( renderTarget );
  44237. if ( renderTarget.samples > 0 && this._useMultisampledExtension( renderTarget ) === false ) {
  44238. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  44239. let mask = gl.COLOR_BUFFER_BIT;
  44240. if ( renderTarget.resolveDepthBuffer ) {
  44241. if ( renderTarget.depthBuffer ) mask |= gl.DEPTH_BUFFER_BIT;
  44242. if ( renderTarget.stencilBuffer && renderTarget.resolveStencilBuffer ) mask |= gl.STENCIL_BUFFER_BIT;
  44243. }
  44244. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  44245. const msaaRenderbuffers = renderTargetContextData.msaaRenderbuffers;
  44246. const textures = renderContext.textures;
  44247. const isMRT = textures.length > 1;
  44248. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  44249. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  44250. if ( isMRT ) {
  44251. // blitFramebuffer() can only copy/resolve the first color attachment of a framebuffer. When using MRT,
  44252. // the engine temporarily removes all attachments and then configures each attachment for the resolve.
  44253. for ( let i = 0; i < textures.length; i ++ ) {
  44254. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, null );
  44255. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.TEXTURE_2D, null, 0 );
  44256. }
  44257. }
  44258. for ( let i = 0; i < textures.length; i ++ ) {
  44259. if ( isMRT ) {
  44260. // configure attachment for resolve
  44261. const { textureGPU } = this.get( textures[ i ] );
  44262. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  44263. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureGPU, 0 );
  44264. }
  44265. if ( renderContext.scissor ) {
  44266. const { x, y, width, height } = renderContext.scissorValue;
  44267. const viewY = renderContext.height - height - y;
  44268. gl.blitFramebuffer( x, viewY, x + width, viewY + height, x, viewY, x + width, viewY + height, mask, gl.NEAREST );
  44269. } else {
  44270. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  44271. }
  44272. }
  44273. if ( isMRT ) {
  44274. // restore attachments
  44275. for ( let i = 0; i < textures.length; i ++ ) {
  44276. const { textureGPU } = this.get( textures[ i ] );
  44277. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  44278. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.TEXTURE_2D, textureGPU, 0 );
  44279. }
  44280. }
  44281. if ( this._supportsInvalidateFramebuffer === true ) {
  44282. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  44283. }
  44284. } else if ( renderTarget.resolveDepthBuffer === false && renderTargetContextData.framebuffers ) {
  44285. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  44286. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  44287. gl.invalidateFramebuffer( gl.DRAW_FRAMEBUFFER, renderTargetContextData.depthInvalidationArray );
  44288. }
  44289. }
  44290. if ( previousContext !== null ) {
  44291. this._setFramebuffer( previousContext );
  44292. if ( previousContext.viewport ) {
  44293. this.updateViewport( previousContext );
  44294. } else {
  44295. const { width, height } = this.getDrawingBufferSize();
  44296. state.viewport( 0, 0, width, height );
  44297. }
  44298. }
  44299. this.prepareTimestampBuffer( renderContext );
  44300. }
  44301. /**
  44302. * This method processes the result of occlusion queries and writes it
  44303. * into render context data.
  44304. *
  44305. * @async
  44306. * @param {RenderContext} renderContext - The render context.
  44307. */
  44308. resolveOccludedAsync( renderContext ) {
  44309. const renderContextData = this.get( renderContext );
  44310. // handle occlusion query results
  44311. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  44312. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  44313. const occluded = new WeakSet();
  44314. const { gl } = this;
  44315. renderContextData.currentOcclusionQueryObjects = null;
  44316. renderContextData.currentOcclusionQueries = null;
  44317. const check = () => {
  44318. let completed = 0;
  44319. // check all queries and requeue as appropriate
  44320. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  44321. const query = currentOcclusionQueries[ i ];
  44322. if ( query === null ) continue;
  44323. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  44324. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) === 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  44325. currentOcclusionQueries[ i ] = null;
  44326. gl.deleteQuery( query );
  44327. completed ++;
  44328. }
  44329. }
  44330. if ( completed < currentOcclusionQueries.length ) {
  44331. requestAnimationFrame( check );
  44332. } else {
  44333. renderContextData.occluded = occluded;
  44334. }
  44335. };
  44336. check();
  44337. }
  44338. }
  44339. /**
  44340. * Returns `true` if the given 3D object is fully occluded by other
  44341. * 3D objects in the scene.
  44342. *
  44343. * @param {RenderContext} renderContext - The render context.
  44344. * @param {Object3D} object - The 3D object to test.
  44345. * @return {boolean} Whether the 3D object is fully occluded or not.
  44346. */
  44347. isOccluded( renderContext, object ) {
  44348. const renderContextData = this.get( renderContext );
  44349. return renderContextData.occluded && renderContextData.occluded.has( object );
  44350. }
  44351. /**
  44352. * Updates the viewport with the values from the given render context.
  44353. *
  44354. * @param {RenderContext} renderContext - The render context.
  44355. */
  44356. updateViewport( renderContext ) {
  44357. const { state } = this;
  44358. const { x, y, width, height } = renderContext.viewportValue;
  44359. state.viewport( x, renderContext.height - height - y, width, height );
  44360. }
  44361. /**
  44362. * Defines the scissor test.
  44363. *
  44364. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  44365. */
  44366. setScissorTest( boolean ) {
  44367. const state = this.state;
  44368. state.setScissorTest( boolean );
  44369. }
  44370. /**
  44371. * Returns the clear color and alpha into a single
  44372. * color object.
  44373. *
  44374. * @return {Color4} The clear color.
  44375. */
  44376. getClearColor() {
  44377. const clearColor = super.getClearColor();
  44378. // Since the canvas is always created with alpha: true,
  44379. // WebGL must always premultiply the clear color.
  44380. clearColor.r *= clearColor.a;
  44381. clearColor.g *= clearColor.a;
  44382. clearColor.b *= clearColor.a;
  44383. return clearColor;
  44384. }
  44385. /**
  44386. * Performs a clear operation.
  44387. *
  44388. * @param {boolean} color - Whether the color buffer should be cleared or not.
  44389. * @param {boolean} depth - Whether the depth buffer should be cleared or not.
  44390. * @param {boolean} stencil - Whether the stencil buffer should be cleared or not.
  44391. * @param {?Object} [descriptor=null] - The render context of the current set render target.
  44392. * @param {boolean} [setFrameBuffer=true] - TODO.
  44393. */
  44394. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true ) {
  44395. const { gl, renderer } = this;
  44396. if ( descriptor === null ) {
  44397. const clearColor = this.getClearColor();
  44398. descriptor = {
  44399. textures: null,
  44400. clearColorValue: clearColor
  44401. };
  44402. }
  44403. //
  44404. let clear = 0;
  44405. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  44406. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  44407. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  44408. if ( clear !== 0 ) {
  44409. let clearColor;
  44410. if ( descriptor.clearColorValue ) {
  44411. clearColor = descriptor.clearColorValue;
  44412. } else {
  44413. clearColor = this.getClearColor();
  44414. }
  44415. const clearDepth = renderer.getClearDepth();
  44416. const clearStencil = renderer.getClearStencil();
  44417. if ( depth ) this.state.setDepthMask( true );
  44418. if ( descriptor.textures === null ) {
  44419. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  44420. gl.clear( clear );
  44421. } else {
  44422. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  44423. if ( color ) {
  44424. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  44425. if ( i === 0 ) {
  44426. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  44427. } else {
  44428. gl.clearBufferfv( gl.COLOR, i, [ 0, 0, 0, 1 ] );
  44429. }
  44430. }
  44431. }
  44432. if ( depth && stencil ) {
  44433. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, clearDepth, clearStencil );
  44434. } else if ( depth ) {
  44435. gl.clearBufferfv( gl.DEPTH, 0, [ clearDepth ] );
  44436. } else if ( stencil ) {
  44437. gl.clearBufferiv( gl.STENCIL, 0, [ clearStencil ] );
  44438. }
  44439. }
  44440. }
  44441. }
  44442. /**
  44443. * This method is executed at the beginning of a compute call and
  44444. * prepares the state for upcoming compute tasks.
  44445. *
  44446. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  44447. */
  44448. beginCompute( computeGroup ) {
  44449. const { state, gl } = this;
  44450. state.bindFramebuffer( gl.FRAMEBUFFER, null );
  44451. this.initTimestampQuery( computeGroup );
  44452. }
  44453. /**
  44454. * Executes a compute command for the given compute node.
  44455. *
  44456. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  44457. * @param {Node} computeNode - The compute node.
  44458. * @param {Array<BindGroup>} bindings - The bindings.
  44459. * @param {ComputePipeline} pipeline - The compute pipeline.
  44460. * @param {number|null} [count=null] - The count of compute invocations. If `null`, the count is determined by the compute node.
  44461. */
  44462. compute( computeGroup, computeNode, bindings, pipeline, count = null ) {
  44463. const { state, gl } = this;
  44464. if ( this.discard === false ) {
  44465. // required here to handle async behaviour of render.compute()
  44466. gl.enable( gl.RASTERIZER_DISCARD );
  44467. this.discard = true;
  44468. }
  44469. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  44470. const vaoKey = this._getVaoKey( attributes );
  44471. const vaoGPU = this.vaoCache[ vaoKey ];
  44472. if ( vaoGPU === undefined ) {
  44473. this.vaoCache[ vaoKey ] = this._createVao( attributes );
  44474. } else {
  44475. state.setVertexState( vaoGPU );
  44476. }
  44477. state.useProgram( programGPU );
  44478. this._bindUniforms( bindings );
  44479. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  44480. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  44481. gl.beginTransformFeedback( gl.POINTS );
  44482. count = ( count !== null ) ? count : computeNode.count;
  44483. if ( Array.isArray( count ) ) {
  44484. warnOnce( 'WebGLBackend.compute(): The count parameter must be a single number, not an array.' );
  44485. count = count[ 0 ];
  44486. }
  44487. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  44488. gl.drawArraysInstanced( gl.POINTS, 0, 1, count );
  44489. } else {
  44490. gl.drawArrays( gl.POINTS, 0, count );
  44491. }
  44492. gl.endTransformFeedback();
  44493. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  44494. // switch active buffers
  44495. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  44496. const dualAttributeData = transformBuffers[ i ];
  44497. if ( dualAttributeData.pbo && this.has( dualAttributeData.pbo ) ) {
  44498. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  44499. }
  44500. dualAttributeData.switchBuffers();
  44501. }
  44502. }
  44503. /**
  44504. * This method is executed at the end of a compute call and
  44505. * finalizes work after compute tasks.
  44506. *
  44507. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  44508. */
  44509. finishCompute( computeGroup ) {
  44510. const gl = this.gl;
  44511. this.discard = false;
  44512. gl.disable( gl.RASTERIZER_DISCARD );
  44513. this.prepareTimestampBuffer( computeGroup );
  44514. if ( this._currentContext ) {
  44515. this._setFramebuffer( this._currentContext );
  44516. }
  44517. }
  44518. /**
  44519. * Internal to determine if the current render target is a render target array with depth 2D array texture.
  44520. *
  44521. * @param {RenderContext} renderContext - The render context.
  44522. * @return {boolean} Whether the render target is a render target array with depth 2D array texture.
  44523. *
  44524. * @private
  44525. */
  44526. _isRenderCameraDepthArray( renderContext ) {
  44527. return renderContext.depthTexture && renderContext.depthTexture.isArrayTexture && renderContext.camera.isArrayCamera;
  44528. }
  44529. /**
  44530. * Executes a draw command for the given render object.
  44531. *
  44532. * @param {RenderObject} renderObject - The render object to draw.
  44533. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  44534. */
  44535. draw( renderObject/*, info*/ ) {
  44536. const { object, pipeline, material, context, hardwareClippingPlanes } = renderObject;
  44537. const { programGPU } = this.get( pipeline );
  44538. const { gl, state } = this;
  44539. const contextData = this.get( context );
  44540. const drawParams = renderObject.getDrawParameters();
  44541. if ( drawParams === null ) return;
  44542. //
  44543. this._bindUniforms( renderObject.getBindings() );
  44544. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  44545. state.setMaterial( material, frontFaceCW, hardwareClippingPlanes );
  44546. state.useProgram( programGPU );
  44547. // vertex state
  44548. const attributes = renderObject.getAttributes();
  44549. const attributesData = this.get( attributes );
  44550. let vaoGPU = attributesData.vaoGPU;
  44551. if ( vaoGPU === undefined ) {
  44552. const vaoKey = this._getVaoKey( attributes );
  44553. vaoGPU = this.vaoCache[ vaoKey ];
  44554. if ( vaoGPU === undefined ) {
  44555. vaoGPU = this._createVao( attributes );
  44556. this.vaoCache[ vaoKey ] = vaoGPU;
  44557. attributesData.vaoGPU = vaoGPU;
  44558. }
  44559. }
  44560. const index = renderObject.getIndex();
  44561. const indexGPU = ( index !== null ) ? this.get( index ).bufferGPU : null;
  44562. state.setVertexState( vaoGPU, indexGPU );
  44563. //
  44564. const lastObject = contextData.lastOcclusionObject;
  44565. if ( lastObject !== object && lastObject !== undefined ) {
  44566. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  44567. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  44568. contextData.occlusionQueryIndex ++;
  44569. }
  44570. if ( object.occlusionTest === true ) {
  44571. const query = gl.createQuery();
  44572. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  44573. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  44574. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  44575. }
  44576. contextData.lastOcclusionObject = object;
  44577. }
  44578. //
  44579. const renderer = this.bufferRenderer;
  44580. if ( object.isPoints ) renderer.mode = gl.POINTS;
  44581. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  44582. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  44583. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  44584. else {
  44585. if ( material.wireframe === true ) {
  44586. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  44587. renderer.mode = gl.LINES;
  44588. } else {
  44589. renderer.mode = gl.TRIANGLES;
  44590. }
  44591. }
  44592. //
  44593. const { vertexCount, instanceCount } = drawParams;
  44594. let { firstVertex } = drawParams;
  44595. renderer.object = object;
  44596. if ( index !== null ) {
  44597. firstVertex *= index.array.BYTES_PER_ELEMENT;
  44598. const indexData = this.get( index );
  44599. renderer.index = index.count;
  44600. renderer.type = indexData.type;
  44601. } else {
  44602. renderer.index = 0;
  44603. }
  44604. const draw = () => {
  44605. if ( object.isBatchedMesh ) {
  44606. if ( object._multiDrawInstances !== null ) {
  44607. // @deprecated, r174
  44608. warnOnce( 'THREE.WebGLBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  44609. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  44610. } else if ( ! this.hasFeature( 'WEBGL_multi_draw' ) ) {
  44611. warnOnce( 'THREE.WebGLRenderer: WEBGL_multi_draw not supported.' );
  44612. } else {
  44613. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  44614. }
  44615. } else if ( instanceCount > 1 ) {
  44616. renderer.renderInstances( firstVertex, vertexCount, instanceCount );
  44617. } else {
  44618. renderer.render( firstVertex, vertexCount );
  44619. }
  44620. };
  44621. if ( renderObject.camera.isArrayCamera === true && renderObject.camera.cameras.length > 0 && renderObject.camera.isMultiViewCamera === false ) {
  44622. const cameraData = this.get( renderObject.camera );
  44623. const cameras = renderObject.camera.cameras;
  44624. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' ).bindings[ 0 ];
  44625. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  44626. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  44627. const indexesGPU = [];
  44628. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  44629. const bufferGPU = gl.createBuffer();
  44630. data[ 0 ] = i;
  44631. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  44632. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.STATIC_DRAW );
  44633. indexesGPU.push( bufferGPU );
  44634. }
  44635. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  44636. }
  44637. const cameraIndexData = this.get( cameraIndex );
  44638. const pixelRatio = this.renderer.getPixelRatio();
  44639. const renderTarget = this._currentContext.renderTarget;
  44640. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( this._currentContext );
  44641. const prevActiveCubeFace = this._currentContext.activeCubeFace;
  44642. if ( isRenderCameraDepthArray ) {
  44643. // Clear the depth texture
  44644. const textureData = this.get( renderTarget.depthTexture );
  44645. if ( textureData.clearedRenderId !== this.renderer._nodes.nodeFrame.renderId ) {
  44646. textureData.clearedRenderId = this.renderer._nodes.nodeFrame.renderId;
  44647. const { stencilBuffer } = renderTarget;
  44648. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  44649. this.renderer._activeCubeFace = i;
  44650. this._currentContext.activeCubeFace = i;
  44651. this._setFramebuffer( this._currentContext );
  44652. this.clear( false, true, stencilBuffer, this._currentContext, false );
  44653. }
  44654. this.renderer._activeCubeFace = prevActiveCubeFace;
  44655. this._currentContext.activeCubeFace = prevActiveCubeFace;
  44656. }
  44657. }
  44658. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  44659. const subCamera = cameras[ i ];
  44660. if ( object.layers.test( subCamera.layers ) ) {
  44661. if ( isRenderCameraDepthArray ) {
  44662. // Update the active layer
  44663. this.renderer._activeCubeFace = i;
  44664. this._currentContext.activeCubeFace = i;
  44665. this._setFramebuffer( this._currentContext );
  44666. }
  44667. const vp = subCamera.viewport;
  44668. if ( vp !== undefined ) {
  44669. const x = vp.x * pixelRatio;
  44670. const y = vp.y * pixelRatio;
  44671. const width = vp.width * pixelRatio;
  44672. const height = vp.height * pixelRatio;
  44673. state.viewport(
  44674. Math.floor( x ),
  44675. Math.floor( renderObject.context.height - height - y ),
  44676. Math.floor( width ),
  44677. Math.floor( height )
  44678. );
  44679. }
  44680. state.bindBufferBase( gl.UNIFORM_BUFFER, cameraIndexData.index, cameraData.indexesGPU[ i ] );
  44681. draw();
  44682. }
  44683. this._currentContext.activeCubeFace = prevActiveCubeFace;
  44684. this.renderer._activeCubeFace = prevActiveCubeFace;
  44685. }
  44686. } else {
  44687. draw();
  44688. }
  44689. }
  44690. /**
  44691. * Explain why always null is returned.
  44692. *
  44693. * @param {RenderObject} renderObject - The render object.
  44694. * @return {boolean} Whether the render pipeline requires an update or not.
  44695. */
  44696. needsRenderUpdate( /*renderObject*/ ) {
  44697. return false;
  44698. }
  44699. /**
  44700. * Explain why no cache key is computed.
  44701. *
  44702. * @param {RenderObject} renderObject - The render object.
  44703. * @return {string} The cache key.
  44704. */
  44705. getRenderCacheKey( /*renderObject*/ ) {
  44706. return '';
  44707. }
  44708. // textures
  44709. /**
  44710. * Creates a default texture for the given texture that can be used
  44711. * as a placeholder until the actual texture is ready for usage.
  44712. *
  44713. * @param {Texture} texture - The texture to create a default texture for.
  44714. */
  44715. createDefaultTexture( texture ) {
  44716. this.textureUtils.createDefaultTexture( texture );
  44717. }
  44718. /**
  44719. * Defines a texture on the GPU for the given texture object.
  44720. *
  44721. * @param {Texture} texture - The texture.
  44722. * @param {Object} [options={}] - Optional configuration parameter.
  44723. */
  44724. createTexture( texture, options ) {
  44725. this.textureUtils.createTexture( texture, options );
  44726. }
  44727. /**
  44728. * Uploads the updated texture data to the GPU.
  44729. *
  44730. * @param {Texture} texture - The texture.
  44731. * @param {Object} [options={}] - Optional configuration parameter.
  44732. */
  44733. updateTexture( texture, options ) {
  44734. this.textureUtils.updateTexture( texture, options );
  44735. }
  44736. /**
  44737. * Generates mipmaps for the given texture.
  44738. *
  44739. * @param {Texture} texture - The texture.
  44740. */
  44741. generateMipmaps( texture ) {
  44742. this.textureUtils.generateMipmaps( texture );
  44743. }
  44744. /**
  44745. * Destroys the GPU data for the given texture object.
  44746. *
  44747. * @param {Texture} texture - The texture.
  44748. */
  44749. destroyTexture( texture ) {
  44750. this.textureUtils.destroyTexture( texture );
  44751. }
  44752. /**
  44753. * Returns texture data as a typed array.
  44754. *
  44755. * @async
  44756. * @param {Texture} texture - The texture to copy.
  44757. * @param {number} x - The x coordinate of the copy origin.
  44758. * @param {number} y - The y coordinate of the copy origin.
  44759. * @param {number} width - The width of the copy.
  44760. * @param {number} height - The height of the copy.
  44761. * @param {number} faceIndex - The face index.
  44762. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  44763. */
  44764. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  44765. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  44766. }
  44767. /**
  44768. * This method does nothing since WebGL 2 has no concept of samplers.
  44769. *
  44770. * @param {Texture} texture - The texture to create the sampler for.
  44771. */
  44772. createSampler( /*texture*/ ) {
  44773. //console.warn( 'Abstract class.' );
  44774. }
  44775. /**
  44776. * This method does nothing since WebGL 2 has no concept of samplers.
  44777. *
  44778. * @param {Texture} texture - The texture to destroy the sampler for.
  44779. */
  44780. destroySampler( /*texture*/ ) {}
  44781. // node builder
  44782. /**
  44783. * Returns a node builder for the given render object.
  44784. *
  44785. * @param {RenderObject} object - The render object.
  44786. * @param {Renderer} renderer - The renderer.
  44787. * @return {GLSLNodeBuilder} The node builder.
  44788. */
  44789. createNodeBuilder( object, renderer ) {
  44790. return new GLSLNodeBuilder( object, renderer );
  44791. }
  44792. // program
  44793. /**
  44794. * Creates a shader program from the given programmable stage.
  44795. *
  44796. * @param {ProgrammableStage} program - The programmable stage.
  44797. */
  44798. createProgram( program ) {
  44799. const gl = this.gl;
  44800. const { stage, code } = program;
  44801. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  44802. gl.shaderSource( shader, code );
  44803. gl.compileShader( shader );
  44804. this.set( program, {
  44805. shaderGPU: shader
  44806. } );
  44807. }
  44808. /**
  44809. * Destroys the shader program of the given programmable stage.
  44810. *
  44811. * @param {ProgrammableStage} program - The programmable stage.
  44812. */
  44813. destroyProgram( program ) {
  44814. this.delete( program );
  44815. }
  44816. /**
  44817. * Creates a render pipeline for the given render object.
  44818. *
  44819. * @param {RenderObject} renderObject - The render object.
  44820. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  44821. */
  44822. createRenderPipeline( renderObject, promises ) {
  44823. const gl = this.gl;
  44824. const pipeline = renderObject.pipeline;
  44825. // Program
  44826. const { fragmentProgram, vertexProgram } = pipeline;
  44827. const programGPU = gl.createProgram();
  44828. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  44829. const vertexShader = this.get( vertexProgram ).shaderGPU;
  44830. gl.attachShader( programGPU, fragmentShader );
  44831. gl.attachShader( programGPU, vertexShader );
  44832. gl.linkProgram( programGPU );
  44833. this.set( pipeline, {
  44834. programGPU,
  44835. fragmentShader,
  44836. vertexShader
  44837. } );
  44838. if ( promises !== null && this.parallel ) {
  44839. const p = new Promise( ( resolve /*, reject*/ ) => {
  44840. const parallel = this.parallel;
  44841. const checkStatus = () => {
  44842. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  44843. this._completeCompile( renderObject, pipeline );
  44844. resolve();
  44845. } else {
  44846. requestAnimationFrame( checkStatus );
  44847. }
  44848. };
  44849. checkStatus();
  44850. } );
  44851. promises.push( p );
  44852. return;
  44853. }
  44854. this._completeCompile( renderObject, pipeline );
  44855. }
  44856. /**
  44857. * Formats the source code of error messages.
  44858. *
  44859. * @private
  44860. * @param {string} string - The code.
  44861. * @param {number} errorLine - The error line.
  44862. * @return {string} The formatted code.
  44863. */
  44864. _handleSource( string, errorLine ) {
  44865. const lines = string.split( '\n' );
  44866. const lines2 = [];
  44867. const from = Math.max( errorLine - 6, 0 );
  44868. const to = Math.min( errorLine + 6, lines.length );
  44869. for ( let i = from; i < to; i ++ ) {
  44870. const line = i + 1;
  44871. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  44872. }
  44873. return lines2.join( '\n' );
  44874. }
  44875. /**
  44876. * Gets the shader compilation errors from the info log.
  44877. *
  44878. * @private
  44879. * @param {WebGL2RenderingContext} gl - The rendering context.
  44880. * @param {WebGLShader} shader - The WebGL shader object.
  44881. * @param {string} type - The shader type.
  44882. * @return {string} The shader errors.
  44883. */
  44884. _getShaderErrors( gl, shader, type ) {
  44885. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  44886. const shaderInfoLog = gl.getShaderInfoLog( shader ) || '';
  44887. const errors = shaderInfoLog.trim();
  44888. if ( status && errors === '' ) return '';
  44889. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  44890. if ( errorMatches ) {
  44891. const errorLine = parseInt( errorMatches[ 1 ] );
  44892. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  44893. } else {
  44894. return errors;
  44895. }
  44896. }
  44897. /**
  44898. * Logs shader compilation errors.
  44899. *
  44900. * @private
  44901. * @param {WebGLProgram} programGPU - The WebGL program.
  44902. * @param {WebGLShader} glFragmentShader - The fragment shader as a native WebGL shader object.
  44903. * @param {WebGLShader} glVertexShader - The vertex shader as a native WebGL shader object.
  44904. */
  44905. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  44906. if ( this.renderer.debug.checkShaderErrors ) {
  44907. const gl = this.gl;
  44908. const programInfoLog = gl.getProgramInfoLog( programGPU ) || '';
  44909. const programLog = programInfoLog.trim();
  44910. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  44911. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  44912. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  44913. } else {
  44914. // default error reporting
  44915. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  44916. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  44917. console.error(
  44918. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  44919. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  44920. 'Program Info Log: ' + programLog + '\n' +
  44921. vertexErrors + '\n' +
  44922. fragmentErrors
  44923. );
  44924. }
  44925. } else if ( programLog !== '' ) {
  44926. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  44927. }
  44928. }
  44929. }
  44930. /**
  44931. * Completes the shader program setup for the given render object.
  44932. *
  44933. * @private
  44934. * @param {RenderObject} renderObject - The render object.
  44935. * @param {RenderPipeline} pipeline - The render pipeline.
  44936. */
  44937. _completeCompile( renderObject, pipeline ) {
  44938. const { state, gl } = this;
  44939. const pipelineData = this.get( pipeline );
  44940. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  44941. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  44942. this._logProgramError( programGPU, fragmentShader, vertexShader );
  44943. }
  44944. state.useProgram( programGPU );
  44945. // Bindings
  44946. const bindings = renderObject.getBindings();
  44947. this._setupBindings( bindings, programGPU );
  44948. //
  44949. this.set( pipeline, {
  44950. programGPU
  44951. } );
  44952. }
  44953. /**
  44954. * Creates a compute pipeline for the given compute node.
  44955. *
  44956. * @param {ComputePipeline} computePipeline - The compute pipeline.
  44957. * @param {Array<BindGroup>} bindings - The bindings.
  44958. */
  44959. createComputePipeline( computePipeline, bindings ) {
  44960. const { state, gl } = this;
  44961. // Program
  44962. const fragmentProgram = {
  44963. stage: 'fragment',
  44964. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  44965. };
  44966. this.createProgram( fragmentProgram );
  44967. const { computeProgram } = computePipeline;
  44968. const programGPU = gl.createProgram();
  44969. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  44970. const vertexShader = this.get( computeProgram ).shaderGPU;
  44971. const transforms = computeProgram.transforms;
  44972. const transformVaryingNames = [];
  44973. const transformAttributeNodes = [];
  44974. for ( let i = 0; i < transforms.length; i ++ ) {
  44975. const transform = transforms[ i ];
  44976. transformVaryingNames.push( transform.varyingName );
  44977. transformAttributeNodes.push( transform.attributeNode );
  44978. }
  44979. gl.attachShader( programGPU, fragmentShader );
  44980. gl.attachShader( programGPU, vertexShader );
  44981. gl.transformFeedbackVaryings(
  44982. programGPU,
  44983. transformVaryingNames,
  44984. gl.SEPARATE_ATTRIBS
  44985. );
  44986. gl.linkProgram( programGPU );
  44987. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  44988. this._logProgramError( programGPU, fragmentShader, vertexShader );
  44989. }
  44990. state.useProgram( programGPU );
  44991. // Bindings
  44992. this._setupBindings( bindings, programGPU );
  44993. const attributeNodes = computeProgram.attributes;
  44994. const attributes = [];
  44995. const transformBuffers = [];
  44996. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  44997. const attribute = attributeNodes[ i ].node.attribute;
  44998. attributes.push( attribute );
  44999. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  45000. }
  45001. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  45002. const attribute = transformAttributeNodes[ i ].attribute;
  45003. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  45004. const attributeData = this.get( attribute );
  45005. transformBuffers.push( attributeData );
  45006. }
  45007. //
  45008. this.set( computePipeline, {
  45009. programGPU,
  45010. transformBuffers,
  45011. attributes
  45012. } );
  45013. }
  45014. /**
  45015. * Creates bindings from the given bind group definition.
  45016. *
  45017. * @param {BindGroup} bindGroup - The bind group.
  45018. * @param {Array<BindGroup>} bindings - Array of bind groups.
  45019. * @param {number} cacheIndex - The cache index.
  45020. * @param {number} version - The version.
  45021. */
  45022. createBindings( bindGroup, bindings /*, cacheIndex, version*/ ) {
  45023. if ( this._knownBindings.has( bindings ) === false ) {
  45024. this._knownBindings.add( bindings );
  45025. let uniformBuffers = 0;
  45026. let textures = 0;
  45027. for ( const bindGroup of bindings ) {
  45028. this.set( bindGroup, {
  45029. textures: textures,
  45030. uniformBuffers: uniformBuffers
  45031. } );
  45032. for ( const binding of bindGroup.bindings ) {
  45033. if ( binding.isUniformBuffer ) uniformBuffers ++;
  45034. if ( binding.isSampledTexture ) textures ++;
  45035. }
  45036. }
  45037. }
  45038. this.updateBindings( bindGroup, bindings );
  45039. }
  45040. /**
  45041. * Updates the given bind group definition.
  45042. *
  45043. * @param {BindGroup} bindGroup - The bind group.
  45044. * @param {Array<BindGroup>} bindings - Array of bind groups.
  45045. * @param {number} cacheIndex - The cache index.
  45046. * @param {number} version - The version.
  45047. */
  45048. updateBindings( bindGroup /*, bindings, cacheIndex, version*/ ) {
  45049. const { gl } = this;
  45050. const bindGroupData = this.get( bindGroup );
  45051. let i = bindGroupData.uniformBuffers;
  45052. let t = bindGroupData.textures;
  45053. for ( const binding of bindGroup.bindings ) {
  45054. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  45055. const data = binding.buffer;
  45056. const bufferGPU = gl.createBuffer();
  45057. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  45058. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  45059. this.set( binding, {
  45060. index: i ++,
  45061. bufferGPU
  45062. } );
  45063. } else if ( binding.isSampledTexture ) {
  45064. const { textureGPU, glTextureType } = this.get( binding.texture );
  45065. this.set( binding, {
  45066. index: t ++,
  45067. textureGPU,
  45068. glTextureType
  45069. } );
  45070. }
  45071. }
  45072. }
  45073. /**
  45074. * Updates a buffer binding.
  45075. *
  45076. * @param {Buffer} binding - The buffer binding to update.
  45077. */
  45078. updateBinding( binding ) {
  45079. const gl = this.gl;
  45080. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  45081. const bindingData = this.get( binding );
  45082. const bufferGPU = bindingData.bufferGPU;
  45083. const data = binding.buffer;
  45084. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  45085. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  45086. }
  45087. }
  45088. // attributes
  45089. /**
  45090. * Creates the GPU buffer of an indexed shader attribute.
  45091. *
  45092. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  45093. */
  45094. createIndexAttribute( attribute ) {
  45095. const gl = this.gl;
  45096. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  45097. }
  45098. /**
  45099. * Creates the GPU buffer of a shader attribute.
  45100. *
  45101. * @param {BufferAttribute} attribute - The buffer attribute.
  45102. */
  45103. createAttribute( attribute ) {
  45104. if ( this.has( attribute ) ) return;
  45105. const gl = this.gl;
  45106. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  45107. }
  45108. /**
  45109. * Creates the GPU buffer of a storage attribute.
  45110. *
  45111. * @param {BufferAttribute} attribute - The buffer attribute.
  45112. */
  45113. createStorageAttribute( attribute ) {
  45114. if ( this.has( attribute ) ) return;
  45115. const gl = this.gl;
  45116. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  45117. }
  45118. /**
  45119. * Updates the GPU buffer of a shader attribute.
  45120. *
  45121. * @param {BufferAttribute} attribute - The buffer attribute to update.
  45122. */
  45123. updateAttribute( attribute ) {
  45124. this.attributeUtils.updateAttribute( attribute );
  45125. }
  45126. /**
  45127. * Destroys the GPU buffer of a shader attribute.
  45128. *
  45129. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  45130. */
  45131. destroyAttribute( attribute ) {
  45132. this.attributeUtils.destroyAttribute( attribute );
  45133. }
  45134. /**
  45135. * Checks if the given feature is supported by the backend.
  45136. *
  45137. * @param {string} name - The feature's name.
  45138. * @return {boolean} Whether the feature is supported or not.
  45139. */
  45140. hasFeature( name ) {
  45141. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  45142. const extensions = this.extensions;
  45143. for ( let i = 0; i < keysMatching.length; i ++ ) {
  45144. if ( extensions.has( keysMatching[ i ] ) ) return true;
  45145. }
  45146. return false;
  45147. }
  45148. /**
  45149. * Returns the maximum anisotropy texture filtering value.
  45150. *
  45151. * @return {number} The maximum anisotropy texture filtering value.
  45152. */
  45153. getMaxAnisotropy() {
  45154. return this.capabilities.getMaxAnisotropy();
  45155. }
  45156. /**
  45157. * Copies data of the given source texture to the given destination texture.
  45158. *
  45159. * @param {Texture} srcTexture - The source texture.
  45160. * @param {Texture} dstTexture - The destination texture.
  45161. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  45162. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  45163. * @param {number} [srcLevel=0] - The source mip level to copy from.
  45164. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  45165. */
  45166. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  45167. this.textureUtils.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, srcLevel, dstLevel );
  45168. }
  45169. /**
  45170. * Copies the current bound framebuffer to the given texture.
  45171. *
  45172. * @param {Texture} texture - The destination texture.
  45173. * @param {RenderContext} renderContext - The render context.
  45174. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  45175. */
  45176. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  45177. this.textureUtils.copyFramebufferToTexture( texture, renderContext, rectangle );
  45178. }
  45179. /**
  45180. * Configures the active framebuffer from the given render context.
  45181. *
  45182. * @private
  45183. * @param {RenderContext} descriptor - The render context.
  45184. */
  45185. _setFramebuffer( descriptor ) {
  45186. const { gl, state } = this;
  45187. let currentFrameBuffer = null;
  45188. if ( descriptor.textures !== null ) {
  45189. const renderTarget = descriptor.renderTarget;
  45190. const renderTargetContextData = this.get( renderTarget );
  45191. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  45192. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  45193. const isRenderTarget3D = renderTarget.isRenderTarget3D === true;
  45194. const isRenderTargetArray = renderTarget.depth > 1;
  45195. const isXRRenderTarget = renderTarget.isXRRenderTarget === true;
  45196. const _hasExternalTextures = ( isXRRenderTarget === true && renderTarget._hasExternalTextures === true );
  45197. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  45198. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  45199. const multisampledRTTExt = this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  45200. const multiviewExt = this.extensions.get( 'OVR_multiview2' );
  45201. const useMultisampledRTT = this._useMultisampledExtension( renderTarget );
  45202. const cacheKey = getCacheKey( descriptor );
  45203. let fb;
  45204. if ( isCube ) {
  45205. renderTargetContextData.cubeFramebuffers || ( renderTargetContextData.cubeFramebuffers = {} );
  45206. fb = renderTargetContextData.cubeFramebuffers[ cacheKey ];
  45207. } else if ( isXRRenderTarget && _hasExternalTextures === false ) {
  45208. fb = this._xrFramebuffer;
  45209. } else {
  45210. renderTargetContextData.framebuffers || ( renderTargetContextData.framebuffers = {} );
  45211. fb = renderTargetContextData.framebuffers[ cacheKey ];
  45212. }
  45213. if ( fb === undefined ) {
  45214. fb = gl.createFramebuffer();
  45215. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  45216. const textures = descriptor.textures;
  45217. const depthInvalidationArray = [];
  45218. if ( isCube ) {
  45219. renderTargetContextData.cubeFramebuffers[ cacheKey ] = fb;
  45220. const { textureGPU } = this.get( textures[ 0 ] );
  45221. const cubeFace = this.renderer._activeCubeFace;
  45222. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, 0 );
  45223. } else {
  45224. renderTargetContextData.framebuffers[ cacheKey ] = fb;
  45225. for ( let i = 0; i < textures.length; i ++ ) {
  45226. const texture = textures[ i ];
  45227. const textureData = this.get( texture );
  45228. textureData.renderTarget = descriptor.renderTarget;
  45229. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  45230. const attachment = gl.COLOR_ATTACHMENT0 + i;
  45231. if ( renderTarget.multiview ) {
  45232. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, attachment, textureData.textureGPU, 0, samples, 0, 2 );
  45233. } else if ( isRenderTarget3D || isRenderTargetArray ) {
  45234. const layer = this.renderer._activeCubeFace;
  45235. gl.framebufferTextureLayer( gl.FRAMEBUFFER, attachment, textureData.textureGPU, 0, layer );
  45236. } else {
  45237. if ( useMultisampledRTT ) {
  45238. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  45239. } else {
  45240. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  45241. }
  45242. }
  45243. }
  45244. }
  45245. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  45246. if ( renderTarget._autoAllocateDepthBuffer === true ) {
  45247. const renderbuffer = gl.createRenderbuffer();
  45248. this.textureUtils.setupRenderBufferStorage( renderbuffer, descriptor, 0, useMultisampledRTT );
  45249. renderTargetContextData.xrDepthRenderbuffer = renderbuffer;
  45250. depthInvalidationArray.push( stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT );
  45251. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  45252. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, depthStyle, gl.RENDERBUFFER, renderbuffer );
  45253. } else {
  45254. if ( descriptor.depthTexture !== null ) {
  45255. depthInvalidationArray.push( stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT );
  45256. const textureData = this.get( descriptor.depthTexture );
  45257. textureData.renderTarget = descriptor.renderTarget;
  45258. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  45259. if ( renderTarget.multiview ) {
  45260. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, samples, 0, 2 );
  45261. } else if ( _hasExternalTextures && useMultisampledRTT ) {
  45262. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  45263. } else {
  45264. if ( descriptor.depthTexture.isArrayTexture ) {
  45265. const layer = this.renderer._activeCubeFace;
  45266. gl.framebufferTextureLayer( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, layer );
  45267. } else {
  45268. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  45269. }
  45270. }
  45271. }
  45272. }
  45273. renderTargetContextData.depthInvalidationArray = depthInvalidationArray;
  45274. } else {
  45275. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( descriptor );
  45276. if ( isRenderCameraDepthArray ) {
  45277. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  45278. const layer = this.renderer._activeCubeFace;
  45279. const depthData = this.get( descriptor.depthTexture );
  45280. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  45281. gl.framebufferTextureLayer(
  45282. gl.FRAMEBUFFER,
  45283. depthStyle,
  45284. depthData.textureGPU,
  45285. 0,
  45286. layer
  45287. );
  45288. }
  45289. // rebind external XR textures
  45290. if ( ( isXRRenderTarget || useMultisampledRTT || renderTarget.multiview ) && ( renderTarget._isOpaqueFramebuffer !== true ) ) {
  45291. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  45292. // rebind color
  45293. const textureData = this.get( descriptor.textures[ 0 ] );
  45294. if ( renderTarget.multiview ) {
  45295. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, textureData.textureGPU, 0, samples, 0, 2 );
  45296. } else if ( useMultisampledRTT ) {
  45297. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  45298. } else {
  45299. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  45300. }
  45301. // rebind depth
  45302. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  45303. if ( renderTarget._autoAllocateDepthBuffer === true ) {
  45304. const renderbuffer = renderTargetContextData.xrDepthRenderbuffer;
  45305. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  45306. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, depthStyle, gl.RENDERBUFFER, renderbuffer );
  45307. } else {
  45308. const textureData = this.get( descriptor.depthTexture );
  45309. if ( renderTarget.multiview ) {
  45310. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, samples, 0, 2 );
  45311. } else if ( useMultisampledRTT ) {
  45312. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  45313. } else {
  45314. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  45315. }
  45316. }
  45317. }
  45318. }
  45319. if ( samples > 0 && useMultisampledRTT === false && ! renderTarget.multiview ) {
  45320. if ( msaaFb === undefined ) {
  45321. const invalidationArray = [];
  45322. msaaFb = gl.createFramebuffer();
  45323. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  45324. const msaaRenderbuffers = [];
  45325. const textures = descriptor.textures;
  45326. for ( let i = 0; i < textures.length; i ++ ) {
  45327. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  45328. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  45329. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  45330. const texture = descriptor.textures[ i ];
  45331. const textureData = this.get( texture );
  45332. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, descriptor.width, descriptor.height );
  45333. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  45334. }
  45335. gl.bindRenderbuffer( gl.RENDERBUFFER, null );
  45336. renderTargetContextData.msaaFrameBuffer = msaaFb;
  45337. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  45338. if ( depthBuffer && depthRenderbuffer === undefined ) {
  45339. depthRenderbuffer = gl.createRenderbuffer();
  45340. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, descriptor, samples );
  45341. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  45342. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  45343. invalidationArray.push( depthStyle );
  45344. }
  45345. renderTargetContextData.invalidationArray = invalidationArray;
  45346. }
  45347. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  45348. } else {
  45349. currentFrameBuffer = fb;
  45350. }
  45351. state.drawBuffers( descriptor, fb );
  45352. }
  45353. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  45354. }
  45355. /**
  45356. * Computes the VAO key for the given index and attributes.
  45357. *
  45358. * @private
  45359. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  45360. * @return {string} The VAO key.
  45361. */
  45362. _getVaoKey( attributes ) {
  45363. let key = '';
  45364. for ( let i = 0; i < attributes.length; i ++ ) {
  45365. const attributeData = this.get( attributes[ i ] );
  45366. key += ':' + attributeData.id;
  45367. }
  45368. return key;
  45369. }
  45370. /**
  45371. * Creates a VAO from the index and attributes.
  45372. *
  45373. * @private
  45374. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  45375. * @return {Object} The VAO data.
  45376. */
  45377. _createVao( attributes ) {
  45378. const { gl } = this;
  45379. const vaoGPU = gl.createVertexArray();
  45380. gl.bindVertexArray( vaoGPU );
  45381. for ( let i = 0; i < attributes.length; i ++ ) {
  45382. const attribute = attributes[ i ];
  45383. const attributeData = this.get( attribute );
  45384. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  45385. gl.enableVertexAttribArray( i );
  45386. let stride, offset;
  45387. if ( attribute.isInterleavedBufferAttribute === true ) {
  45388. stride = attribute.data.stride * attributeData.bytesPerElement;
  45389. offset = attribute.offset * attributeData.bytesPerElement;
  45390. } else {
  45391. stride = 0;
  45392. offset = 0;
  45393. }
  45394. if ( attributeData.isInteger ) {
  45395. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  45396. } else {
  45397. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  45398. }
  45399. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  45400. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  45401. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  45402. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  45403. }
  45404. }
  45405. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  45406. return vaoGPU;
  45407. }
  45408. /**
  45409. * Creates a transform feedback from the given transform buffers.
  45410. *
  45411. * @private
  45412. * @param {Array<DualAttributeData>} transformBuffers - The transform buffers.
  45413. * @return {WebGLTransformFeedback} The transform feedback.
  45414. */
  45415. _getTransformFeedback( transformBuffers ) {
  45416. let key = '';
  45417. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  45418. key += ':' + transformBuffers[ i ].id;
  45419. }
  45420. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  45421. if ( transformFeedbackGPU !== undefined ) {
  45422. return transformFeedbackGPU;
  45423. }
  45424. const { gl } = this;
  45425. transformFeedbackGPU = gl.createTransformFeedback();
  45426. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  45427. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  45428. const attributeData = transformBuffers[ i ];
  45429. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  45430. }
  45431. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  45432. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  45433. return transformFeedbackGPU;
  45434. }
  45435. /**
  45436. * Setups the given bindings.
  45437. *
  45438. * @private
  45439. * @param {Array<BindGroup>} bindings - The bindings.
  45440. * @param {WebGLProgram} programGPU - The WebGL program.
  45441. */
  45442. _setupBindings( bindings, programGPU ) {
  45443. const gl = this.gl;
  45444. for ( const bindGroup of bindings ) {
  45445. for ( const binding of bindGroup.bindings ) {
  45446. const bindingData = this.get( binding );
  45447. const index = bindingData.index;
  45448. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  45449. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  45450. gl.uniformBlockBinding( programGPU, location, index );
  45451. } else if ( binding.isSampledTexture ) {
  45452. const location = gl.getUniformLocation( programGPU, binding.name );
  45453. gl.uniform1i( location, index );
  45454. }
  45455. }
  45456. }
  45457. }
  45458. /**
  45459. * Binds the given uniforms.
  45460. *
  45461. * @private
  45462. * @param {Array<BindGroup>} bindings - The bindings.
  45463. */
  45464. _bindUniforms( bindings ) {
  45465. const { gl, state } = this;
  45466. for ( const bindGroup of bindings ) {
  45467. for ( const binding of bindGroup.bindings ) {
  45468. const bindingData = this.get( binding );
  45469. const index = bindingData.index;
  45470. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  45471. // TODO USE bindBufferRange to group multiple uniform buffers
  45472. state.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  45473. } else if ( binding.isSampledTexture ) {
  45474. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  45475. }
  45476. }
  45477. }
  45478. }
  45479. /**
  45480. * Returns `true` if the `WEBGL_multisampled_render_to_texture` extension
  45481. * should be used when MSAA is enabled.
  45482. *
  45483. * @private
  45484. * @param {RenderTarget} renderTarget - The render target that should be multisampled.
  45485. * @return {boolean} Whether to use the `WEBGL_multisampled_render_to_texture` extension for MSAA or not.
  45486. */
  45487. _useMultisampledExtension( renderTarget ) {
  45488. if ( renderTarget.multiview === true ) {
  45489. return true;
  45490. }
  45491. return renderTarget.samples > 0 && this.extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTarget._autoAllocateDepthBuffer !== false;
  45492. }
  45493. /**
  45494. * Frees internal resources.
  45495. */
  45496. dispose() {
  45497. const extension = this.extensions.get( 'WEBGL_lose_context' );
  45498. if ( extension ) extension.loseContext();
  45499. this.renderer.domElement.removeEventListener( 'webglcontextlost', this._onContextLost );
  45500. }
  45501. }
  45502. const GPUPrimitiveTopology = {
  45503. PointList: 'point-list',
  45504. LineList: 'line-list',
  45505. LineStrip: 'line-strip',
  45506. TriangleList: 'triangle-list',
  45507. TriangleStrip: 'triangle-strip',
  45508. };
  45509. const GPUCompareFunction = {
  45510. Never: 'never',
  45511. Less: 'less',
  45512. Equal: 'equal',
  45513. LessEqual: 'less-equal',
  45514. Greater: 'greater',
  45515. NotEqual: 'not-equal',
  45516. GreaterEqual: 'greater-equal',
  45517. Always: 'always'
  45518. };
  45519. const GPUStoreOp = {
  45520. Store: 'store'};
  45521. const GPULoadOp = {
  45522. Load: 'load',
  45523. Clear: 'clear'
  45524. };
  45525. const GPUFrontFace = {
  45526. CCW: 'ccw'};
  45527. const GPUCullMode = {
  45528. None: 'none',
  45529. Front: 'front',
  45530. Back: 'back'
  45531. };
  45532. const GPUIndexFormat = {
  45533. Uint16: 'uint16',
  45534. Uint32: 'uint32'
  45535. };
  45536. const GPUTextureFormat = {
  45537. // 8-bit formats
  45538. R8Unorm: 'r8unorm',
  45539. R8Snorm: 'r8snorm',
  45540. R8Uint: 'r8uint',
  45541. R8Sint: 'r8sint',
  45542. // 16-bit formats
  45543. R16Uint: 'r16uint',
  45544. R16Sint: 'r16sint',
  45545. R16Float: 'r16float',
  45546. RG8Unorm: 'rg8unorm',
  45547. RG8Snorm: 'rg8snorm',
  45548. RG8Uint: 'rg8uint',
  45549. RG8Sint: 'rg8sint',
  45550. // 32-bit formats
  45551. R32Uint: 'r32uint',
  45552. R32Sint: 'r32sint',
  45553. R32Float: 'r32float',
  45554. RG16Uint: 'rg16uint',
  45555. RG16Sint: 'rg16sint',
  45556. RG16Float: 'rg16float',
  45557. RGBA8Unorm: 'rgba8unorm',
  45558. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  45559. RGBA8Snorm: 'rgba8snorm',
  45560. RGBA8Uint: 'rgba8uint',
  45561. RGBA8Sint: 'rgba8sint',
  45562. BGRA8Unorm: 'bgra8unorm',
  45563. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  45564. // Packed 32-bit formats
  45565. RGB9E5UFloat: 'rgb9e5ufloat',
  45566. RGB10A2Unorm: 'rgb10a2unorm',
  45567. RG11B10UFloat: 'rgb10a2unorm',
  45568. // 64-bit formats
  45569. RG32Uint: 'rg32uint',
  45570. RG32Sint: 'rg32sint',
  45571. RG32Float: 'rg32float',
  45572. RGBA16Uint: 'rgba16uint',
  45573. RGBA16Sint: 'rgba16sint',
  45574. RGBA16Float: 'rgba16float',
  45575. // 128-bit formats
  45576. RGBA32Uint: 'rgba32uint',
  45577. RGBA32Sint: 'rgba32sint',
  45578. RGBA32Float: 'rgba32float',
  45579. Depth16Unorm: 'depth16unorm',
  45580. Depth24Plus: 'depth24plus',
  45581. Depth24PlusStencil8: 'depth24plus-stencil8',
  45582. Depth32Float: 'depth32float',
  45583. // 'depth32float-stencil8' extension
  45584. Depth32FloatStencil8: 'depth32float-stencil8',
  45585. // BC compressed formats usable if 'texture-compression-bc' is both
  45586. // supported by the device/user agent and enabled in requestDevice.
  45587. BC1RGBAUnorm: 'bc1-rgba-unorm',
  45588. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  45589. BC2RGBAUnorm: 'bc2-rgba-unorm',
  45590. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  45591. BC3RGBAUnorm: 'bc3-rgba-unorm',
  45592. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  45593. BC4RUnorm: 'bc4-r-unorm',
  45594. BC4RSnorm: 'bc4-r-snorm',
  45595. BC5RGUnorm: 'bc5-rg-unorm',
  45596. BC5RGSnorm: 'bc5-rg-snorm',
  45597. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  45598. BC6HRGBFloat: 'bc6h-rgb-float',
  45599. BC7RGBAUnorm: 'bc7-rgba-unorm',
  45600. BC7RGBAUnormSRGB: 'bc7-rgba-srgb',
  45601. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  45602. // supported by the device/user agent and enabled in requestDevice.
  45603. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  45604. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  45605. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  45606. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  45607. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  45608. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  45609. EACR11Unorm: 'eac-r11unorm',
  45610. EACR11Snorm: 'eac-r11snorm',
  45611. EACRG11Unorm: 'eac-rg11unorm',
  45612. EACRG11Snorm: 'eac-rg11snorm',
  45613. // ASTC compressed formats usable if 'texture-compression-astc' is both
  45614. // supported by the device/user agent and enabled in requestDevice.
  45615. ASTC4x4Unorm: 'astc-4x4-unorm',
  45616. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  45617. ASTC5x4Unorm: 'astc-5x4-unorm',
  45618. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  45619. ASTC5x5Unorm: 'astc-5x5-unorm',
  45620. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  45621. ASTC6x5Unorm: 'astc-6x5-unorm',
  45622. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  45623. ASTC6x6Unorm: 'astc-6x6-unorm',
  45624. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  45625. ASTC8x5Unorm: 'astc-8x5-unorm',
  45626. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  45627. ASTC8x6Unorm: 'astc-8x6-unorm',
  45628. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  45629. ASTC8x8Unorm: 'astc-8x8-unorm',
  45630. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  45631. ASTC10x5Unorm: 'astc-10x5-unorm',
  45632. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  45633. ASTC10x6Unorm: 'astc-10x6-unorm',
  45634. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  45635. ASTC10x8Unorm: 'astc-10x8-unorm',
  45636. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  45637. ASTC10x10Unorm: 'astc-10x10-unorm',
  45638. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  45639. ASTC12x10Unorm: 'astc-12x10-unorm',
  45640. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  45641. ASTC12x12Unorm: 'astc-12x12-unorm',
  45642. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  45643. };
  45644. const GPUAddressMode = {
  45645. ClampToEdge: 'clamp-to-edge',
  45646. Repeat: 'repeat',
  45647. MirrorRepeat: 'mirror-repeat'
  45648. };
  45649. const GPUFilterMode = {
  45650. Linear: 'linear',
  45651. Nearest: 'nearest'
  45652. };
  45653. const GPUBlendFactor = {
  45654. Zero: 'zero',
  45655. One: 'one',
  45656. Src: 'src',
  45657. OneMinusSrc: 'one-minus-src',
  45658. SrcAlpha: 'src-alpha',
  45659. OneMinusSrcAlpha: 'one-minus-src-alpha',
  45660. Dst: 'dst',
  45661. OneMinusDst: 'one-minus-dst',
  45662. DstAlpha: 'dst-alpha',
  45663. OneMinusDstAlpha: 'one-minus-dst-alpha',
  45664. SrcAlphaSaturated: 'src-alpha-saturated',
  45665. Constant: 'constant',
  45666. OneMinusConstant: 'one-minus-constant'
  45667. };
  45668. const GPUBlendOperation = {
  45669. Add: 'add',
  45670. Subtract: 'subtract',
  45671. ReverseSubtract: 'reverse-subtract',
  45672. Min: 'min',
  45673. Max: 'max'
  45674. };
  45675. const GPUColorWriteFlags = {
  45676. None: 0,
  45677. All: 0xF
  45678. };
  45679. const GPUStencilOperation = {
  45680. Keep: 'keep',
  45681. Zero: 'zero',
  45682. Replace: 'replace',
  45683. Invert: 'invert',
  45684. IncrementClamp: 'increment-clamp',
  45685. DecrementClamp: 'decrement-clamp',
  45686. IncrementWrap: 'increment-wrap',
  45687. DecrementWrap: 'decrement-wrap'
  45688. };
  45689. const GPUBufferBindingType = {
  45690. Storage: 'storage',
  45691. ReadOnlyStorage: 'read-only-storage'
  45692. };
  45693. const GPUStorageTextureAccess = {
  45694. WriteOnly: 'write-only',
  45695. ReadOnly: 'read-only',
  45696. ReadWrite: 'read-write',
  45697. };
  45698. const GPUSamplerBindingType = {
  45699. NonFiltering: 'non-filtering',
  45700. Comparison: 'comparison'
  45701. };
  45702. const GPUTextureSampleType = {
  45703. Float: 'float',
  45704. UnfilterableFloat: 'unfilterable-float',
  45705. Depth: 'depth',
  45706. SInt: 'sint',
  45707. UInt: 'uint'
  45708. };
  45709. const GPUTextureDimension = {
  45710. TwoD: '2d',
  45711. ThreeD: '3d'
  45712. };
  45713. const GPUTextureViewDimension = {
  45714. TwoD: '2d',
  45715. TwoDArray: '2d-array',
  45716. Cube: 'cube',
  45717. ThreeD: '3d'
  45718. };
  45719. const GPUTextureAspect = {
  45720. All: 'all'};
  45721. const GPUInputStepMode = {
  45722. Vertex: 'vertex',
  45723. Instance: 'instance'
  45724. };
  45725. const GPUFeatureName = {
  45726. CoreFeaturesAndLimits: 'core-features-and-limits',
  45727. DepthClipControl: 'depth-clip-control',
  45728. Depth32FloatStencil8: 'depth32float-stencil8',
  45729. TextureCompressionBC: 'texture-compression-bc',
  45730. TextureCompressionBCSliced3D: 'texture-compression-bc-sliced-3d',
  45731. TextureCompressionETC2: 'texture-compression-etc2',
  45732. TextureCompressionASTC: 'texture-compression-astc',
  45733. TextureCompressionASTCSliced3D: 'texture-compression-astc-sliced-3d',
  45734. TimestampQuery: 'timestamp-query',
  45735. IndirectFirstInstance: 'indirect-first-instance',
  45736. ShaderF16: 'shader-f16',
  45737. RG11B10UFloat: 'rg11b10ufloat-renderable',
  45738. BGRA8UNormStorage: 'bgra8unorm-storage',
  45739. Float32Filterable: 'float32-filterable',
  45740. Float32Blendable: 'float32-blendable',
  45741. ClipDistances: 'clip-distances',
  45742. DualSourceBlending: 'dual-source-blending',
  45743. Subgroups: 'subgroups',
  45744. TextureFormatsTier1: 'texture-formats-tier1',
  45745. TextureFormatsTier2: 'texture-formats-tier2'
  45746. };
  45747. /**
  45748. * Represents a sampler binding type.
  45749. *
  45750. * @private
  45751. * @augments Binding
  45752. */
  45753. class Sampler extends Binding {
  45754. /**
  45755. * Constructs a new sampler.
  45756. *
  45757. * @param {string} name - The samplers's name.
  45758. * @param {?Texture} texture - The texture this binding is referring to.
  45759. */
  45760. constructor( name, texture ) {
  45761. super( name );
  45762. /**
  45763. * The texture the sampler is referring to.
  45764. *
  45765. * @type {?Texture}
  45766. */
  45767. this.texture = texture;
  45768. /**
  45769. * The binding's version.
  45770. *
  45771. * @type {number}
  45772. */
  45773. this.version = texture ? texture.version : 0;
  45774. /**
  45775. * This flag can be used for type testing.
  45776. *
  45777. * @type {boolean}
  45778. * @readonly
  45779. * @default true
  45780. */
  45781. this.isSampler = true;
  45782. }
  45783. }
  45784. /**
  45785. * A special form of sampler binding type.
  45786. * It's texture value is managed by a node object.
  45787. *
  45788. * @private
  45789. * @augments Sampler
  45790. */
  45791. class NodeSampler extends Sampler {
  45792. /**
  45793. * Constructs a new node-based sampler.
  45794. *
  45795. * @param {string} name - The samplers's name.
  45796. * @param {TextureNode} textureNode - The texture node.
  45797. * @param {UniformGroupNode} groupNode - The uniform group node.
  45798. */
  45799. constructor( name, textureNode, groupNode ) {
  45800. super( name, textureNode ? textureNode.value : null );
  45801. /**
  45802. * The texture node.
  45803. *
  45804. * @type {TextureNode}
  45805. */
  45806. this.textureNode = textureNode;
  45807. /**
  45808. * The uniform group node.
  45809. *
  45810. * @type {UniformGroupNode}
  45811. */
  45812. this.groupNode = groupNode;
  45813. }
  45814. /**
  45815. * Updates the texture value of this sampler.
  45816. */
  45817. update() {
  45818. this.texture = this.textureNode.value;
  45819. }
  45820. }
  45821. /**
  45822. * Represents a storage buffer binding type.
  45823. *
  45824. * @private
  45825. * @augments Buffer
  45826. */
  45827. class StorageBuffer extends Buffer {
  45828. /**
  45829. * Constructs a new uniform buffer.
  45830. *
  45831. * @param {string} name - The buffer's name.
  45832. * @param {BufferAttribute} attribute - The buffer attribute.
  45833. */
  45834. constructor( name, attribute ) {
  45835. super( name, attribute ? attribute.array : null );
  45836. /**
  45837. * This flag can be used for type testing.
  45838. *
  45839. * @type {BufferAttribute}
  45840. */
  45841. this.attribute = attribute;
  45842. /**
  45843. * This flag can be used for type testing.
  45844. *
  45845. * @type {boolean}
  45846. * @readonly
  45847. * @default true
  45848. */
  45849. this.isStorageBuffer = true;
  45850. }
  45851. }
  45852. let _id = 0;
  45853. /**
  45854. * A special form of storage buffer binding type.
  45855. * It's buffer value is managed by a node object.
  45856. *
  45857. * @private
  45858. * @augments StorageBuffer
  45859. */
  45860. class NodeStorageBuffer extends StorageBuffer {
  45861. /**
  45862. * Constructs a new node-based storage buffer.
  45863. *
  45864. * @param {StorageBufferNode} nodeUniform - The storage buffer node.
  45865. * @param {UniformGroupNode} groupNode - The uniform group node.
  45866. */
  45867. constructor( nodeUniform, groupNode ) {
  45868. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  45869. /**
  45870. * The node uniform.
  45871. *
  45872. * @type {StorageBufferNode}
  45873. */
  45874. this.nodeUniform = nodeUniform;
  45875. /**
  45876. * The access type.
  45877. *
  45878. * @type {string}
  45879. */
  45880. this.access = nodeUniform ? nodeUniform.access : NodeAccess.READ_WRITE;
  45881. /**
  45882. * The uniform group node.
  45883. *
  45884. * @type {UniformGroupNode}
  45885. */
  45886. this.groupNode = groupNode;
  45887. }
  45888. /**
  45889. * The storage buffer.
  45890. *
  45891. * @type {BufferAttribute}
  45892. */
  45893. get buffer() {
  45894. return this.nodeUniform.value;
  45895. }
  45896. }
  45897. /**
  45898. * A WebGPU backend utility module used by {@link WebGPUTextureUtils}.
  45899. *
  45900. * @private
  45901. */
  45902. class WebGPUTexturePassUtils extends DataMap {
  45903. /**
  45904. * Constructs a new utility object.
  45905. *
  45906. * @param {GPUDevice} device - The WebGPU device.
  45907. */
  45908. constructor( device ) {
  45909. super();
  45910. /**
  45911. * The WebGPU device.
  45912. *
  45913. * @type {GPUDevice}
  45914. */
  45915. this.device = device;
  45916. const mipmapVertexSource = `
  45917. struct VarysStruct {
  45918. @builtin( position ) Position: vec4<f32>,
  45919. @location( 0 ) vTex : vec2<f32>
  45920. };
  45921. @vertex
  45922. fn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {
  45923. var Varys : VarysStruct;
  45924. var pos = array< vec2<f32>, 4 >(
  45925. vec2<f32>( -1.0, 1.0 ),
  45926. vec2<f32>( 1.0, 1.0 ),
  45927. vec2<f32>( -1.0, -1.0 ),
  45928. vec2<f32>( 1.0, -1.0 )
  45929. );
  45930. var tex = array< vec2<f32>, 4 >(
  45931. vec2<f32>( 0.0, 0.0 ),
  45932. vec2<f32>( 1.0, 0.0 ),
  45933. vec2<f32>( 0.0, 1.0 ),
  45934. vec2<f32>( 1.0, 1.0 )
  45935. );
  45936. Varys.vTex = tex[ vertexIndex ];
  45937. Varys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );
  45938. return Varys;
  45939. }
  45940. `;
  45941. const mipmapFragmentSource = `
  45942. @group( 0 ) @binding( 0 )
  45943. var imgSampler : sampler;
  45944. @group( 0 ) @binding( 1 )
  45945. var img : texture_2d<f32>;
  45946. @fragment
  45947. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  45948. return textureSample( img, imgSampler, vTex );
  45949. }
  45950. `;
  45951. const flipYFragmentSource = `
  45952. @group( 0 ) @binding( 0 )
  45953. var imgSampler : sampler;
  45954. @group( 0 ) @binding( 1 )
  45955. var img : texture_2d<f32>;
  45956. @fragment
  45957. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  45958. return textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );
  45959. }
  45960. `;
  45961. /**
  45962. * The mipmap GPU sampler.
  45963. *
  45964. * @type {GPUSampler}
  45965. */
  45966. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  45967. /**
  45968. * The flipY GPU sampler.
  45969. *
  45970. * @type {GPUSampler}
  45971. */
  45972. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  45973. /**
  45974. * A cache for GPU render pipelines used for copy/transfer passes.
  45975. * Every texture format requires a unique pipeline.
  45976. *
  45977. * @type {Object<string,GPURenderPipeline>}
  45978. */
  45979. this.transferPipelines = {};
  45980. /**
  45981. * A cache for GPU render pipelines used for flipY passes.
  45982. * Every texture format requires a unique pipeline.
  45983. *
  45984. * @type {Object<string,GPURenderPipeline>}
  45985. */
  45986. this.flipYPipelines = {};
  45987. /**
  45988. * The mipmap vertex shader module.
  45989. *
  45990. * @type {GPUShaderModule}
  45991. */
  45992. this.mipmapVertexShaderModule = device.createShaderModule( {
  45993. label: 'mipmapVertex',
  45994. code: mipmapVertexSource
  45995. } );
  45996. /**
  45997. * The mipmap fragment shader module.
  45998. *
  45999. * @type {GPUShaderModule}
  46000. */
  46001. this.mipmapFragmentShaderModule = device.createShaderModule( {
  46002. label: 'mipmapFragment',
  46003. code: mipmapFragmentSource
  46004. } );
  46005. /**
  46006. * The flipY fragment shader module.
  46007. *
  46008. * @type {GPUShaderModule}
  46009. */
  46010. this.flipYFragmentShaderModule = device.createShaderModule( {
  46011. label: 'flipYFragment',
  46012. code: flipYFragmentSource
  46013. } );
  46014. }
  46015. /**
  46016. * Returns a render pipeline for the internal copy render pass. The pass
  46017. * requires a unique render pipeline for each texture format.
  46018. *
  46019. * @param {string} format - The GPU texture format
  46020. * @return {GPURenderPipeline} The GPU render pipeline.
  46021. */
  46022. getTransferPipeline( format ) {
  46023. let pipeline = this.transferPipelines[ format ];
  46024. if ( pipeline === undefined ) {
  46025. pipeline = this.device.createRenderPipeline( {
  46026. label: `mipmap-${ format }`,
  46027. vertex: {
  46028. module: this.mipmapVertexShaderModule,
  46029. entryPoint: 'main'
  46030. },
  46031. fragment: {
  46032. module: this.mipmapFragmentShaderModule,
  46033. entryPoint: 'main',
  46034. targets: [ { format } ]
  46035. },
  46036. primitive: {
  46037. topology: GPUPrimitiveTopology.TriangleStrip,
  46038. stripIndexFormat: GPUIndexFormat.Uint32
  46039. },
  46040. layout: 'auto'
  46041. } );
  46042. this.transferPipelines[ format ] = pipeline;
  46043. }
  46044. return pipeline;
  46045. }
  46046. /**
  46047. * Returns a render pipeline for the flipY render pass. The pass
  46048. * requires a unique render pipeline for each texture format.
  46049. *
  46050. * @param {string} format - The GPU texture format
  46051. * @return {GPURenderPipeline} The GPU render pipeline.
  46052. */
  46053. getFlipYPipeline( format ) {
  46054. let pipeline = this.flipYPipelines[ format ];
  46055. if ( pipeline === undefined ) {
  46056. pipeline = this.device.createRenderPipeline( {
  46057. label: `flipY-${ format }`,
  46058. vertex: {
  46059. module: this.mipmapVertexShaderModule,
  46060. entryPoint: 'main'
  46061. },
  46062. fragment: {
  46063. module: this.flipYFragmentShaderModule,
  46064. entryPoint: 'main',
  46065. targets: [ { format } ]
  46066. },
  46067. primitive: {
  46068. topology: GPUPrimitiveTopology.TriangleStrip,
  46069. stripIndexFormat: GPUIndexFormat.Uint32
  46070. },
  46071. layout: 'auto'
  46072. } );
  46073. this.flipYPipelines[ format ] = pipeline;
  46074. }
  46075. return pipeline;
  46076. }
  46077. /**
  46078. * Flip the contents of the given GPU texture along its vertical axis.
  46079. *
  46080. * @param {GPUTexture} textureGPU - The GPU texture object.
  46081. * @param {Object} textureGPUDescriptor - The texture descriptor.
  46082. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  46083. */
  46084. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  46085. const format = textureGPUDescriptor.format;
  46086. const { width, height } = textureGPUDescriptor.size;
  46087. const transferPipeline = this.getTransferPipeline( format );
  46088. const flipYPipeline = this.getFlipYPipeline( format );
  46089. const tempTexture = this.device.createTexture( {
  46090. size: { width, height, depthOrArrayLayers: 1 },
  46091. format,
  46092. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
  46093. } );
  46094. const srcView = textureGPU.createView( {
  46095. baseMipLevel: 0,
  46096. mipLevelCount: 1,
  46097. dimension: GPUTextureViewDimension.TwoD,
  46098. baseArrayLayer
  46099. } );
  46100. const dstView = tempTexture.createView( {
  46101. baseMipLevel: 0,
  46102. mipLevelCount: 1,
  46103. dimension: GPUTextureViewDimension.TwoD,
  46104. baseArrayLayer: 0
  46105. } );
  46106. const commandEncoder = this.device.createCommandEncoder( {} );
  46107. const pass = ( pipeline, sourceView, destinationView ) => {
  46108. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  46109. const bindGroup = this.device.createBindGroup( {
  46110. layout: bindGroupLayout,
  46111. entries: [ {
  46112. binding: 0,
  46113. resource: this.flipYSampler
  46114. }, {
  46115. binding: 1,
  46116. resource: sourceView
  46117. } ]
  46118. } );
  46119. const passEncoder = commandEncoder.beginRenderPass( {
  46120. colorAttachments: [ {
  46121. view: destinationView,
  46122. loadOp: GPULoadOp.Clear,
  46123. storeOp: GPUStoreOp.Store,
  46124. clearValue: [ 0, 0, 0, 0 ]
  46125. } ]
  46126. } );
  46127. passEncoder.setPipeline( pipeline );
  46128. passEncoder.setBindGroup( 0, bindGroup );
  46129. passEncoder.draw( 4, 1, 0, 0 );
  46130. passEncoder.end();
  46131. };
  46132. pass( transferPipeline, srcView, dstView );
  46133. pass( flipYPipeline, dstView, srcView );
  46134. this.device.queue.submit( [ commandEncoder.finish() ] );
  46135. tempTexture.destroy();
  46136. }
  46137. /**
  46138. * Generates mipmaps for the given GPU texture.
  46139. *
  46140. * @param {GPUTexture} textureGPU - The GPU texture object.
  46141. * @param {Object} textureGPUDescriptor - The texture descriptor.
  46142. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  46143. */
  46144. generateMipmaps( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  46145. const textureData = this.get( textureGPU );
  46146. if ( textureData.useCount === undefined ) {
  46147. textureData.useCount = 0;
  46148. textureData.layers = [];
  46149. }
  46150. const passes = textureData.layers[ baseArrayLayer ] || this._mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer );
  46151. const commandEncoder = this.device.createCommandEncoder( {} );
  46152. this._mipmapRunBundles( commandEncoder, passes );
  46153. this.device.queue.submit( [ commandEncoder.finish() ] );
  46154. if ( textureData.useCount !== 0 ) textureData.layers[ baseArrayLayer ] = passes;
  46155. textureData.useCount ++;
  46156. }
  46157. /**
  46158. * Since multiple copy render passes are required to generate mipmaps, the passes
  46159. * are managed as render bundles to improve performance.
  46160. *
  46161. * @param {GPUTexture} textureGPU - The GPU texture object.
  46162. * @param {Object} textureGPUDescriptor - The texture descriptor.
  46163. * @param {number} baseArrayLayer - The index of the first array layer accessible to the texture view.
  46164. * @return {Array<Object>} An array of render bundles.
  46165. */
  46166. _mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer ) {
  46167. const pipeline = this.getTransferPipeline( textureGPUDescriptor.format );
  46168. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  46169. let srcView = textureGPU.createView( {
  46170. baseMipLevel: 0,
  46171. mipLevelCount: 1,
  46172. dimension: GPUTextureViewDimension.TwoD,
  46173. baseArrayLayer
  46174. } );
  46175. const passes = [];
  46176. for ( let i = 1; i < textureGPUDescriptor.mipLevelCount; i ++ ) {
  46177. const bindGroup = this.device.createBindGroup( {
  46178. layout: bindGroupLayout,
  46179. entries: [ {
  46180. binding: 0,
  46181. resource: this.mipmapSampler
  46182. }, {
  46183. binding: 1,
  46184. resource: srcView
  46185. } ]
  46186. } );
  46187. const dstView = textureGPU.createView( {
  46188. baseMipLevel: i,
  46189. mipLevelCount: 1,
  46190. dimension: GPUTextureViewDimension.TwoD,
  46191. baseArrayLayer
  46192. } );
  46193. const passDescriptor = {
  46194. colorAttachments: [ {
  46195. view: dstView,
  46196. loadOp: GPULoadOp.Clear,
  46197. storeOp: GPUStoreOp.Store,
  46198. clearValue: [ 0, 0, 0, 0 ]
  46199. } ]
  46200. };
  46201. const passEncoder = this.device.createRenderBundleEncoder( {
  46202. colorFormats: [ textureGPUDescriptor.format ]
  46203. } );
  46204. passEncoder.setPipeline( pipeline );
  46205. passEncoder.setBindGroup( 0, bindGroup );
  46206. passEncoder.draw( 4, 1, 0, 0 );
  46207. passes.push( {
  46208. renderBundles: [ passEncoder.finish() ],
  46209. passDescriptor
  46210. } );
  46211. srcView = dstView;
  46212. }
  46213. return passes;
  46214. }
  46215. /**
  46216. * Executes the render bundles.
  46217. *
  46218. * @param {GPUCommandEncoder} commandEncoder - The GPU command encoder.
  46219. * @param {Array<Object>} passes - An array of render bundles.
  46220. */
  46221. _mipmapRunBundles( commandEncoder, passes ) {
  46222. const levels = passes.length;
  46223. for ( let i = 0; i < levels; i ++ ) {
  46224. const pass = passes[ i ];
  46225. const passEncoder = commandEncoder.beginRenderPass( pass.passDescriptor );
  46226. passEncoder.executeBundles( pass.renderBundles );
  46227. passEncoder.end();
  46228. }
  46229. }
  46230. }
  46231. const _compareToWebGPU = {
  46232. [ NeverCompare ]: 'never',
  46233. [ LessCompare ]: 'less',
  46234. [ EqualCompare ]: 'equal',
  46235. [ LessEqualCompare ]: 'less-equal',
  46236. [ GreaterCompare ]: 'greater',
  46237. [ GreaterEqualCompare ]: 'greater-equal',
  46238. [ AlwaysCompare ]: 'always',
  46239. [ NotEqualCompare ]: 'not-equal'
  46240. };
  46241. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  46242. /**
  46243. * A WebGPU backend utility module for managing textures.
  46244. *
  46245. * @private
  46246. */
  46247. class WebGPUTextureUtils {
  46248. /**
  46249. * Constructs a new utility object.
  46250. *
  46251. * @param {WebGPUBackend} backend - The WebGPU backend.
  46252. */
  46253. constructor( backend ) {
  46254. /**
  46255. * A reference to the WebGPU backend.
  46256. *
  46257. * @type {WebGPUBackend}
  46258. */
  46259. this.backend = backend;
  46260. /**
  46261. * A reference to the pass utils.
  46262. *
  46263. * @type {?WebGPUTexturePassUtils}
  46264. * @default null
  46265. */
  46266. this._passUtils = null;
  46267. /**
  46268. * A dictionary for managing default textures. The key
  46269. * is the texture format, the value the texture object.
  46270. *
  46271. * @type {Object<string,Texture>}
  46272. */
  46273. this.defaultTexture = {};
  46274. /**
  46275. * A dictionary for managing default cube textures. The key
  46276. * is the texture format, the value the texture object.
  46277. *
  46278. * @type {Object<string,CubeTexture>}
  46279. */
  46280. this.defaultCubeTexture = {};
  46281. /**
  46282. * A default video frame.
  46283. *
  46284. * @type {?VideoFrame}
  46285. * @default null
  46286. */
  46287. this.defaultVideoFrame = null;
  46288. /**
  46289. * Represents the color attachment of the default framebuffer.
  46290. *
  46291. * @type {?GPUTexture}
  46292. * @default null
  46293. */
  46294. this.colorBuffer = null;
  46295. /**
  46296. * Represents the depth attachment of the default framebuffer.
  46297. *
  46298. * @type {DepthTexture}
  46299. */
  46300. this.depthTexture = new DepthTexture();
  46301. this.depthTexture.name = 'depthBuffer';
  46302. }
  46303. /**
  46304. * Creates a GPU sampler for the given texture.
  46305. *
  46306. * @param {Texture} texture - The texture to create the sampler for.
  46307. */
  46308. createSampler( texture ) {
  46309. const backend = this.backend;
  46310. const device = backend.device;
  46311. const textureGPU = backend.get( texture );
  46312. const samplerDescriptorGPU = {
  46313. addressModeU: this._convertAddressMode( texture.wrapS ),
  46314. addressModeV: this._convertAddressMode( texture.wrapT ),
  46315. addressModeW: this._convertAddressMode( texture.wrapR ),
  46316. magFilter: this._convertFilterMode( texture.magFilter ),
  46317. minFilter: this._convertFilterMode( texture.minFilter ),
  46318. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  46319. maxAnisotropy: 1
  46320. };
  46321. // anisotropy can only be used when all filter modes are set to linear.
  46322. if ( samplerDescriptorGPU.magFilter === GPUFilterMode.Linear && samplerDescriptorGPU.minFilter === GPUFilterMode.Linear && samplerDescriptorGPU.mipmapFilter === GPUFilterMode.Linear ) {
  46323. samplerDescriptorGPU.maxAnisotropy = texture.anisotropy;
  46324. }
  46325. if ( texture.isDepthTexture && texture.compareFunction !== null ) {
  46326. samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ];
  46327. }
  46328. textureGPU.sampler = device.createSampler( samplerDescriptorGPU );
  46329. }
  46330. /**
  46331. * Creates a default texture for the given texture that can be used
  46332. * as a placeholder until the actual texture is ready for usage.
  46333. *
  46334. * @param {Texture} texture - The texture to create a default texture for.
  46335. */
  46336. createDefaultTexture( texture ) {
  46337. let textureGPU;
  46338. const format = getFormat( texture );
  46339. if ( texture.isCubeTexture ) {
  46340. textureGPU = this._getDefaultCubeTextureGPU( format );
  46341. } else {
  46342. textureGPU = this._getDefaultTextureGPU( format );
  46343. }
  46344. this.backend.get( texture ).texture = textureGPU;
  46345. }
  46346. /**
  46347. * Defines a texture on the GPU for the given texture object.
  46348. *
  46349. * @param {Texture} texture - The texture.
  46350. * @param {Object} [options={}] - Optional configuration parameter.
  46351. */
  46352. createTexture( texture, options = {} ) {
  46353. const backend = this.backend;
  46354. const textureData = backend.get( texture );
  46355. if ( textureData.initialized ) {
  46356. throw new Error( 'WebGPUTextureUtils: Texture already initialized.' );
  46357. }
  46358. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  46359. if ( options.levels === undefined ) options.levels = 1;
  46360. if ( options.depth === undefined ) options.depth = 1;
  46361. const { width, height, depth, levels } = options;
  46362. if ( texture.isFramebufferTexture ) {
  46363. if ( options.renderTarget ) {
  46364. options.format = this.backend.utils.getCurrentColorFormat( options.renderTarget );
  46365. } else {
  46366. options.format = this.backend.utils.getPreferredCanvasFormat();
  46367. }
  46368. }
  46369. const dimension = this._getDimension( texture );
  46370. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  46371. textureData.format = format;
  46372. const { samples, primarySamples, isMSAA } = backend.utils.getTextureSampleData( texture );
  46373. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  46374. if ( texture.isStorageTexture === true ) {
  46375. usage |= GPUTextureUsage.STORAGE_BINDING;
  46376. }
  46377. if ( texture.isCompressedTexture !== true && texture.isCompressedArrayTexture !== true ) {
  46378. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  46379. }
  46380. const textureDescriptorGPU = {
  46381. label: texture.name,
  46382. size: {
  46383. width: width,
  46384. height: height,
  46385. depthOrArrayLayers: depth,
  46386. },
  46387. mipLevelCount: levels,
  46388. sampleCount: primarySamples,
  46389. dimension: dimension,
  46390. format: format,
  46391. usage: usage
  46392. };
  46393. // texture creation
  46394. if ( format === undefined ) {
  46395. console.warn( 'WebGPURenderer: Texture format not supported.' );
  46396. this.createDefaultTexture( texture );
  46397. return;
  46398. }
  46399. if ( texture.isCubeTexture ) {
  46400. textureDescriptorGPU.textureBindingViewDimension = GPUTextureViewDimension.Cube;
  46401. }
  46402. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  46403. if ( isMSAA ) {
  46404. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  46405. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  46406. msaaTextureDescriptorGPU.sampleCount = samples;
  46407. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  46408. }
  46409. textureData.initialized = true;
  46410. textureData.textureDescriptorGPU = textureDescriptorGPU;
  46411. }
  46412. /**
  46413. * Destroys the GPU data for the given texture object.
  46414. *
  46415. * @param {Texture} texture - The texture.
  46416. */
  46417. destroyTexture( texture ) {
  46418. const backend = this.backend;
  46419. const textureData = backend.get( texture );
  46420. if ( textureData.texture !== undefined ) textureData.texture.destroy();
  46421. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  46422. backend.delete( texture );
  46423. }
  46424. /**
  46425. * Destroys the GPU sampler for the given texture.
  46426. *
  46427. * @param {Texture} texture - The texture to destroy the sampler for.
  46428. */
  46429. destroySampler( texture ) {
  46430. const backend = this.backend;
  46431. const textureData = backend.get( texture );
  46432. delete textureData.sampler;
  46433. }
  46434. /**
  46435. * Generates mipmaps for the given texture.
  46436. *
  46437. * @param {Texture} texture - The texture.
  46438. */
  46439. generateMipmaps( texture ) {
  46440. const textureData = this.backend.get( texture );
  46441. if ( texture.isCubeTexture ) {
  46442. for ( let i = 0; i < 6; i ++ ) {
  46443. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  46444. }
  46445. } else {
  46446. const depth = texture.image.depth || 1;
  46447. for ( let i = 0; i < depth; i ++ ) {
  46448. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  46449. }
  46450. }
  46451. }
  46452. /**
  46453. * Returns the color buffer representing the color
  46454. * attachment of the default framebuffer.
  46455. *
  46456. * @return {GPUTexture} The color buffer.
  46457. */
  46458. getColorBuffer() {
  46459. if ( this.colorBuffer ) this.colorBuffer.destroy();
  46460. const backend = this.backend;
  46461. const { width, height } = backend.getDrawingBufferSize();
  46462. this.colorBuffer = backend.device.createTexture( {
  46463. label: 'colorBuffer',
  46464. size: {
  46465. width: width,
  46466. height: height,
  46467. depthOrArrayLayers: 1
  46468. },
  46469. sampleCount: backend.utils.getSampleCount( backend.renderer.samples ),
  46470. format: backend.utils.getPreferredCanvasFormat(),
  46471. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  46472. } );
  46473. return this.colorBuffer;
  46474. }
  46475. /**
  46476. * Returns the depth buffer representing the depth
  46477. * attachment of the default framebuffer.
  46478. *
  46479. * @param {boolean} [depth=true] - Whether depth is enabled or not.
  46480. * @param {boolean} [stencil=false] - Whether stencil is enabled or not.
  46481. * @return {GPUTexture} The depth buffer.
  46482. */
  46483. getDepthBuffer( depth = true, stencil = false ) {
  46484. const backend = this.backend;
  46485. const { width, height } = backend.getDrawingBufferSize();
  46486. const depthTexture = this.depthTexture;
  46487. const depthTextureGPU = backend.get( depthTexture ).texture;
  46488. let format, type;
  46489. if ( stencil ) {
  46490. format = DepthStencilFormat;
  46491. type = UnsignedInt248Type;
  46492. } else if ( depth ) {
  46493. format = DepthFormat;
  46494. type = UnsignedIntType;
  46495. }
  46496. if ( depthTextureGPU !== undefined ) {
  46497. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type ) {
  46498. return depthTextureGPU;
  46499. }
  46500. this.destroyTexture( depthTexture );
  46501. }
  46502. depthTexture.name = 'depthBuffer';
  46503. depthTexture.format = format;
  46504. depthTexture.type = type;
  46505. depthTexture.image.width = width;
  46506. depthTexture.image.height = height;
  46507. this.createTexture( depthTexture, { width, height } );
  46508. return backend.get( depthTexture ).texture;
  46509. }
  46510. /**
  46511. * Uploads the updated texture data to the GPU.
  46512. *
  46513. * @param {Texture} texture - The texture.
  46514. * @param {Object} [options={}] - Optional configuration parameter.
  46515. */
  46516. updateTexture( texture, options ) {
  46517. const textureData = this.backend.get( texture );
  46518. const { textureDescriptorGPU } = textureData;
  46519. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  46520. return;
  46521. // transfer texture data
  46522. if ( texture.isDataTexture ) {
  46523. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  46524. } else if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isData3DTexture ) {
  46525. for ( let i = 0; i < options.image.depth; i ++ ) {
  46526. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  46527. }
  46528. } else if ( texture.isCompressedTexture || texture.isCompressedArrayTexture ) {
  46529. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  46530. } else if ( texture.isCubeTexture ) {
  46531. this._copyCubeMapToTexture( options.images, textureData.texture, textureDescriptorGPU, texture.flipY, texture.premultiplyAlpha );
  46532. } else {
  46533. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY, texture.premultiplyAlpha );
  46534. }
  46535. //
  46536. textureData.version = texture.version;
  46537. if ( texture.onUpdate ) texture.onUpdate( texture );
  46538. }
  46539. /**
  46540. * Returns texture data as a typed array.
  46541. *
  46542. * @async
  46543. * @param {Texture} texture - The texture to copy.
  46544. * @param {number} x - The x coordinate of the copy origin.
  46545. * @param {number} y - The y coordinate of the copy origin.
  46546. * @param {number} width - The width of the copy.
  46547. * @param {number} height - The height of the copy.
  46548. * @param {number} faceIndex - The face index.
  46549. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  46550. */
  46551. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  46552. const device = this.backend.device;
  46553. const textureData = this.backend.get( texture );
  46554. const textureGPU = textureData.texture;
  46555. const format = textureData.textureDescriptorGPU.format;
  46556. const bytesPerTexel = this._getBytesPerTexel( format );
  46557. let bytesPerRow = width * bytesPerTexel;
  46558. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  46559. const readBuffer = device.createBuffer(
  46560. {
  46561. size: width * height * bytesPerTexel,
  46562. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  46563. }
  46564. );
  46565. const encoder = device.createCommandEncoder();
  46566. encoder.copyTextureToBuffer(
  46567. {
  46568. texture: textureGPU,
  46569. origin: { x, y, z: faceIndex },
  46570. },
  46571. {
  46572. buffer: readBuffer,
  46573. bytesPerRow: bytesPerRow
  46574. },
  46575. {
  46576. width: width,
  46577. height: height
  46578. }
  46579. );
  46580. const typedArrayType = this._getTypedArrayType( format );
  46581. device.queue.submit( [ encoder.finish() ] );
  46582. await readBuffer.mapAsync( GPUMapMode.READ );
  46583. const buffer = readBuffer.getMappedRange();
  46584. return new typedArrayType( buffer );
  46585. }
  46586. /**
  46587. * Returns the default GPU texture for the given format.
  46588. *
  46589. * @private
  46590. * @param {string} format - The GPU format.
  46591. * @return {GPUTexture} The GPU texture.
  46592. */
  46593. _getDefaultTextureGPU( format ) {
  46594. let defaultTexture = this.defaultTexture[ format ];
  46595. if ( defaultTexture === undefined ) {
  46596. const texture = new Texture();
  46597. texture.minFilter = NearestFilter;
  46598. texture.magFilter = NearestFilter;
  46599. this.createTexture( texture, { width: 1, height: 1, format } );
  46600. this.defaultTexture[ format ] = defaultTexture = texture;
  46601. }
  46602. return this.backend.get( defaultTexture ).texture;
  46603. }
  46604. /**
  46605. * Returns the default GPU cube texture for the given format.
  46606. *
  46607. * @private
  46608. * @param {string} format - The GPU format.
  46609. * @return {GPUTexture} The GPU texture.
  46610. */
  46611. _getDefaultCubeTextureGPU( format ) {
  46612. let defaultCubeTexture = this.defaultTexture[ format ];
  46613. if ( defaultCubeTexture === undefined ) {
  46614. const texture = new CubeTexture();
  46615. texture.minFilter = NearestFilter;
  46616. texture.magFilter = NearestFilter;
  46617. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  46618. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  46619. }
  46620. return this.backend.get( defaultCubeTexture ).texture;
  46621. }
  46622. /**
  46623. * Uploads cube texture image data to the GPU memory.
  46624. *
  46625. * @private
  46626. * @param {Array} images - The cube image data.
  46627. * @param {GPUTexture} textureGPU - The GPU texture.
  46628. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  46629. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  46630. * @param {boolean} premultiplyAlpha - Whether the texture should have its RGB channels premultiplied by the alpha channel or not.
  46631. */
  46632. _copyCubeMapToTexture( images, textureGPU, textureDescriptorGPU, flipY, premultiplyAlpha ) {
  46633. for ( let i = 0; i < 6; i ++ ) {
  46634. const image = images[ i ];
  46635. const flipIndex = flipY === true ? _flipMap[ i ] : i;
  46636. if ( image.isDataTexture ) {
  46637. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  46638. } else {
  46639. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, flipY, premultiplyAlpha );
  46640. }
  46641. }
  46642. }
  46643. /**
  46644. * Uploads texture image data to the GPU memory.
  46645. *
  46646. * @private
  46647. * @param {HTMLImageElement|ImageBitmap|HTMLCanvasElement} image - The image data.
  46648. * @param {GPUTexture} textureGPU - The GPU texture.
  46649. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  46650. * @param {number} originDepth - The origin depth.
  46651. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  46652. * @param {boolean} premultiplyAlpha - Whether the texture should have its RGB channels premultiplied by the alpha channel or not.
  46653. */
  46654. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, premultiplyAlpha ) {
  46655. const device = this.backend.device;
  46656. device.queue.copyExternalImageToTexture(
  46657. {
  46658. source: image,
  46659. flipY: flipY
  46660. }, {
  46661. texture: textureGPU,
  46662. mipLevel: 0,
  46663. origin: { x: 0, y: 0, z: originDepth },
  46664. premultipliedAlpha: premultiplyAlpha
  46665. }, {
  46666. width: textureDescriptorGPU.size.width,
  46667. height: textureDescriptorGPU.size.height,
  46668. depthOrArrayLayers: 1
  46669. }
  46670. );
  46671. }
  46672. /**
  46673. * Returns the pass utils singleton.
  46674. *
  46675. * @private
  46676. * @return {WebGPUTexturePassUtils} The utils instance.
  46677. */
  46678. _getPassUtils() {
  46679. let passUtils = this._passUtils;
  46680. if ( passUtils === null ) {
  46681. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  46682. }
  46683. return passUtils;
  46684. }
  46685. /**
  46686. * Generates mipmaps for the given GPU texture.
  46687. *
  46688. * @private
  46689. * @param {GPUTexture} textureGPU - The GPU texture object.
  46690. * @param {Object} textureDescriptorGPU - The texture descriptor.
  46691. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  46692. */
  46693. _generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer = 0 ) {
  46694. this._getPassUtils().generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer );
  46695. }
  46696. /**
  46697. * Flip the contents of the given GPU texture along its vertical axis.
  46698. *
  46699. * @private
  46700. * @param {GPUTexture} textureGPU - The GPU texture object.
  46701. * @param {Object} textureDescriptorGPU - The texture descriptor.
  46702. * @param {number} [originDepth=0] - The origin depth.
  46703. */
  46704. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  46705. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  46706. }
  46707. /**
  46708. * Uploads texture buffer data to the GPU memory.
  46709. *
  46710. * @private
  46711. * @param {Object} image - An object defining the image buffer data.
  46712. * @param {GPUTexture} textureGPU - The GPU texture.
  46713. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  46714. * @param {number} originDepth - The origin depth.
  46715. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  46716. * @param {number} [depth=0] - TODO.
  46717. */
  46718. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0 ) {
  46719. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  46720. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  46721. const device = this.backend.device;
  46722. const data = image.data;
  46723. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  46724. const bytesPerRow = image.width * bytesPerTexel;
  46725. device.queue.writeTexture(
  46726. {
  46727. texture: textureGPU,
  46728. mipLevel: 0,
  46729. origin: { x: 0, y: 0, z: originDepth }
  46730. },
  46731. data,
  46732. {
  46733. offset: image.width * image.height * bytesPerTexel * depth,
  46734. bytesPerRow
  46735. },
  46736. {
  46737. width: image.width,
  46738. height: image.height,
  46739. depthOrArrayLayers: 1
  46740. } );
  46741. if ( flipY === true ) {
  46742. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  46743. }
  46744. }
  46745. /**
  46746. * Uploads compressed texture data to the GPU memory.
  46747. *
  46748. * @private
  46749. * @param {Array<Object>} mipmaps - An array with mipmap data.
  46750. * @param {GPUTexture} textureGPU - The GPU texture.
  46751. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  46752. */
  46753. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU ) {
  46754. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  46755. const device = this.backend.device;
  46756. const blockData = this._getBlockData( textureDescriptorGPU.format );
  46757. const isArrayTexture = textureDescriptorGPU.size.depthOrArrayLayers > 1;
  46758. for ( let i = 0; i < mipmaps.length; i ++ ) {
  46759. const mipmap = mipmaps[ i ];
  46760. const width = mipmap.width;
  46761. const height = mipmap.height;
  46762. const depth = isArrayTexture ? textureDescriptorGPU.size.depthOrArrayLayers : 1;
  46763. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  46764. const bytesPerImage = bytesPerRow * Math.ceil( height / blockData.height );
  46765. for ( let j = 0; j < depth; j ++ ) {
  46766. device.queue.writeTexture(
  46767. {
  46768. texture: textureGPU,
  46769. mipLevel: i,
  46770. origin: { x: 0, y: 0, z: j }
  46771. },
  46772. mipmap.data,
  46773. {
  46774. offset: j * bytesPerImage,
  46775. bytesPerRow,
  46776. rowsPerImage: Math.ceil( height / blockData.height )
  46777. },
  46778. {
  46779. width: Math.ceil( width / blockData.width ) * blockData.width,
  46780. height: Math.ceil( height / blockData.height ) * blockData.height,
  46781. depthOrArrayLayers: 1
  46782. }
  46783. );
  46784. }
  46785. }
  46786. }
  46787. /**
  46788. * This method is only relevant for compressed texture formats. It returns a block
  46789. * data descriptor for the given GPU compressed texture format.
  46790. *
  46791. * @private
  46792. * @param {string} format - The GPU compressed texture format.
  46793. * @return {Object} The block data descriptor.
  46794. */
  46795. _getBlockData( format ) {
  46796. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  46797. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  46798. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  46799. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSnorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  46800. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  46801. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  46802. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  46803. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  46804. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  46805. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  46806. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  46807. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  46808. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  46809. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  46810. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  46811. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  46812. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  46813. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  46814. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  46815. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  46816. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  46817. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  46818. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  46819. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  46820. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  46821. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  46822. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  46823. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  46824. }
  46825. /**
  46826. * Converts the three.js uv wrapping constants to GPU address mode constants.
  46827. *
  46828. * @private
  46829. * @param {number} value - The three.js constant defining a uv wrapping mode.
  46830. * @return {string} The GPU address mode.
  46831. */
  46832. _convertAddressMode( value ) {
  46833. let addressMode = GPUAddressMode.ClampToEdge;
  46834. if ( value === RepeatWrapping ) {
  46835. addressMode = GPUAddressMode.Repeat;
  46836. } else if ( value === MirroredRepeatWrapping ) {
  46837. addressMode = GPUAddressMode.MirrorRepeat;
  46838. }
  46839. return addressMode;
  46840. }
  46841. /**
  46842. * Converts the three.js filter constants to GPU filter constants.
  46843. *
  46844. * @private
  46845. * @param {number} value - The three.js constant defining a filter mode.
  46846. * @return {string} The GPU filter mode.
  46847. */
  46848. _convertFilterMode( value ) {
  46849. let filterMode = GPUFilterMode.Linear;
  46850. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  46851. filterMode = GPUFilterMode.Nearest;
  46852. }
  46853. return filterMode;
  46854. }
  46855. /**
  46856. * Returns the bytes-per-texel value for the given GPU texture format.
  46857. *
  46858. * @private
  46859. * @param {string} format - The GPU texture format.
  46860. * @return {number} The bytes-per-texel.
  46861. */
  46862. _getBytesPerTexel( format ) {
  46863. // 8-bit formats
  46864. if ( format === GPUTextureFormat.R8Unorm ||
  46865. format === GPUTextureFormat.R8Snorm ||
  46866. format === GPUTextureFormat.R8Uint ||
  46867. format === GPUTextureFormat.R8Sint ) return 1;
  46868. // 16-bit formats
  46869. if ( format === GPUTextureFormat.R16Uint ||
  46870. format === GPUTextureFormat.R16Sint ||
  46871. format === GPUTextureFormat.R16Float ||
  46872. format === GPUTextureFormat.RG8Unorm ||
  46873. format === GPUTextureFormat.RG8Snorm ||
  46874. format === GPUTextureFormat.RG8Uint ||
  46875. format === GPUTextureFormat.RG8Sint ) return 2;
  46876. // 32-bit formats
  46877. if ( format === GPUTextureFormat.R32Uint ||
  46878. format === GPUTextureFormat.R32Sint ||
  46879. format === GPUTextureFormat.R32Float ||
  46880. format === GPUTextureFormat.RG16Uint ||
  46881. format === GPUTextureFormat.RG16Sint ||
  46882. format === GPUTextureFormat.RG16Float ||
  46883. format === GPUTextureFormat.RGBA8Unorm ||
  46884. format === GPUTextureFormat.RGBA8UnormSRGB ||
  46885. format === GPUTextureFormat.RGBA8Snorm ||
  46886. format === GPUTextureFormat.RGBA8Uint ||
  46887. format === GPUTextureFormat.RGBA8Sint ||
  46888. format === GPUTextureFormat.BGRA8Unorm ||
  46889. format === GPUTextureFormat.BGRA8UnormSRGB ||
  46890. // Packed 32-bit formats
  46891. format === GPUTextureFormat.RGB9E5UFloat ||
  46892. format === GPUTextureFormat.RGB10A2Unorm ||
  46893. format === GPUTextureFormat.RG11B10UFloat ||
  46894. format === GPUTextureFormat.Depth32Float ||
  46895. format === GPUTextureFormat.Depth24Plus ||
  46896. format === GPUTextureFormat.Depth24PlusStencil8 ||
  46897. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  46898. // 64-bit formats
  46899. if ( format === GPUTextureFormat.RG32Uint ||
  46900. format === GPUTextureFormat.RG32Sint ||
  46901. format === GPUTextureFormat.RG32Float ||
  46902. format === GPUTextureFormat.RGBA16Uint ||
  46903. format === GPUTextureFormat.RGBA16Sint ||
  46904. format === GPUTextureFormat.RGBA16Float ) return 8;
  46905. // 128-bit formats
  46906. if ( format === GPUTextureFormat.RGBA32Uint ||
  46907. format === GPUTextureFormat.RGBA32Sint ||
  46908. format === GPUTextureFormat.RGBA32Float ) return 16;
  46909. }
  46910. /**
  46911. * Returns the corresponding typed array type for the given GPU texture format.
  46912. *
  46913. * @private
  46914. * @param {string} format - The GPU texture format.
  46915. * @return {TypedArray.constructor} The typed array type.
  46916. */
  46917. _getTypedArrayType( format ) {
  46918. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  46919. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  46920. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  46921. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  46922. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  46923. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  46924. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  46925. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  46926. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  46927. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  46928. if ( format === GPUTextureFormat.RGBA8Unorm ) return Uint8Array;
  46929. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  46930. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  46931. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  46932. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  46933. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  46934. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  46935. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  46936. if ( format === GPUTextureFormat.R16Float ) return Uint16Array;
  46937. if ( format === GPUTextureFormat.RG16Float ) return Uint16Array;
  46938. if ( format === GPUTextureFormat.RGBA16Float ) return Uint16Array;
  46939. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  46940. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  46941. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  46942. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  46943. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  46944. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  46945. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  46946. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  46947. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  46948. if ( format === GPUTextureFormat.BGRA8Unorm ) return Uint8Array;
  46949. if ( format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  46950. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  46951. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  46952. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  46953. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  46954. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  46955. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  46956. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  46957. }
  46958. /**
  46959. * Returns the GPU dimensions for the given texture.
  46960. *
  46961. * @private
  46962. * @param {Texture} texture - The texture.
  46963. * @return {string} The GPU dimension.
  46964. */
  46965. _getDimension( texture ) {
  46966. let dimension;
  46967. if ( texture.is3DTexture || texture.isData3DTexture ) {
  46968. dimension = GPUTextureDimension.ThreeD;
  46969. } else {
  46970. dimension = GPUTextureDimension.TwoD;
  46971. }
  46972. return dimension;
  46973. }
  46974. }
  46975. /**
  46976. * Returns the GPU format for the given texture.
  46977. *
  46978. * @param {Texture} texture - The texture.
  46979. * @param {?GPUDevice} [device=null] - The GPU device which is used for feature detection.
  46980. * It is not necessary to apply the device for most formats.
  46981. * @return {string} The GPU format.
  46982. */
  46983. function getFormat( texture, device = null ) {
  46984. const format = texture.format;
  46985. const type = texture.type;
  46986. const colorSpace = texture.colorSpace;
  46987. const transfer = ColorManagement.getTransfer( colorSpace );
  46988. let formatGPU;
  46989. if ( texture.isCompressedTexture === true || texture.isCompressedArrayTexture === true ) {
  46990. switch ( format ) {
  46991. case RGBA_S3TC_DXT1_Format:
  46992. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  46993. break;
  46994. case RGBA_S3TC_DXT3_Format:
  46995. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  46996. break;
  46997. case RGBA_S3TC_DXT5_Format:
  46998. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  46999. break;
  47000. case RGB_ETC2_Format:
  47001. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  47002. break;
  47003. case RGBA_ETC2_EAC_Format:
  47004. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  47005. break;
  47006. case RGBA_ASTC_4x4_Format:
  47007. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  47008. break;
  47009. case RGBA_ASTC_5x4_Format:
  47010. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  47011. break;
  47012. case RGBA_ASTC_5x5_Format:
  47013. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  47014. break;
  47015. case RGBA_ASTC_6x5_Format:
  47016. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  47017. break;
  47018. case RGBA_ASTC_6x6_Format:
  47019. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  47020. break;
  47021. case RGBA_ASTC_8x5_Format:
  47022. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  47023. break;
  47024. case RGBA_ASTC_8x6_Format:
  47025. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  47026. break;
  47027. case RGBA_ASTC_8x8_Format:
  47028. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  47029. break;
  47030. case RGBA_ASTC_10x5_Format:
  47031. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  47032. break;
  47033. case RGBA_ASTC_10x6_Format:
  47034. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  47035. break;
  47036. case RGBA_ASTC_10x8_Format:
  47037. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  47038. break;
  47039. case RGBA_ASTC_10x10_Format:
  47040. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  47041. break;
  47042. case RGBA_ASTC_12x10_Format:
  47043. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  47044. break;
  47045. case RGBA_ASTC_12x12_Format:
  47046. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  47047. break;
  47048. case RGBAFormat:
  47049. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  47050. break;
  47051. default:
  47052. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  47053. }
  47054. } else {
  47055. switch ( format ) {
  47056. case RGBAFormat:
  47057. switch ( type ) {
  47058. case ByteType:
  47059. formatGPU = GPUTextureFormat.RGBA8Snorm;
  47060. break;
  47061. case ShortType:
  47062. formatGPU = GPUTextureFormat.RGBA16Sint;
  47063. break;
  47064. case UnsignedShortType:
  47065. formatGPU = GPUTextureFormat.RGBA16Uint;
  47066. break;
  47067. case UnsignedIntType:
  47068. formatGPU = GPUTextureFormat.RGBA32Uint;
  47069. break;
  47070. case IntType:
  47071. formatGPU = GPUTextureFormat.RGBA32Sint;
  47072. break;
  47073. case UnsignedByteType:
  47074. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  47075. break;
  47076. case HalfFloatType:
  47077. formatGPU = GPUTextureFormat.RGBA16Float;
  47078. break;
  47079. case FloatType:
  47080. formatGPU = GPUTextureFormat.RGBA32Float;
  47081. break;
  47082. default:
  47083. console.error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  47084. }
  47085. break;
  47086. case RGBFormat:
  47087. switch ( type ) {
  47088. case UnsignedInt5999Type:
  47089. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  47090. break;
  47091. default:
  47092. console.error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  47093. }
  47094. break;
  47095. case RedFormat:
  47096. switch ( type ) {
  47097. case ByteType:
  47098. formatGPU = GPUTextureFormat.R8Snorm;
  47099. break;
  47100. case ShortType:
  47101. formatGPU = GPUTextureFormat.R16Sint;
  47102. break;
  47103. case UnsignedShortType:
  47104. formatGPU = GPUTextureFormat.R16Uint;
  47105. break;
  47106. case UnsignedIntType:
  47107. formatGPU = GPUTextureFormat.R32Uint;
  47108. break;
  47109. case IntType:
  47110. formatGPU = GPUTextureFormat.R32Sint;
  47111. break;
  47112. case UnsignedByteType:
  47113. formatGPU = GPUTextureFormat.R8Unorm;
  47114. break;
  47115. case HalfFloatType:
  47116. formatGPU = GPUTextureFormat.R16Float;
  47117. break;
  47118. case FloatType:
  47119. formatGPU = GPUTextureFormat.R32Float;
  47120. break;
  47121. default:
  47122. console.error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  47123. }
  47124. break;
  47125. case RGFormat:
  47126. switch ( type ) {
  47127. case ByteType:
  47128. formatGPU = GPUTextureFormat.RG8Snorm;
  47129. break;
  47130. case ShortType:
  47131. formatGPU = GPUTextureFormat.RG16Sint;
  47132. break;
  47133. case UnsignedShortType:
  47134. formatGPU = GPUTextureFormat.RG16Uint;
  47135. break;
  47136. case UnsignedIntType:
  47137. formatGPU = GPUTextureFormat.RG32Uint;
  47138. break;
  47139. case IntType:
  47140. formatGPU = GPUTextureFormat.RG32Sint;
  47141. break;
  47142. case UnsignedByteType:
  47143. formatGPU = GPUTextureFormat.RG8Unorm;
  47144. break;
  47145. case HalfFloatType:
  47146. formatGPU = GPUTextureFormat.RG16Float;
  47147. break;
  47148. case FloatType:
  47149. formatGPU = GPUTextureFormat.RG32Float;
  47150. break;
  47151. default:
  47152. console.error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  47153. }
  47154. break;
  47155. case DepthFormat:
  47156. switch ( type ) {
  47157. case UnsignedShortType:
  47158. formatGPU = GPUTextureFormat.Depth16Unorm;
  47159. break;
  47160. case UnsignedIntType:
  47161. formatGPU = GPUTextureFormat.Depth24Plus;
  47162. break;
  47163. case FloatType:
  47164. formatGPU = GPUTextureFormat.Depth32Float;
  47165. break;
  47166. default:
  47167. console.error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  47168. }
  47169. break;
  47170. case DepthStencilFormat:
  47171. switch ( type ) {
  47172. case UnsignedInt248Type:
  47173. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  47174. break;
  47175. case FloatType:
  47176. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  47177. console.error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  47178. }
  47179. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  47180. break;
  47181. default:
  47182. console.error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  47183. }
  47184. break;
  47185. case RedIntegerFormat:
  47186. switch ( type ) {
  47187. case IntType:
  47188. formatGPU = GPUTextureFormat.R32Sint;
  47189. break;
  47190. case UnsignedIntType:
  47191. formatGPU = GPUTextureFormat.R32Uint;
  47192. break;
  47193. default:
  47194. console.error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  47195. }
  47196. break;
  47197. case RGIntegerFormat:
  47198. switch ( type ) {
  47199. case IntType:
  47200. formatGPU = GPUTextureFormat.RG32Sint;
  47201. break;
  47202. case UnsignedIntType:
  47203. formatGPU = GPUTextureFormat.RG32Uint;
  47204. break;
  47205. default:
  47206. console.error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  47207. }
  47208. break;
  47209. case RGBAIntegerFormat:
  47210. switch ( type ) {
  47211. case IntType:
  47212. formatGPU = GPUTextureFormat.RGBA32Sint;
  47213. break;
  47214. case UnsignedIntType:
  47215. formatGPU = GPUTextureFormat.RGBA32Uint;
  47216. break;
  47217. default:
  47218. console.error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  47219. }
  47220. break;
  47221. default:
  47222. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  47223. }
  47224. }
  47225. return formatGPU;
  47226. }
  47227. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  47228. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  47229. const wgslTypeLib$1 = {
  47230. 'f32': 'float',
  47231. 'i32': 'int',
  47232. 'u32': 'uint',
  47233. 'bool': 'bool',
  47234. 'vec2<f32>': 'vec2',
  47235. 'vec2<i32>': 'ivec2',
  47236. 'vec2<u32>': 'uvec2',
  47237. 'vec2<bool>': 'bvec2',
  47238. 'vec2f': 'vec2',
  47239. 'vec2i': 'ivec2',
  47240. 'vec2u': 'uvec2',
  47241. 'vec2b': 'bvec2',
  47242. 'vec3<f32>': 'vec3',
  47243. 'vec3<i32>': 'ivec3',
  47244. 'vec3<u32>': 'uvec3',
  47245. 'vec3<bool>': 'bvec3',
  47246. 'vec3f': 'vec3',
  47247. 'vec3i': 'ivec3',
  47248. 'vec3u': 'uvec3',
  47249. 'vec3b': 'bvec3',
  47250. 'vec4<f32>': 'vec4',
  47251. 'vec4<i32>': 'ivec4',
  47252. 'vec4<u32>': 'uvec4',
  47253. 'vec4<bool>': 'bvec4',
  47254. 'vec4f': 'vec4',
  47255. 'vec4i': 'ivec4',
  47256. 'vec4u': 'uvec4',
  47257. 'vec4b': 'bvec4',
  47258. 'mat2x2<f32>': 'mat2',
  47259. 'mat2x2f': 'mat2',
  47260. 'mat3x3<f32>': 'mat3',
  47261. 'mat3x3f': 'mat3',
  47262. 'mat4x4<f32>': 'mat4',
  47263. 'mat4x4f': 'mat4',
  47264. 'sampler': 'sampler',
  47265. 'texture_1d': 'texture',
  47266. 'texture_2d': 'texture',
  47267. 'texture_2d_array': 'texture',
  47268. 'texture_multisampled_2d': 'cubeTexture',
  47269. 'texture_depth_2d': 'depthTexture',
  47270. 'texture_depth_2d_array': 'depthTexture',
  47271. 'texture_depth_multisampled_2d': 'depthTexture',
  47272. 'texture_depth_cube': 'depthTexture',
  47273. 'texture_depth_cube_array': 'depthTexture',
  47274. 'texture_3d': 'texture3D',
  47275. 'texture_cube': 'cubeTexture',
  47276. 'texture_cube_array': 'cubeTexture',
  47277. 'texture_storage_1d': 'storageTexture',
  47278. 'texture_storage_2d': 'storageTexture',
  47279. 'texture_storage_2d_array': 'storageTexture',
  47280. 'texture_storage_3d': 'storageTexture'
  47281. };
  47282. const parse = ( source ) => {
  47283. source = source.trim();
  47284. const declaration = source.match( declarationRegexp );
  47285. if ( declaration !== null && declaration.length === 4 ) {
  47286. const inputsCode = declaration[ 2 ];
  47287. const propsMatches = [];
  47288. let match = null;
  47289. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  47290. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  47291. }
  47292. // Process matches to correctly pair names and types
  47293. const inputs = [];
  47294. for ( let i = 0; i < propsMatches.length; i ++ ) {
  47295. const { name, type } = propsMatches[ i ];
  47296. let resolvedType = type;
  47297. if ( resolvedType.startsWith( 'ptr' ) ) {
  47298. resolvedType = 'pointer';
  47299. } else {
  47300. if ( resolvedType.startsWith( 'texture' ) ) {
  47301. resolvedType = type.split( '<' )[ 0 ];
  47302. }
  47303. resolvedType = wgslTypeLib$1[ resolvedType ];
  47304. }
  47305. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  47306. }
  47307. const blockCode = source.substring( declaration[ 0 ].length );
  47308. const outputType = declaration[ 3 ] || 'void';
  47309. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  47310. const type = wgslTypeLib$1[ outputType ] || outputType;
  47311. return {
  47312. type,
  47313. inputs,
  47314. name,
  47315. inputsCode,
  47316. blockCode,
  47317. outputType
  47318. };
  47319. } else {
  47320. throw new Error( 'FunctionNode: Function is not a WGSL code.' );
  47321. }
  47322. };
  47323. /**
  47324. * This class represents a WSL node function.
  47325. *
  47326. * @augments NodeFunction
  47327. */
  47328. class WGSLNodeFunction extends NodeFunction {
  47329. /**
  47330. * Constructs a new WGSL node function.
  47331. *
  47332. * @param {string} source - The WGSL source.
  47333. */
  47334. constructor( source ) {
  47335. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  47336. super( type, inputs, name );
  47337. this.inputsCode = inputsCode;
  47338. this.blockCode = blockCode;
  47339. this.outputType = outputType;
  47340. }
  47341. /**
  47342. * This method returns the WGSL code of the node function.
  47343. *
  47344. * @param {string} [name=this.name] - The function's name.
  47345. * @return {string} The shader code.
  47346. */
  47347. getCode( name = this.name ) {
  47348. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  47349. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  47350. }
  47351. }
  47352. /**
  47353. * A WGSL node parser.
  47354. *
  47355. * @augments NodeParser
  47356. */
  47357. class WGSLNodeParser extends NodeParser {
  47358. /**
  47359. * The method parses the given WGSL code an returns a node function.
  47360. *
  47361. * @param {string} source - The WGSL code.
  47362. * @return {WGSLNodeFunction} A node function.
  47363. */
  47364. parseFunction( source ) {
  47365. return new WGSLNodeFunction( source );
  47366. }
  47367. }
  47368. // GPUShaderStage is not defined in browsers not supporting WebGPU
  47369. const GPUShaderStage = ( typeof self !== 'undefined' ) ? self.GPUShaderStage : { VERTEX: 1, FRAGMENT: 2, COMPUTE: 4 };
  47370. const accessNames = {
  47371. [ NodeAccess.READ_ONLY ]: 'read',
  47372. [ NodeAccess.WRITE_ONLY ]: 'write',
  47373. [ NodeAccess.READ_WRITE ]: 'read_write'
  47374. };
  47375. const wrapNames = {
  47376. [ RepeatWrapping ]: 'repeat',
  47377. [ ClampToEdgeWrapping ]: 'clamp',
  47378. [ MirroredRepeatWrapping ]: 'mirror'
  47379. };
  47380. const gpuShaderStageLib = {
  47381. 'vertex': GPUShaderStage ? GPUShaderStage.VERTEX : 1,
  47382. 'fragment': GPUShaderStage ? GPUShaderStage.FRAGMENT : 2,
  47383. 'compute': GPUShaderStage ? GPUShaderStage.COMPUTE : 4
  47384. };
  47385. const supports = {
  47386. instance: true,
  47387. swizzleAssign: false,
  47388. storageBuffer: true
  47389. };
  47390. const wgslFnOpLib = {
  47391. '^^': 'tsl_xor'
  47392. };
  47393. const wgslTypeLib = {
  47394. float: 'f32',
  47395. int: 'i32',
  47396. uint: 'u32',
  47397. bool: 'bool',
  47398. color: 'vec3<f32>',
  47399. vec2: 'vec2<f32>',
  47400. ivec2: 'vec2<i32>',
  47401. uvec2: 'vec2<u32>',
  47402. bvec2: 'vec2<bool>',
  47403. vec3: 'vec3<f32>',
  47404. ivec3: 'vec3<i32>',
  47405. uvec3: 'vec3<u32>',
  47406. bvec3: 'vec3<bool>',
  47407. vec4: 'vec4<f32>',
  47408. ivec4: 'vec4<i32>',
  47409. uvec4: 'vec4<u32>',
  47410. bvec4: 'vec4<bool>',
  47411. mat2: 'mat2x2<f32>',
  47412. mat3: 'mat3x3<f32>',
  47413. mat4: 'mat4x4<f32>'
  47414. };
  47415. const wgslCodeCache = {};
  47416. const wgslPolyfill = {
  47417. tsl_xor: new CodeNode( 'fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }' ),
  47418. mod_float: new CodeNode( 'fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  47419. mod_vec2: new CodeNode( 'fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  47420. mod_vec3: new CodeNode( 'fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  47421. mod_vec4: new CodeNode( 'fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  47422. equals_bool: new CodeNode( 'fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  47423. 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 ); }' ),
  47424. 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 ); }' ),
  47425. 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 ); }' ),
  47426. repeatWrapping_float: new CodeNode( 'fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }' ),
  47427. 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 ); }' ),
  47428. clampWrapping_float: new CodeNode( 'fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }' ),
  47429. biquadraticTexture: new CodeNode( /* wgsl */`
  47430. fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {
  47431. let res = vec2f( iRes );
  47432. let uvScaled = coord * res;
  47433. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  47434. // https://www.shadertoy.com/view/WtyXRy
  47435. let uv = uvWrapping - 0.5;
  47436. let iuv = floor( uv );
  47437. let f = fract( uv );
  47438. let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );
  47439. let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );
  47440. let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );
  47441. let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );
  47442. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  47443. }
  47444. ` )
  47445. };
  47446. const wgslMethods = {
  47447. dFdx: 'dpdx',
  47448. dFdy: '- dpdy',
  47449. mod_float: 'tsl_mod_float',
  47450. mod_vec2: 'tsl_mod_vec2',
  47451. mod_vec3: 'tsl_mod_vec3',
  47452. mod_vec4: 'tsl_mod_vec4',
  47453. equals_bool: 'tsl_equals_bool',
  47454. equals_bvec2: 'tsl_equals_bvec2',
  47455. equals_bvec3: 'tsl_equals_bvec3',
  47456. equals_bvec4: 'tsl_equals_bvec4',
  47457. inversesqrt: 'inverseSqrt',
  47458. bitcast: 'bitcast<f32>'
  47459. };
  47460. // WebGPU issue: does not support pow() with negative base on Windows
  47461. if ( typeof navigator !== 'undefined' && /Windows/g.test( navigator.userAgent ) ) {
  47462. 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 ); }' );
  47463. 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 ] );
  47464. 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 ] );
  47465. 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 ] );
  47466. wgslMethods.pow_float = 'tsl_pow_float';
  47467. wgslMethods.pow_vec2 = 'tsl_pow_vec2';
  47468. wgslMethods.pow_vec3 = 'tsl_pow_vec3';
  47469. wgslMethods.pow_vec4 = 'tsl_pow_vec4';
  47470. }
  47471. //
  47472. let diagnostics = '';
  47473. if ( ( typeof navigator !== 'undefined' && /Firefox|Deno/g.test( navigator.userAgent ) ) !== true ) {
  47474. diagnostics += 'diagnostic( off, derivative_uniformity );\n';
  47475. }
  47476. /**
  47477. * A node builder targeting WGSL.
  47478. *
  47479. * This module generates WGSL shader code from node materials and also
  47480. * generates the respective bindings and vertex buffer definitions. These
  47481. * data are later used by the renderer to create render and compute pipelines
  47482. * for render objects.
  47483. *
  47484. * @augments NodeBuilder
  47485. */
  47486. class WGSLNodeBuilder extends NodeBuilder {
  47487. /**
  47488. * Constructs a new WGSL node builder renderer.
  47489. *
  47490. * @param {Object3D} object - The 3D object.
  47491. * @param {Renderer} renderer - The renderer.
  47492. */
  47493. constructor( object, renderer ) {
  47494. super( object, renderer, new WGSLNodeParser() );
  47495. /**
  47496. * A dictionary that holds for each shader stage ('vertex', 'fragment', 'compute')
  47497. * another dictionary which manages UBOs per group ('render','frame','object').
  47498. *
  47499. * @type {Object<string,Object<string,NodeUniformsGroup>>}
  47500. */
  47501. this.uniformGroups = {};
  47502. /**
  47503. * A dictionary that holds for each shader stage a Map of builtins.
  47504. *
  47505. * @type {Object<string,Map<string,Object>>}
  47506. */
  47507. this.builtins = {};
  47508. /**
  47509. * A dictionary that holds for each shader stage a Set of directives.
  47510. *
  47511. * @type {Object<string,Set<string>>}
  47512. */
  47513. this.directives = {};
  47514. /**
  47515. * A map for managing scope arrays. Only relevant for when using
  47516. * {@link WorkgroupInfoNode} in context of compute shaders.
  47517. *
  47518. * @type {Map<string,Object>}
  47519. */
  47520. this.scopedArrays = new Map();
  47521. }
  47522. /**
  47523. * Generates the WGSL snippet for sampled textures.
  47524. *
  47525. * @private
  47526. * @param {Texture} texture - The texture.
  47527. * @param {string} textureProperty - The name of the texture uniform in the shader.
  47528. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  47529. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  47530. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  47531. * @return {string} The WGSL snippet.
  47532. */
  47533. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  47534. if ( shaderStage === 'fragment' ) {
  47535. if ( depthSnippet ) {
  47536. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  47537. } else {
  47538. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  47539. }
  47540. } else {
  47541. return this.generateTextureSampleLevel( texture, textureProperty, uvSnippet, '0', depthSnippet );
  47542. }
  47543. }
  47544. /**
  47545. * Generates the WGSL snippet when sampling textures with explicit mip level.
  47546. *
  47547. * @private
  47548. * @param {Texture} texture - The texture.
  47549. * @param {string} textureProperty - The name of the texture uniform in the shader.
  47550. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  47551. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  47552. * @param {string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  47553. * @return {string} The WGSL snippet.
  47554. */
  47555. generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet ) {
  47556. if ( this.isUnfilterable( texture ) === false ) {
  47557. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  47558. } else if ( this.isFilteredTexture( texture ) ) {
  47559. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet );
  47560. } else {
  47561. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet );
  47562. }
  47563. }
  47564. /**
  47565. * Generates a wrap function used in context of textures.
  47566. *
  47567. * @param {Texture} texture - The texture to generate the function for.
  47568. * @return {string} The name of the generated function.
  47569. */
  47570. generateWrapFunction( texture ) {
  47571. const functionName = `tsl_coord_${ wrapNames[ texture.wrapS ] }S_${ wrapNames[ texture.wrapT ] }_${ texture.isData3DTexture ? '3d' : '2d' }T`;
  47572. let nodeCode = wgslCodeCache[ functionName ];
  47573. if ( nodeCode === undefined ) {
  47574. const includes = [];
  47575. // For 3D textures, use vec3f; for texture arrays, keep vec2f since array index is separate
  47576. const coordType = texture.isData3DTexture ? 'vec3f' : 'vec2f';
  47577. let code = `fn ${ functionName }( coord : ${ coordType } ) -> ${ coordType } {\n\n\treturn ${ coordType }(\n`;
  47578. const addWrapSnippet = ( wrap, axis ) => {
  47579. if ( wrap === RepeatWrapping ) {
  47580. includes.push( wgslPolyfill.repeatWrapping_float );
  47581. code += `\t\ttsl_repeatWrapping_float( coord.${ axis } )`;
  47582. } else if ( wrap === ClampToEdgeWrapping ) {
  47583. includes.push( wgslPolyfill.clampWrapping_float );
  47584. code += `\t\ttsl_clampWrapping_float( coord.${ axis } )`;
  47585. } else if ( wrap === MirroredRepeatWrapping ) {
  47586. includes.push( wgslPolyfill.mirrorWrapping_float );
  47587. code += `\t\ttsl_mirrorWrapping_float( coord.${ axis } )`;
  47588. } else {
  47589. code += `\t\tcoord.${ axis }`;
  47590. console.warn( `WebGPURenderer: Unsupported texture wrap type "${ wrap }" for vertex shader.` );
  47591. }
  47592. };
  47593. addWrapSnippet( texture.wrapS, 'x' );
  47594. code += ',\n';
  47595. addWrapSnippet( texture.wrapT, 'y' );
  47596. if ( texture.isData3DTexture ) {
  47597. code += ',\n';
  47598. addWrapSnippet( texture.wrapR, 'z' );
  47599. }
  47600. code += '\n\t);\n\n}\n';
  47601. wgslCodeCache[ functionName ] = nodeCode = new CodeNode( code, includes );
  47602. }
  47603. nodeCode.build( this );
  47604. return functionName;
  47605. }
  47606. /**
  47607. * Generates the array declaration string.
  47608. *
  47609. * @param {string} type - The type.
  47610. * @param {?number} [count] - The count.
  47611. * @return {string} The generated value as a shader string.
  47612. */
  47613. generateArrayDeclaration( type, count ) {
  47614. return `array< ${ this.getType( type ) }, ${ count } >`;
  47615. }
  47616. /**
  47617. * Generates a WGSL variable that holds the texture dimension of the given texture.
  47618. * It also returns information about the number of layers (elements) of an arrayed
  47619. * texture as well as the cube face count of cube textures.
  47620. *
  47621. * @param {Texture} texture - The texture to generate the function for.
  47622. * @param {string} textureProperty - The name of the video texture uniform in the shader.
  47623. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  47624. * @return {string} The name of the dimension variable.
  47625. */
  47626. generateTextureDimension( texture, textureProperty, levelSnippet ) {
  47627. const textureData = this.getDataFromNode( texture, this.shaderStage, this.globalCache );
  47628. if ( textureData.dimensionsSnippet === undefined ) textureData.dimensionsSnippet = {};
  47629. let textureDimensionNode = textureData.dimensionsSnippet[ levelSnippet ];
  47630. if ( textureData.dimensionsSnippet[ levelSnippet ] === undefined ) {
  47631. let textureDimensionsParams;
  47632. let dimensionType;
  47633. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  47634. const isMultisampled = primarySamples > 1;
  47635. if ( texture.isData3DTexture ) {
  47636. dimensionType = 'vec3<u32>';
  47637. } else {
  47638. // Regular 2D textures, depth textures, etc.
  47639. dimensionType = 'vec2<u32>';
  47640. }
  47641. // Build parameters string based on texture type and multisampling
  47642. if ( isMultisampled || texture.isStorageTexture ) {
  47643. textureDimensionsParams = textureProperty;
  47644. } else {
  47645. textureDimensionsParams = `${textureProperty}${levelSnippet ? `, u32( ${ levelSnippet } )` : ''}`;
  47646. }
  47647. textureDimensionNode = new VarNode( new ExpressionNode( `textureDimensions( ${ textureDimensionsParams } )`, dimensionType ) );
  47648. textureData.dimensionsSnippet[ levelSnippet ] = textureDimensionNode;
  47649. if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isData3DTexture ) {
  47650. textureData.arrayLayerCount = new VarNode(
  47651. new ExpressionNode(
  47652. `textureNumLayers(${textureProperty})`,
  47653. 'u32'
  47654. )
  47655. );
  47656. }
  47657. // For cube textures, we know it's always 6 faces
  47658. if ( texture.isTextureCube ) {
  47659. textureData.cubeFaceCount = new VarNode(
  47660. new ExpressionNode( '6u', 'u32' )
  47661. );
  47662. }
  47663. }
  47664. return textureDimensionNode.build( this );
  47665. }
  47666. /**
  47667. * Generates the WGSL snippet for a manual filtered texture.
  47668. *
  47669. * @param {Texture} texture - The texture.
  47670. * @param {string} textureProperty - The name of the texture uniform in the shader.
  47671. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  47672. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  47673. * @return {string} The WGSL snippet.
  47674. */
  47675. generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet = '0u' ) {
  47676. this._include( 'biquadraticTexture' );
  47677. const wrapFunction = this.generateWrapFunction( texture );
  47678. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  47679. return `tsl_biquadraticTexture( ${ textureProperty }, ${ wrapFunction }( ${ uvSnippet } ), ${ textureDimension }, u32( ${ levelSnippet } ) )`;
  47680. }
  47681. /**
  47682. * Generates the WGSL snippet for a texture lookup with explicit level-of-detail.
  47683. * Since it's a lookup, no sampling or filtering is applied.
  47684. *
  47685. * @param {Texture} texture - The texture.
  47686. * @param {string} textureProperty - The name of the texture uniform in the shader.
  47687. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  47688. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  47689. * @param {string} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  47690. * @return {string} The WGSL snippet.
  47691. */
  47692. generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet = '0u' ) {
  47693. const wrapFunction = this.generateWrapFunction( texture );
  47694. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  47695. const vecType = texture.isData3DTexture ? 'vec3' : 'vec2';
  47696. const coordSnippet = `${ vecType }<u32>( ${ wrapFunction }( ${ uvSnippet } ) * ${ vecType }<f32>( ${ textureDimension } ) )`;
  47697. return this.generateTextureLoad( texture, textureProperty, coordSnippet, depthSnippet, levelSnippet );
  47698. }
  47699. /**
  47700. * Generates the WGSL snippet that reads a single texel from a texture without sampling or filtering.
  47701. *
  47702. * @param {Texture} texture - The texture.
  47703. * @param {string} textureProperty - The name of the texture uniform in the shader.
  47704. * @param {string} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  47705. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  47706. * @param {string} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  47707. * @return {string} The WGSL snippet.
  47708. */
  47709. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0u' ) {
  47710. let snippet;
  47711. if ( depthSnippet ) {
  47712. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, u32( ${ levelSnippet } ) )`;
  47713. } else {
  47714. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, u32( ${ levelSnippet } ) )`;
  47715. if ( this.renderer.backend.compatibilityMode && texture.isDepthTexture ) {
  47716. snippet += '.x';
  47717. }
  47718. }
  47719. return snippet;
  47720. }
  47721. /**
  47722. * Generates the WGSL snippet that writes a single texel to a texture.
  47723. *
  47724. * @param {Texture} texture - The texture.
  47725. * @param {string} textureProperty - The name of the texture uniform in the shader.
  47726. * @param {string} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  47727. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  47728. * @param {string} valueSnippet - A WGSL snippet that represent the new texel value.
  47729. * @return {string} The WGSL snippet.
  47730. */
  47731. generateTextureStore( texture, textureProperty, uvIndexSnippet, depthSnippet, valueSnippet ) {
  47732. let snippet;
  47733. if ( depthSnippet ) {
  47734. snippet = `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, ${ valueSnippet } )`;
  47735. } else {
  47736. snippet = `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  47737. }
  47738. return snippet;
  47739. }
  47740. /**
  47741. * Returns `true` if the sampled values of the given texture should be compared against a reference value.
  47742. *
  47743. * @param {Texture} texture - The texture.
  47744. * @return {boolean} Whether the sampled values of the given texture should be compared against a reference value or not.
  47745. */
  47746. isSampleCompare( texture ) {
  47747. return texture.isDepthTexture === true && texture.compareFunction !== null;
  47748. }
  47749. /**
  47750. * Returns `true` if the given texture is unfilterable.
  47751. *
  47752. * @param {Texture} texture - The texture.
  47753. * @return {boolean} Whether the given texture is unfilterable or not.
  47754. */
  47755. isUnfilterable( texture ) {
  47756. return this.getComponentTypeFromTexture( texture ) !== 'float' ||
  47757. ( ! this.isAvailable( 'float32Filterable' ) && texture.isDataTexture === true && texture.type === FloatType ) ||
  47758. ( this.isSampleCompare( texture ) === false && texture.minFilter === NearestFilter && texture.magFilter === NearestFilter ) ||
  47759. this.renderer.backend.utils.getTextureSampleData( texture ).primarySamples > 1;
  47760. }
  47761. /**
  47762. * Generates the WGSL snippet for sampling/loading the given texture.
  47763. *
  47764. * @param {Texture} texture - The texture.
  47765. * @param {string} textureProperty - The name of the texture uniform in the shader.
  47766. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  47767. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  47768. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  47769. * @return {string} The WGSL snippet.
  47770. */
  47771. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  47772. let snippet = null;
  47773. if ( this.isUnfilterable( texture ) ) {
  47774. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, '0', shaderStage );
  47775. } else {
  47776. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage );
  47777. }
  47778. return snippet;
  47779. }
  47780. /**
  47781. * Generates the WGSL snippet for sampling/loading the given texture using explicit gradients.
  47782. *
  47783. * @param {Texture} texture - The texture.
  47784. * @param {string} textureProperty - The name of the texture uniform in the shader.
  47785. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  47786. * @param {Array<string>} gradSnippet - An array holding both gradient WGSL snippets.
  47787. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  47788. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  47789. * @return {string} The WGSL snippet.
  47790. */
  47791. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  47792. if ( shaderStage === 'fragment' ) {
  47793. // TODO handle i32 or u32 --> uvSnippet, array_index: A, ddx, ddy
  47794. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  47795. } else {
  47796. console.error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  47797. }
  47798. }
  47799. /**
  47800. * Generates the WGSL snippet for sampling a depth texture and comparing the sampled depth values
  47801. * against a reference value.
  47802. *
  47803. * @param {Texture} texture - The texture.
  47804. * @param {string} textureProperty - The name of the texture uniform in the shader.
  47805. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  47806. * @param {string} compareSnippet - A WGSL snippet that represents the reference value.
  47807. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  47808. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  47809. * @return {string} The WGSL snippet.
  47810. */
  47811. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  47812. if ( shaderStage === 'fragment' ) {
  47813. if ( texture.isDepthTexture === true && texture.isArrayTexture === true ) {
  47814. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } )`;
  47815. }
  47816. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  47817. } else {
  47818. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  47819. }
  47820. }
  47821. /**
  47822. * Generates the WGSL snippet when sampling textures with explicit mip level.
  47823. *
  47824. * @param {Texture} texture - The texture.
  47825. * @param {string} textureProperty - The name of the texture uniform in the shader.
  47826. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  47827. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  47828. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  47829. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  47830. * @return {string} The WGSL snippet.
  47831. */
  47832. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet ) {
  47833. if ( this.isUnfilterable( texture ) === false ) {
  47834. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  47835. } else if ( this.isFilteredTexture( texture ) ) {
  47836. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet );
  47837. } else {
  47838. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet );
  47839. }
  47840. }
  47841. /**
  47842. * Generates the WGSL snippet when sampling textures with a bias to the mip level.
  47843. *
  47844. * @param {Texture} texture - The texture.
  47845. * @param {string} textureProperty - The name of the texture uniform in the shader.
  47846. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  47847. * @param {string} biasSnippet - A WGSL snippet that represents the bias to apply to the mip level before sampling.
  47848. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  47849. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  47850. * @return {string} The WGSL snippet.
  47851. */
  47852. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  47853. if ( shaderStage === 'fragment' ) {
  47854. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  47855. } else {
  47856. console.error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  47857. }
  47858. }
  47859. /**
  47860. * Returns a WGSL snippet that represents the property name of the given node.
  47861. *
  47862. * @param {Node} node - The node.
  47863. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  47864. * @return {string} The property name.
  47865. */
  47866. getPropertyName( node, shaderStage = this.shaderStage ) {
  47867. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  47868. if ( shaderStage === 'vertex' ) {
  47869. return `varyings.${ node.name }`;
  47870. }
  47871. } else if ( node.isNodeUniform === true ) {
  47872. const name = node.name;
  47873. const type = node.type;
  47874. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  47875. return name;
  47876. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  47877. if ( this.isCustomStruct( node ) ) {
  47878. return name;
  47879. }
  47880. return name + '.value';
  47881. } else {
  47882. return node.groupNode.name + '.' + name;
  47883. }
  47884. }
  47885. return super.getPropertyName( node );
  47886. }
  47887. /**
  47888. * Returns the output struct name.
  47889. *
  47890. * @return {string} The name of the output struct.
  47891. */
  47892. getOutputStructName() {
  47893. return 'output';
  47894. }
  47895. /**
  47896. * Returns the native shader operator name for a given generic name.
  47897. *
  47898. * @param {string} op - The operator name to resolve.
  47899. * @return {?string} The resolved operator name.
  47900. */
  47901. getFunctionOperator( op ) {
  47902. const fnOp = wgslFnOpLib[ op ];
  47903. if ( fnOp !== undefined ) {
  47904. this._include( fnOp );
  47905. return fnOp;
  47906. }
  47907. return null;
  47908. }
  47909. /**
  47910. * Returns the node access for the given node and shader stage.
  47911. *
  47912. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  47913. * @param {string} shaderStage - The shader stage.
  47914. * @return {string} The node access.
  47915. */
  47916. getNodeAccess( node, shaderStage ) {
  47917. if ( shaderStage !== 'compute' )
  47918. return NodeAccess.READ_ONLY;
  47919. return node.access;
  47920. }
  47921. /**
  47922. * Returns A WGSL snippet representing the storage access.
  47923. *
  47924. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  47925. * @param {string} shaderStage - The shader stage.
  47926. * @return {string} The WGSL snippet representing the storage access.
  47927. */
  47928. getStorageAccess( node, shaderStage ) {
  47929. return accessNames[ this.getNodeAccess( node, shaderStage ) ];
  47930. }
  47931. /**
  47932. * This method is one of the more important ones since it's responsible
  47933. * for generating a matching binding instance for the given uniform node.
  47934. *
  47935. * These bindings are later used in the renderer to create bind groups
  47936. * and layouts.
  47937. *
  47938. * @param {UniformNode} node - The uniform node.
  47939. * @param {string} type - The node data type.
  47940. * @param {string} shaderStage - The shader stage.
  47941. * @param {?string} [name=null] - An optional uniform name.
  47942. * @return {NodeUniform} The node uniform object.
  47943. */
  47944. getUniformFromNode( node, type, shaderStage, name = null ) {
  47945. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  47946. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  47947. if ( nodeData.uniformGPU === undefined ) {
  47948. let uniformGPU;
  47949. const group = node.groupNode;
  47950. const groupName = group.name;
  47951. const bindings = this.getBindGroupArray( groupName, shaderStage );
  47952. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  47953. let texture = null;
  47954. const access = this.getNodeAccess( node, shaderStage );
  47955. if ( type === 'texture' || type === 'storageTexture' ) {
  47956. if ( node.value.is3DTexture === true ) {
  47957. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  47958. } else {
  47959. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, access );
  47960. }
  47961. } else if ( type === 'cubeTexture' ) {
  47962. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, access );
  47963. } else if ( type === 'texture3D' ) {
  47964. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  47965. }
  47966. texture.store = node.isStorageTextureNode === true;
  47967. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  47968. if ( this.isUnfilterable( node.value ) === false && texture.store === false ) {
  47969. const sampler = new NodeSampler( `${ uniformNode.name }_sampler`, uniformNode.node, group );
  47970. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  47971. bindings.push( sampler, texture );
  47972. uniformGPU = [ sampler, texture ];
  47973. } else {
  47974. bindings.push( texture );
  47975. uniformGPU = [ texture ];
  47976. }
  47977. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  47978. const bufferClass = type === 'buffer' ? NodeUniformBuffer : NodeStorageBuffer;
  47979. const buffer = new bufferClass( node, group );
  47980. buffer.setVisibility( gpuShaderStageLib[ shaderStage ] );
  47981. bindings.push( buffer );
  47982. uniformGPU = buffer;
  47983. uniformNode.name = name ? name : 'NodeBuffer_' + uniformNode.id;
  47984. } else {
  47985. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  47986. let uniformsGroup = uniformsStage[ groupName ];
  47987. if ( uniformsGroup === undefined ) {
  47988. uniformsGroup = new NodeUniformsGroup( groupName, group );
  47989. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  47990. uniformsStage[ groupName ] = uniformsGroup;
  47991. bindings.push( uniformsGroup );
  47992. }
  47993. uniformGPU = this.getNodeUniform( uniformNode, type );
  47994. uniformsGroup.addUniform( uniformGPU );
  47995. }
  47996. nodeData.uniformGPU = uniformGPU;
  47997. }
  47998. return uniformNode;
  47999. }
  48000. /**
  48001. * This method should be used whenever builtins are required in nodes.
  48002. * The internal builtins data structure will make sure builtins are
  48003. * defined in the WGSL source.
  48004. *
  48005. * @param {string} name - The builtin name.
  48006. * @param {string} property - The property name.
  48007. * @param {string} type - The node data type.
  48008. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  48009. * @return {string} The property name.
  48010. */
  48011. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  48012. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  48013. if ( map.has( name ) === false ) {
  48014. map.set( name, {
  48015. name,
  48016. property,
  48017. type
  48018. } );
  48019. }
  48020. return property;
  48021. }
  48022. /**
  48023. * Returns `true` if the given builtin is defined in the given shader stage.
  48024. *
  48025. * @param {string} name - The builtin name.
  48026. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  48027. * @return {boolean} Whether the given builtin is defined in the given shader stage or not.
  48028. */
  48029. hasBuiltin( name, shaderStage = this.shaderStage ) {
  48030. return ( this.builtins[ shaderStage ] !== undefined && this.builtins[ shaderStage ].has( name ) );
  48031. }
  48032. /**
  48033. * Returns the vertex index builtin.
  48034. *
  48035. * @return {string} The vertex index.
  48036. */
  48037. getVertexIndex() {
  48038. if ( this.shaderStage === 'vertex' ) {
  48039. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  48040. }
  48041. return 'vertexIndex';
  48042. }
  48043. /**
  48044. * Builds the given shader node.
  48045. *
  48046. * @param {ShaderNodeInternal} shaderNode - The shader node.
  48047. * @return {string} The WGSL function code.
  48048. */
  48049. buildFunctionCode( shaderNode ) {
  48050. const layout = shaderNode.layout;
  48051. const flowData = this.flowShaderNode( shaderNode );
  48052. const parameters = [];
  48053. for ( const input of layout.inputs ) {
  48054. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  48055. }
  48056. //
  48057. let code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  48058. ${ flowData.vars }
  48059. ${ flowData.code }
  48060. `;
  48061. if ( flowData.result ) {
  48062. code += `\treturn ${ flowData.result };\n`;
  48063. }
  48064. code += '\n}\n';
  48065. //
  48066. return code;
  48067. }
  48068. /**
  48069. * Returns the instance index builtin.
  48070. *
  48071. * @return {string} The instance index.
  48072. */
  48073. getInstanceIndex() {
  48074. if ( this.shaderStage === 'vertex' ) {
  48075. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  48076. }
  48077. return 'instanceIndex';
  48078. }
  48079. /**
  48080. * Returns the invocation local index builtin.
  48081. *
  48082. * @return {string} The invocation local index.
  48083. */
  48084. getInvocationLocalIndex() {
  48085. return this.getBuiltin( 'local_invocation_index', 'invocationLocalIndex', 'u32', 'attribute' );
  48086. }
  48087. /**
  48088. * Returns the subgroup size builtin.
  48089. *
  48090. * @return {string} The subgroup size.
  48091. */
  48092. getSubgroupSize() {
  48093. this.enableSubGroups();
  48094. return this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  48095. }
  48096. /**
  48097. * Returns the invocation subgroup index builtin.
  48098. *
  48099. * @return {string} The invocation subgroup index.
  48100. */
  48101. getInvocationSubgroupIndex() {
  48102. this.enableSubGroups();
  48103. return this.getBuiltin( 'subgroup_invocation_id', 'invocationSubgroupIndex', 'u32', 'attribute' );
  48104. }
  48105. /**
  48106. * Returns the subgroup index builtin.
  48107. *
  48108. * @return {string} The subgroup index.
  48109. */
  48110. getSubgroupIndex() {
  48111. this.enableSubGroups();
  48112. return this.getBuiltin( 'subgroup_id', 'subgroupIndex', 'u32', 'attribute' );
  48113. }
  48114. /**
  48115. * Overwritten as a NOP since this method is intended for the WebGL 2 backend.
  48116. *
  48117. * @return {null} Null.
  48118. */
  48119. getDrawIndex() {
  48120. return null;
  48121. }
  48122. /**
  48123. * Returns the front facing builtin.
  48124. *
  48125. * @return {string} The front facing builtin.
  48126. */
  48127. getFrontFacing() {
  48128. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  48129. }
  48130. /**
  48131. * Returns the frag coord builtin.
  48132. *
  48133. * @return {string} The frag coord builtin.
  48134. */
  48135. getFragCoord() {
  48136. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xy';
  48137. }
  48138. /**
  48139. * Returns the frag depth builtin.
  48140. *
  48141. * @return {string} The frag depth builtin.
  48142. */
  48143. getFragDepth() {
  48144. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  48145. }
  48146. /**
  48147. * Returns the clip distances builtin.
  48148. *
  48149. * @return {string} The clip distances builtin.
  48150. */
  48151. getClipDistance() {
  48152. return 'varyings.hw_clip_distances';
  48153. }
  48154. /**
  48155. * Whether to flip texture data along its vertical axis or not.
  48156. *
  48157. * @return {boolean} Returns always `false` in context of WGSL.
  48158. */
  48159. isFlipY() {
  48160. return false;
  48161. }
  48162. /**
  48163. * Enables the given directive for the given shader stage.
  48164. *
  48165. * @param {string} name - The directive name.
  48166. * @param {string} [shaderStage=this.shaderStage] - The shader stage to enable the directive for.
  48167. */
  48168. enableDirective( name, shaderStage = this.shaderStage ) {
  48169. const stage = this.directives[ shaderStage ] || ( this.directives[ shaderStage ] = new Set() );
  48170. stage.add( name );
  48171. }
  48172. /**
  48173. * Returns the directives of the given shader stage as a WGSL string.
  48174. *
  48175. * @param {string} shaderStage - The shader stage.
  48176. * @return {string} A WGSL snippet that enables the directives of the given stage.
  48177. */
  48178. getDirectives( shaderStage ) {
  48179. const snippets = [];
  48180. const directives = this.directives[ shaderStage ];
  48181. if ( directives !== undefined ) {
  48182. for ( const directive of directives ) {
  48183. snippets.push( `enable ${directive};` );
  48184. }
  48185. }
  48186. return snippets.join( '\n' );
  48187. }
  48188. /**
  48189. * Enables the 'subgroups' directive.
  48190. */
  48191. enableSubGroups() {
  48192. this.enableDirective( 'subgroups' );
  48193. }
  48194. /**
  48195. * Enables the 'subgroups-f16' directive.
  48196. */
  48197. enableSubgroupsF16() {
  48198. this.enableDirective( 'subgroups-f16' );
  48199. }
  48200. /**
  48201. * Enables the 'clip_distances' directive.
  48202. */
  48203. enableClipDistances() {
  48204. this.enableDirective( 'clip_distances' );
  48205. }
  48206. /**
  48207. * Enables the 'f16' directive.
  48208. */
  48209. enableShaderF16() {
  48210. this.enableDirective( 'f16' );
  48211. }
  48212. /**
  48213. * Enables the 'dual_source_blending' directive.
  48214. */
  48215. enableDualSourceBlending() {
  48216. this.enableDirective( 'dual_source_blending' );
  48217. }
  48218. /**
  48219. * Enables hardware clipping.
  48220. *
  48221. * @param {string} planeCount - The clipping plane count.
  48222. */
  48223. enableHardwareClipping( planeCount ) {
  48224. this.enableClipDistances();
  48225. this.getBuiltin( 'clip_distances', 'hw_clip_distances', `array<f32, ${ planeCount } >`, 'vertex' );
  48226. }
  48227. /**
  48228. * Returns the builtins of the given shader stage as a WGSL string.
  48229. *
  48230. * @param {string} shaderStage - The shader stage.
  48231. * @return {string} A WGSL snippet that represents the builtins of the given stage.
  48232. */
  48233. getBuiltins( shaderStage ) {
  48234. const snippets = [];
  48235. const builtins = this.builtins[ shaderStage ];
  48236. if ( builtins !== undefined ) {
  48237. for ( const { name, property, type } of builtins.values() ) {
  48238. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  48239. }
  48240. }
  48241. return snippets.join( ',\n\t' );
  48242. }
  48243. /**
  48244. * This method should be used when a new scoped buffer is used in context of
  48245. * compute shaders. It adds the array to the internal data structure which is
  48246. * later used to generate the respective WGSL.
  48247. *
  48248. * @param {string} name - The array name.
  48249. * @param {string} scope - The scope.
  48250. * @param {string} bufferType - The buffer type.
  48251. * @param {string} bufferCount - The buffer count.
  48252. * @return {string} The array name.
  48253. */
  48254. getScopedArray( name, scope, bufferType, bufferCount ) {
  48255. if ( this.scopedArrays.has( name ) === false ) {
  48256. this.scopedArrays.set( name, {
  48257. name,
  48258. scope,
  48259. bufferType,
  48260. bufferCount
  48261. } );
  48262. }
  48263. return name;
  48264. }
  48265. /**
  48266. * Returns the scoped arrays of the given shader stage as a WGSL string.
  48267. *
  48268. * @param {string} shaderStage - The shader stage.
  48269. * @return {string|undefined} The WGSL snippet that defines the scoped arrays.
  48270. * Returns `undefined` when used in the vertex or fragment stage.
  48271. */
  48272. getScopedArrays( shaderStage ) {
  48273. if ( shaderStage !== 'compute' ) {
  48274. return;
  48275. }
  48276. const snippets = [];
  48277. for ( const { name, scope, bufferType, bufferCount } of this.scopedArrays.values() ) {
  48278. const type = this.getType( bufferType );
  48279. snippets.push( `var<${scope}> ${name}: array< ${type}, ${bufferCount} >;` );
  48280. }
  48281. return snippets.join( '\n' );
  48282. }
  48283. /**
  48284. * Returns the shader attributes of the given shader stage as a WGSL string.
  48285. *
  48286. * @param {string} shaderStage - The shader stage.
  48287. * @return {string} The WGSL snippet that defines the shader attributes.
  48288. */
  48289. getAttributes( shaderStage ) {
  48290. const snippets = [];
  48291. if ( shaderStage === 'compute' ) {
  48292. this.getBuiltin( 'global_invocation_id', 'globalId', 'vec3<u32>', 'attribute' );
  48293. this.getBuiltin( 'workgroup_id', 'workgroupId', 'vec3<u32>', 'attribute' );
  48294. this.getBuiltin( 'local_invocation_id', 'localId', 'vec3<u32>', 'attribute' );
  48295. this.getBuiltin( 'num_workgroups', 'numWorkgroups', 'vec3<u32>', 'attribute' );
  48296. if ( this.renderer.hasFeature( 'subgroups' ) ) {
  48297. this.enableDirective( 'subgroups', shaderStage );
  48298. this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  48299. }
  48300. }
  48301. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  48302. const builtins = this.getBuiltins( 'attribute' );
  48303. if ( builtins ) snippets.push( builtins );
  48304. const attributes = this.getAttributesArray();
  48305. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  48306. const attribute = attributes[ index ];
  48307. const name = attribute.name;
  48308. const type = this.getType( attribute.type );
  48309. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  48310. }
  48311. }
  48312. return snippets.join( ',\n\t' );
  48313. }
  48314. /**
  48315. * Returns the members of the given struct type node as a WGSL string.
  48316. *
  48317. * @param {StructTypeNode} struct - The struct type node.
  48318. * @return {string} The WGSL snippet that defines the struct members.
  48319. */
  48320. getStructMembers( struct ) {
  48321. const snippets = [];
  48322. for ( const member of struct.members ) {
  48323. const prefix = struct.output ? '@location( ' + member.index + ' ) ' : '';
  48324. let type = this.getType( member.type );
  48325. if ( member.atomic ) {
  48326. type = 'atomic< ' + type + ' >';
  48327. }
  48328. snippets.push( `\t${ prefix + member.name } : ${ type }` );
  48329. }
  48330. if ( struct.output ) {
  48331. snippets.push( `\t${ this.getBuiltins( 'output' ) }` );
  48332. }
  48333. return snippets.join( ',\n' );
  48334. }
  48335. /**
  48336. * Returns the structs of the given shader stage as a WGSL string.
  48337. *
  48338. * @param {string} shaderStage - The shader stage.
  48339. * @return {string} The WGSL snippet that defines the structs.
  48340. */
  48341. getStructs( shaderStage ) {
  48342. let result = '';
  48343. const structs = this.structs[ shaderStage ];
  48344. if ( structs.length > 0 ) {
  48345. const snippets = [];
  48346. for ( const struct of structs ) {
  48347. let snippet = `struct ${ struct.name } {\n`;
  48348. snippet += this.getStructMembers( struct );
  48349. snippet += '\n};';
  48350. snippets.push( snippet );
  48351. }
  48352. result = '\n' + snippets.join( '\n\n' ) + '\n';
  48353. }
  48354. return result;
  48355. }
  48356. /**
  48357. * Returns a WGSL string representing a variable.
  48358. *
  48359. * @param {string} type - The variable's type.
  48360. * @param {string} name - The variable's name.
  48361. * @param {?number} [count=null] - The array length.
  48362. * @return {string} The WGSL snippet that defines a variable.
  48363. */
  48364. getVar( type, name, count = null ) {
  48365. let snippet = `var ${ name } : `;
  48366. if ( count !== null ) {
  48367. snippet += this.generateArrayDeclaration( type, count );
  48368. } else {
  48369. snippet += this.getType( type );
  48370. }
  48371. return snippet;
  48372. }
  48373. /**
  48374. * Returns the variables of the given shader stage as a WGSL string.
  48375. *
  48376. * @param {string} shaderStage - The shader stage.
  48377. * @return {string} The WGSL snippet that defines the variables.
  48378. */
  48379. getVars( shaderStage ) {
  48380. const snippets = [];
  48381. const vars = this.vars[ shaderStage ];
  48382. if ( vars !== undefined ) {
  48383. for ( const variable of vars ) {
  48384. snippets.push( `\t${ this.getVar( variable.type, variable.name, variable.count ) };` );
  48385. }
  48386. }
  48387. return `\n${ snippets.join( '\n' ) }\n`;
  48388. }
  48389. /**
  48390. * Returns the varyings of the given shader stage as a WGSL string.
  48391. *
  48392. * @param {string} shaderStage - The shader stage.
  48393. * @return {string} The WGSL snippet that defines the varyings.
  48394. */
  48395. getVaryings( shaderStage ) {
  48396. const snippets = [];
  48397. if ( shaderStage === 'vertex' ) {
  48398. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  48399. }
  48400. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  48401. const varyings = this.varyings;
  48402. const vars = this.vars[ shaderStage ];
  48403. for ( let index = 0; index < varyings.length; index ++ ) {
  48404. const varying = varyings[ index ];
  48405. if ( varying.needsInterpolation ) {
  48406. let attributesSnippet = `@location( ${index} )`;
  48407. if ( varying.interpolationType ) {
  48408. const samplingSnippet = varying.interpolationSampling !== null ? `, ${ varying.interpolationSampling } )` : ' )';
  48409. attributesSnippet += ` @interpolate( ${ varying.interpolationType }${ samplingSnippet }`;
  48410. // Otherwise, optimize interpolation when sensible
  48411. } else if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  48412. attributesSnippet += ` @interpolate( ${ this.renderer.backend.compatibilityMode ? 'flat, either' : 'flat' } )`;
  48413. }
  48414. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  48415. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  48416. vars.push( varying );
  48417. }
  48418. }
  48419. }
  48420. const builtins = this.getBuiltins( shaderStage );
  48421. if ( builtins ) snippets.push( builtins );
  48422. const code = snippets.join( ',\n\t' );
  48423. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  48424. }
  48425. isCustomStruct( nodeUniform ) {
  48426. const attribute = nodeUniform.value;
  48427. const bufferNode = nodeUniform.node;
  48428. const isAttributeStructType = ( attribute.isBufferAttribute || attribute.isInstancedBufferAttribute ) && bufferNode.structTypeNode !== null;
  48429. const isStructArray =
  48430. ( bufferNode.value && bufferNode.value.array ) &&
  48431. ( typeof bufferNode.value.itemSize === 'number' && bufferNode.value.array.length > bufferNode.value.itemSize );
  48432. return isAttributeStructType && ! isStructArray;
  48433. }
  48434. /**
  48435. * Returns the uniforms of the given shader stage as a WGSL string.
  48436. *
  48437. * @param {string} shaderStage - The shader stage.
  48438. * @return {string} The WGSL snippet that defines the uniforms.
  48439. */
  48440. getUniforms( shaderStage ) {
  48441. const uniforms = this.uniforms[ shaderStage ];
  48442. const bindingSnippets = [];
  48443. const bufferSnippets = [];
  48444. const structSnippets = [];
  48445. const uniformGroups = {};
  48446. for ( const uniform of uniforms ) {
  48447. const groupName = uniform.groupNode.name;
  48448. const uniformIndexes = this.bindingsIndexes[ groupName ];
  48449. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  48450. const texture = uniform.node.value;
  48451. if ( this.isUnfilterable( texture ) === false && uniform.node.isStorageTextureNode !== true ) {
  48452. if ( this.isSampleCompare( texture ) ) {
  48453. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  48454. } else {
  48455. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  48456. }
  48457. }
  48458. let textureType;
  48459. let multisampled = '';
  48460. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  48461. if ( primarySamples > 1 ) {
  48462. multisampled = '_multisampled';
  48463. }
  48464. if ( texture.isCubeTexture === true ) {
  48465. textureType = 'texture_cube<f32>';
  48466. } else if ( texture.isDepthTexture === true ) {
  48467. if ( this.renderer.backend.compatibilityMode && texture.compareFunction === null ) {
  48468. textureType = `texture${ multisampled }_2d<f32>`;
  48469. } else {
  48470. textureType = `texture_depth${ multisampled }_2d${ texture.isArrayTexture === true ? '_array' : '' }`;
  48471. }
  48472. } else if ( uniform.node.isStorageTextureNode === true ) {
  48473. const format = getFormat( texture );
  48474. const access = this.getStorageAccess( uniform.node, shaderStage );
  48475. const is3D = uniform.node.value.is3DTexture;
  48476. const isArrayTexture = uniform.node.value.isArrayTexture;
  48477. const dimension = is3D ? '3d' : `2d${ isArrayTexture ? '_array' : '' }`;
  48478. textureType = `texture_storage_${ dimension }<${ format }, ${ access }>`;
  48479. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  48480. textureType = 'texture_2d_array<f32>';
  48481. } else if ( texture.is3DTexture === true || texture.isData3DTexture === true ) {
  48482. textureType = 'texture_3d<f32>';
  48483. } else {
  48484. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  48485. textureType = `texture${ multisampled }_2d<${ componentPrefix }32>`;
  48486. }
  48487. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  48488. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' || uniform.type === 'indirectStorageBuffer' ) {
  48489. const bufferNode = uniform.node;
  48490. const bufferType = this.getType( bufferNode.getNodeType( this ) );
  48491. const bufferCount = bufferNode.bufferCount;
  48492. const bufferCountSnippet = bufferCount > 0 && uniform.type === 'buffer' ? ', ' + bufferCount : '';
  48493. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode, shaderStage ) }` : 'uniform';
  48494. if ( this.isCustomStruct( uniform ) ) {
  48495. bufferSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var<${ bufferAccessMode }> ${ uniform.name } : ${ bufferType };` );
  48496. } else {
  48497. const bufferTypeSnippet = bufferNode.isAtomic ? `atomic<${ bufferType }>` : `${ bufferType }`;
  48498. const bufferSnippet = `\tvalue : array< ${ bufferTypeSnippet }${ bufferCountSnippet } >`;
  48499. bufferSnippets.push( this._getWGSLStructBinding( uniform.name, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  48500. }
  48501. } else {
  48502. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  48503. const groupName = uniform.groupNode.name;
  48504. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  48505. index: uniformIndexes.binding ++,
  48506. id: uniformIndexes.group,
  48507. snippets: []
  48508. } );
  48509. group.snippets.push( `\t${ uniform.name } : ${ vectorType }` );
  48510. }
  48511. }
  48512. for ( const name in uniformGroups ) {
  48513. const group = uniformGroups[ name ];
  48514. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  48515. }
  48516. let code = bindingSnippets.join( '\n' );
  48517. code += bufferSnippets.join( '\n' );
  48518. code += structSnippets.join( '\n' );
  48519. return code;
  48520. }
  48521. /**
  48522. * Controls the code build of the shader stages.
  48523. */
  48524. buildCode() {
  48525. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  48526. this.sortBindingGroups();
  48527. for ( const shaderStage in shadersData ) {
  48528. this.shaderStage = shaderStage;
  48529. const stageData = shadersData[ shaderStage ];
  48530. stageData.uniforms = this.getUniforms( shaderStage );
  48531. stageData.attributes = this.getAttributes( shaderStage );
  48532. stageData.varyings = this.getVaryings( shaderStage );
  48533. stageData.structs = this.getStructs( shaderStage );
  48534. stageData.vars = this.getVars( shaderStage );
  48535. stageData.codes = this.getCodes( shaderStage );
  48536. stageData.directives = this.getDirectives( shaderStage );
  48537. stageData.scopedArrays = this.getScopedArrays( shaderStage );
  48538. //
  48539. let flow = '// code\n\n';
  48540. flow += this.flowCode[ shaderStage ];
  48541. const flowNodes = this.flowNodes[ shaderStage ];
  48542. const mainNode = flowNodes[ flowNodes.length - 1 ];
  48543. const outputNode = mainNode.outputNode;
  48544. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  48545. for ( const node of flowNodes ) {
  48546. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  48547. const slotName = node.name;
  48548. if ( slotName ) {
  48549. if ( flow.length > 0 ) flow += '\n';
  48550. flow += `\t// flow -> ${ slotName }\n`;
  48551. }
  48552. flow += `${ flowSlotData.code }\n\t`;
  48553. if ( node === mainNode && shaderStage !== 'compute' ) {
  48554. flow += '// result\n\n\t';
  48555. if ( shaderStage === 'vertex' ) {
  48556. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  48557. } else if ( shaderStage === 'fragment' ) {
  48558. if ( isOutputStruct ) {
  48559. stageData.returnType = outputNode.getNodeType( this );
  48560. stageData.structs += 'var<private> output : ' + stageData.returnType + ';';
  48561. flow += `return ${ flowSlotData.result };`;
  48562. } else {
  48563. let structSnippet = '\t@location(0) color: vec4<f32>';
  48564. const builtins = this.getBuiltins( 'output' );
  48565. if ( builtins ) structSnippet += ',\n\t' + builtins;
  48566. stageData.returnType = 'OutputStruct';
  48567. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  48568. stageData.structs += '\nvar<private> output : OutputStruct;';
  48569. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  48570. }
  48571. }
  48572. }
  48573. }
  48574. stageData.flow = flow;
  48575. }
  48576. this.shaderStage = null;
  48577. if ( this.material !== null ) {
  48578. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  48579. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  48580. } else {
  48581. // Early strictly validated in computeNode
  48582. const workgroupSize = this.object.workgroupSize;
  48583. this.computeShader = this._getWGSLComputeCode( shadersData.compute, workgroupSize );
  48584. }
  48585. }
  48586. /**
  48587. * Returns the native shader method name for a given generic name.
  48588. *
  48589. * @param {string} method - The method name to resolve.
  48590. * @param {?string} [output=null] - An optional output.
  48591. * @return {string} The resolved WGSL method name.
  48592. */
  48593. getMethod( method, output = null ) {
  48594. let wgslMethod;
  48595. if ( output !== null ) {
  48596. wgslMethod = this._getWGSLMethod( method + '_' + output );
  48597. }
  48598. if ( wgslMethod === undefined ) {
  48599. wgslMethod = this._getWGSLMethod( method );
  48600. }
  48601. return wgslMethod || method;
  48602. }
  48603. /**
  48604. * Returns the WGSL type of the given node data type.
  48605. *
  48606. * @param {string} type - The node data type.
  48607. * @return {string} The WGSL type.
  48608. */
  48609. getType( type ) {
  48610. return wgslTypeLib[ type ] || type;
  48611. }
  48612. /**
  48613. * Whether the requested feature is available or not.
  48614. *
  48615. * @param {string} name - The requested feature.
  48616. * @return {boolean} Whether the requested feature is supported or not.
  48617. */
  48618. isAvailable( name ) {
  48619. let result = supports[ name ];
  48620. if ( result === undefined ) {
  48621. if ( name === 'float32Filterable' ) {
  48622. result = this.renderer.hasFeature( 'float32-filterable' );
  48623. } else if ( name === 'clipDistance' ) {
  48624. result = this.renderer.hasFeature( 'clip-distances' );
  48625. }
  48626. supports[ name ] = result;
  48627. }
  48628. return result;
  48629. }
  48630. /**
  48631. * Returns the native shader method name for a given generic name.
  48632. *
  48633. * @private
  48634. * @param {string} method - The method name to resolve.
  48635. * @return {string} The resolved WGSL method name.
  48636. */
  48637. _getWGSLMethod( method ) {
  48638. if ( wgslPolyfill[ method ] !== undefined ) {
  48639. this._include( method );
  48640. }
  48641. return wgslMethods[ method ];
  48642. }
  48643. /**
  48644. * Includes the given method name into the current
  48645. * function node.
  48646. *
  48647. * @private
  48648. * @param {string} name - The method name to include.
  48649. * @return {CodeNode} The respective code node.
  48650. */
  48651. _include( name ) {
  48652. const codeNode = wgslPolyfill[ name ];
  48653. codeNode.build( this );
  48654. if ( this.currentFunctionNode !== null ) {
  48655. this.currentFunctionNode.includes.push( codeNode );
  48656. }
  48657. return codeNode;
  48658. }
  48659. /**
  48660. * Returns a WGSL vertex shader based on the given shader data.
  48661. *
  48662. * @private
  48663. * @param {Object} shaderData - The shader data.
  48664. * @return {string} The vertex shader.
  48665. */
  48666. _getWGSLVertexCode( shaderData ) {
  48667. return `${ this.getSignature() }
  48668. // directives
  48669. ${shaderData.directives}
  48670. // structs
  48671. ${shaderData.structs}
  48672. // uniforms
  48673. ${shaderData.uniforms}
  48674. // varyings
  48675. ${shaderData.varyings}
  48676. var<private> varyings : VaryingsStruct;
  48677. // codes
  48678. ${shaderData.codes}
  48679. @vertex
  48680. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  48681. // vars
  48682. ${shaderData.vars}
  48683. // flow
  48684. ${shaderData.flow}
  48685. return varyings;
  48686. }
  48687. `;
  48688. }
  48689. /**
  48690. * Returns a WGSL fragment shader based on the given shader data.
  48691. *
  48692. * @private
  48693. * @param {Object} shaderData - The shader data.
  48694. * @return {string} The vertex shader.
  48695. */
  48696. _getWGSLFragmentCode( shaderData ) {
  48697. return `${ this.getSignature() }
  48698. // global
  48699. ${ diagnostics }
  48700. // structs
  48701. ${shaderData.structs}
  48702. // uniforms
  48703. ${shaderData.uniforms}
  48704. // codes
  48705. ${shaderData.codes}
  48706. @fragment
  48707. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  48708. // vars
  48709. ${shaderData.vars}
  48710. // flow
  48711. ${shaderData.flow}
  48712. }
  48713. `;
  48714. }
  48715. /**
  48716. * Returns a WGSL compute shader based on the given shader data.
  48717. *
  48718. * @private
  48719. * @param {Object} shaderData - The shader data.
  48720. * @param {string} workgroupSize - The workgroup size.
  48721. * @return {string} The vertex shader.
  48722. */
  48723. _getWGSLComputeCode( shaderData, workgroupSize ) {
  48724. const [ workgroupSizeX, workgroupSizeY, workgroupSizeZ ] = workgroupSize;
  48725. return `${ this.getSignature() }
  48726. // directives
  48727. ${ shaderData.directives }
  48728. // system
  48729. var<private> instanceIndex : u32;
  48730. // locals
  48731. ${ shaderData.scopedArrays }
  48732. // structs
  48733. ${ shaderData.structs }
  48734. // uniforms
  48735. ${ shaderData.uniforms }
  48736. // codes
  48737. ${ shaderData.codes }
  48738. @compute @workgroup_size( ${ workgroupSizeX }, ${ workgroupSizeY }, ${ workgroupSizeZ } )
  48739. fn main( ${ shaderData.attributes } ) {
  48740. // system
  48741. instanceIndex = globalId.x
  48742. + globalId.y * ( ${ workgroupSizeX } * numWorkgroups.x )
  48743. + globalId.z * ( ${ workgroupSizeX } * numWorkgroups.x ) * ( ${ workgroupSizeY } * numWorkgroups.y );
  48744. // vars
  48745. ${ shaderData.vars }
  48746. // flow
  48747. ${ shaderData.flow }
  48748. }
  48749. `;
  48750. }
  48751. /**
  48752. * Returns a WGSL struct based on the given name and variables.
  48753. *
  48754. * @private
  48755. * @param {string} name - The struct name.
  48756. * @param {string} vars - The struct variables.
  48757. * @return {string} The WGSL snippet representing a struct.
  48758. */
  48759. _getWGSLStruct( name, vars ) {
  48760. return `
  48761. struct ${name} {
  48762. ${vars}
  48763. };`;
  48764. }
  48765. /**
  48766. * Returns a WGSL struct binding.
  48767. *
  48768. * @private
  48769. * @param {string} name - The struct name.
  48770. * @param {string} vars - The struct variables.
  48771. * @param {string} access - The access.
  48772. * @param {number} [binding=0] - The binding index.
  48773. * @param {number} [group=0] - The group index.
  48774. * @return {string} The WGSL snippet representing a struct binding.
  48775. */
  48776. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  48777. const structName = name + 'Struct';
  48778. const structSnippet = this._getWGSLStruct( structName, vars );
  48779. return `${structSnippet}
  48780. @binding( ${ binding } ) @group( ${ group } )
  48781. var<${access}> ${ name } : ${ structName };`;
  48782. }
  48783. }
  48784. /**
  48785. * A WebGPU backend utility module with common helpers.
  48786. *
  48787. * @private
  48788. */
  48789. class WebGPUUtils {
  48790. /**
  48791. * Constructs a new utility object.
  48792. *
  48793. * @param {WebGPUBackend} backend - The WebGPU backend.
  48794. */
  48795. constructor( backend ) {
  48796. /**
  48797. * A reference to the WebGPU backend.
  48798. *
  48799. * @type {WebGPUBackend}
  48800. */
  48801. this.backend = backend;
  48802. }
  48803. /**
  48804. * Returns the depth/stencil GPU format for the given render context.
  48805. *
  48806. * @param {RenderContext} renderContext - The render context.
  48807. * @return {string} The depth/stencil GPU texture format.
  48808. */
  48809. getCurrentDepthStencilFormat( renderContext ) {
  48810. let format;
  48811. if ( renderContext.depthTexture !== null ) {
  48812. format = this.getTextureFormatGPU( renderContext.depthTexture );
  48813. } else if ( renderContext.depth && renderContext.stencil ) {
  48814. format = GPUTextureFormat.Depth24PlusStencil8;
  48815. } else if ( renderContext.depth ) {
  48816. format = GPUTextureFormat.Depth24Plus;
  48817. }
  48818. return format;
  48819. }
  48820. /**
  48821. * Returns the GPU format for the given texture.
  48822. *
  48823. * @param {Texture} texture - The texture.
  48824. * @return {string} The GPU texture format.
  48825. */
  48826. getTextureFormatGPU( texture ) {
  48827. return this.backend.get( texture ).format;
  48828. }
  48829. /**
  48830. * Returns an object that defines the multi-sampling state of the given texture.
  48831. *
  48832. * @param {Texture} texture - The texture.
  48833. * @return {Object} The multi-sampling state.
  48834. */
  48835. getTextureSampleData( texture ) {
  48836. let samples;
  48837. if ( texture.isFramebufferTexture ) {
  48838. samples = 1;
  48839. } else if ( texture.isDepthTexture && ! texture.renderTarget ) {
  48840. const renderer = this.backend.renderer;
  48841. const renderTarget = renderer.getRenderTarget();
  48842. samples = renderTarget ? renderTarget.samples : renderer.samples;
  48843. } else if ( texture.renderTarget ) {
  48844. samples = texture.renderTarget.samples;
  48845. }
  48846. samples = samples || 1;
  48847. const isMSAA = samples > 1 && texture.renderTarget !== null && ( texture.isDepthTexture !== true && texture.isFramebufferTexture !== true );
  48848. const primarySamples = isMSAA ? 1 : samples;
  48849. return { samples, primarySamples, isMSAA };
  48850. }
  48851. /**
  48852. * Returns the default color attachment's GPU format of the current render context.
  48853. *
  48854. * @param {RenderContext} renderContext - The render context.
  48855. * @return {string} The GPU texture format of the default color attachment.
  48856. */
  48857. getCurrentColorFormat( renderContext ) {
  48858. let format;
  48859. if ( renderContext.textures !== null ) {
  48860. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  48861. } else {
  48862. format = this.getPreferredCanvasFormat(); // default context format
  48863. }
  48864. return format;
  48865. }
  48866. /**
  48867. * Returns the output color space of the current render context.
  48868. *
  48869. * @param {RenderContext} renderContext - The render context.
  48870. * @return {string} The output color space.
  48871. */
  48872. getCurrentColorSpace( renderContext ) {
  48873. if ( renderContext.textures !== null ) {
  48874. return renderContext.textures[ 0 ].colorSpace;
  48875. }
  48876. return this.backend.renderer.outputColorSpace;
  48877. }
  48878. /**
  48879. * Returns GPU primitive topology for the given object and material.
  48880. *
  48881. * @param {Object3D} object - The 3D object.
  48882. * @param {Material} material - The material.
  48883. * @return {string} The GPU primitive topology.
  48884. */
  48885. getPrimitiveTopology( object, material ) {
  48886. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  48887. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  48888. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  48889. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  48890. }
  48891. /**
  48892. * Returns a modified sample count from the given sample count value.
  48893. *
  48894. * That is required since WebGPU only supports either 1 or 4.
  48895. *
  48896. * @param {number} sampleCount - The input sample count.
  48897. * @return {number} The (potentially updated) output sample count.
  48898. */
  48899. getSampleCount( sampleCount ) {
  48900. return sampleCount >= 4 ? 4 : 1;
  48901. }
  48902. /**
  48903. * Returns the sample count of the given render context.
  48904. *
  48905. * @param {RenderContext} renderContext - The render context.
  48906. * @return {number} The sample count.
  48907. */
  48908. getSampleCountRenderContext( renderContext ) {
  48909. if ( renderContext.textures !== null ) {
  48910. return this.getSampleCount( renderContext.sampleCount );
  48911. }
  48912. return this.getSampleCount( this.backend.renderer.samples );
  48913. }
  48914. /**
  48915. * Returns the preferred canvas format.
  48916. *
  48917. * There is a separate method for this so it's possible to
  48918. * honor edge cases for specific devices.
  48919. *
  48920. * @return {string} The GPU texture format of the canvas.
  48921. */
  48922. getPreferredCanvasFormat() {
  48923. const outputType = this.backend.parameters.outputType;
  48924. if ( outputType === undefined ) {
  48925. return navigator.gpu.getPreferredCanvasFormat();
  48926. } else if ( outputType === UnsignedByteType ) {
  48927. return GPUTextureFormat.BGRA8Unorm;
  48928. } else if ( outputType === HalfFloatType ) {
  48929. return GPUTextureFormat.RGBA16Float;
  48930. } else {
  48931. throw new Error( 'Unsupported outputType' );
  48932. }
  48933. }
  48934. }
  48935. const typedArraysToVertexFormatPrefix = new Map( [
  48936. [ Int8Array, [ 'sint8', 'snorm8' ]],
  48937. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  48938. [ Int16Array, [ 'sint16', 'snorm16' ]],
  48939. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  48940. [ Int32Array, [ 'sint32', 'snorm32' ]],
  48941. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  48942. [ Float32Array, [ 'float32', ]],
  48943. ] );
  48944. if ( typeof Float16Array !== 'undefined' ) {
  48945. typedArraysToVertexFormatPrefix.set( Float16Array, [ 'float16' ] );
  48946. }
  48947. const typedAttributeToVertexFormatPrefix = new Map( [
  48948. [ Float16BufferAttribute, [ 'float16', ]],
  48949. ] );
  48950. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  48951. [ Int32Array, 'sint32' ],
  48952. [ Int16Array, 'sint32' ], // patch for INT16
  48953. [ Uint32Array, 'uint32' ],
  48954. [ Uint16Array, 'uint32' ], // patch for UINT16
  48955. [ Float32Array, 'float32' ]
  48956. ] );
  48957. /**
  48958. * A WebGPU backend utility module for managing shader attributes.
  48959. *
  48960. * @private
  48961. */
  48962. class WebGPUAttributeUtils {
  48963. /**
  48964. * Constructs a new utility object.
  48965. *
  48966. * @param {WebGPUBackend} backend - The WebGPU backend.
  48967. */
  48968. constructor( backend ) {
  48969. /**
  48970. * A reference to the WebGPU backend.
  48971. *
  48972. * @type {WebGPUBackend}
  48973. */
  48974. this.backend = backend;
  48975. }
  48976. /**
  48977. * Creates the GPU buffer for the given buffer attribute.
  48978. *
  48979. * @param {BufferAttribute} attribute - The buffer attribute.
  48980. * @param {GPUBufferUsage} usage - A flag that indicates how the buffer may be used after its creation.
  48981. */
  48982. createAttribute( attribute, usage ) {
  48983. const bufferAttribute = this._getBufferAttribute( attribute );
  48984. const backend = this.backend;
  48985. const bufferData = backend.get( bufferAttribute );
  48986. let buffer = bufferData.buffer;
  48987. if ( buffer === undefined ) {
  48988. const device = backend.device;
  48989. let array = bufferAttribute.array;
  48990. // patch for INT16 and UINT16
  48991. if ( attribute.normalized === false ) {
  48992. if ( array.constructor === Int16Array || array.constructor === Int8Array ) {
  48993. array = new Int32Array( array );
  48994. } else if ( array.constructor === Uint16Array || array.constructor === Uint8Array ) {
  48995. array = new Uint32Array( array );
  48996. if ( usage & GPUBufferUsage.INDEX ) {
  48997. for ( let i = 0; i < array.length; i ++ ) {
  48998. if ( array[ i ] === 0xffff ) array[ i ] = 0xffffffff; // use correct primitive restart index
  48999. }
  49000. }
  49001. }
  49002. }
  49003. bufferAttribute.array = array;
  49004. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  49005. array = new array.constructor( bufferAttribute.count * 4 );
  49006. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  49007. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  49008. }
  49009. // Update BufferAttribute
  49010. bufferAttribute.itemSize = 4;
  49011. bufferAttribute.array = array;
  49012. bufferData._force3to4BytesAlignment = true;
  49013. }
  49014. // ensure 4 byte alignment
  49015. const byteLength = array.byteLength;
  49016. const size = byteLength + ( ( 4 - ( byteLength % 4 ) ) % 4 );
  49017. buffer = device.createBuffer( {
  49018. label: bufferAttribute.name,
  49019. size: size,
  49020. usage: usage,
  49021. mappedAtCreation: true
  49022. } );
  49023. new array.constructor( buffer.getMappedRange() ).set( array );
  49024. buffer.unmap();
  49025. bufferData.buffer = buffer;
  49026. }
  49027. }
  49028. /**
  49029. * Updates the GPU buffer of the given buffer attribute.
  49030. *
  49031. * @param {BufferAttribute} attribute - The buffer attribute.
  49032. */
  49033. updateAttribute( attribute ) {
  49034. const bufferAttribute = this._getBufferAttribute( attribute );
  49035. const backend = this.backend;
  49036. const device = backend.device;
  49037. const bufferData = backend.get( bufferAttribute );
  49038. const buffer = backend.get( bufferAttribute ).buffer;
  49039. let array = bufferAttribute.array;
  49040. // if storage buffer ensure 4 byte alignment
  49041. if ( bufferData._force3to4BytesAlignment === true ) {
  49042. array = new array.constructor( bufferAttribute.count * 4 );
  49043. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  49044. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  49045. }
  49046. bufferAttribute.array = array;
  49047. }
  49048. const isTypedArray = this._isTypedArray( array );
  49049. const updateRanges = bufferAttribute.updateRanges;
  49050. if ( updateRanges.length === 0 ) {
  49051. // Not using update ranges
  49052. device.queue.writeBuffer(
  49053. buffer,
  49054. 0,
  49055. array,
  49056. 0
  49057. );
  49058. } else {
  49059. const byteOffsetFactor = isTypedArray ? 1 : array.BYTES_PER_ELEMENT;
  49060. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  49061. const range = updateRanges[ i ];
  49062. let dataOffset, size;
  49063. if ( bufferData._force3to4BytesAlignment === true ) {
  49064. const vertexStart = Math.floor( range.start / 3 );
  49065. const vertexCount = Math.ceil( range.count / 3 );
  49066. dataOffset = vertexStart * 4 * byteOffsetFactor;
  49067. size = vertexCount * 4 * byteOffsetFactor;
  49068. } else {
  49069. dataOffset = range.start * byteOffsetFactor;
  49070. size = range.count * byteOffsetFactor;
  49071. }
  49072. const bufferOffset = dataOffset * ( isTypedArray ? array.BYTES_PER_ELEMENT : 1 ); // bufferOffset is always in bytes
  49073. device.queue.writeBuffer(
  49074. buffer,
  49075. bufferOffset,
  49076. array,
  49077. dataOffset,
  49078. size
  49079. );
  49080. }
  49081. bufferAttribute.clearUpdateRanges();
  49082. }
  49083. }
  49084. /**
  49085. * This method creates the vertex buffer layout data which are
  49086. * require when creating a render pipeline for the given render object.
  49087. *
  49088. * @param {RenderObject} renderObject - The render object.
  49089. * @return {Array<Object>} An array holding objects which describe the vertex buffer layout.
  49090. */
  49091. createShaderVertexBuffers( renderObject ) {
  49092. const attributes = renderObject.getAttributes();
  49093. const vertexBuffers = new Map();
  49094. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  49095. const geometryAttribute = attributes[ slot ];
  49096. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  49097. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  49098. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  49099. if ( vertexBufferLayout === undefined ) {
  49100. let arrayStride, stepMode;
  49101. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  49102. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  49103. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  49104. } else {
  49105. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  49106. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  49107. }
  49108. // patch for INT16 and UINT16
  49109. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  49110. arrayStride = 4;
  49111. }
  49112. vertexBufferLayout = {
  49113. arrayStride,
  49114. attributes: [],
  49115. stepMode
  49116. };
  49117. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  49118. }
  49119. const format = this._getVertexFormat( geometryAttribute );
  49120. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  49121. vertexBufferLayout.attributes.push( {
  49122. shaderLocation: slot,
  49123. offset,
  49124. format
  49125. } );
  49126. }
  49127. return Array.from( vertexBuffers.values() );
  49128. }
  49129. /**
  49130. * Destroys the GPU buffer of the given buffer attribute.
  49131. *
  49132. * @param {BufferAttribute} attribute - The buffer attribute.
  49133. */
  49134. destroyAttribute( attribute ) {
  49135. const backend = this.backend;
  49136. const data = backend.get( this._getBufferAttribute( attribute ) );
  49137. data.buffer.destroy();
  49138. backend.delete( attribute );
  49139. }
  49140. /**
  49141. * This method performs a readback operation by moving buffer data from
  49142. * a storage buffer attribute from the GPU to the CPU.
  49143. *
  49144. * @async
  49145. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  49146. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  49147. */
  49148. async getArrayBufferAsync( attribute ) {
  49149. const backend = this.backend;
  49150. const device = backend.device;
  49151. const data = backend.get( this._getBufferAttribute( attribute ) );
  49152. const bufferGPU = data.buffer;
  49153. const size = bufferGPU.size;
  49154. const readBufferGPU = device.createBuffer( {
  49155. label: `${ attribute.name }_readback`,
  49156. size,
  49157. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  49158. } );
  49159. const cmdEncoder = device.createCommandEncoder( {
  49160. label: `readback_encoder_${ attribute.name }`
  49161. } );
  49162. cmdEncoder.copyBufferToBuffer(
  49163. bufferGPU,
  49164. 0,
  49165. readBufferGPU,
  49166. 0,
  49167. size
  49168. );
  49169. const gpuCommands = cmdEncoder.finish();
  49170. device.queue.submit( [ gpuCommands ] );
  49171. await readBufferGPU.mapAsync( GPUMapMode.READ );
  49172. const arrayBuffer = readBufferGPU.getMappedRange();
  49173. const dstBuffer = new attribute.array.constructor( arrayBuffer.slice( 0 ) );
  49174. readBufferGPU.unmap();
  49175. return dstBuffer.buffer;
  49176. }
  49177. /**
  49178. * Returns the vertex format of the given buffer attribute.
  49179. *
  49180. * @private
  49181. * @param {BufferAttribute} geometryAttribute - The buffer attribute.
  49182. * @return {string|undefined} The vertex format (e.g. 'float32x3').
  49183. */
  49184. _getVertexFormat( geometryAttribute ) {
  49185. const { itemSize, normalized } = geometryAttribute;
  49186. const ArrayType = geometryAttribute.array.constructor;
  49187. const AttributeType = geometryAttribute.constructor;
  49188. let format;
  49189. if ( itemSize === 1 ) {
  49190. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  49191. } else {
  49192. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  49193. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  49194. if ( prefix ) {
  49195. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  49196. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  49197. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  49198. if ( paddedItemSize % 1 ) {
  49199. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  49200. }
  49201. format = `${prefix}x${paddedItemSize}`;
  49202. }
  49203. }
  49204. if ( ! format ) {
  49205. console.error( 'THREE.WebGPUAttributeUtils: Vertex format not supported yet.' );
  49206. }
  49207. return format;
  49208. }
  49209. /**
  49210. * Returns `true` if the given array is a typed array.
  49211. *
  49212. * @private
  49213. * @param {any} array - The array.
  49214. * @return {boolean} Whether the given array is a typed array or not.
  49215. */
  49216. _isTypedArray( array ) {
  49217. return ArrayBuffer.isView( array ) && ! ( array instanceof DataView );
  49218. }
  49219. /**
  49220. * Utility method for handling interleaved buffer attributes correctly.
  49221. * To process them, their `InterleavedBuffer` is returned.
  49222. *
  49223. * @private
  49224. * @param {BufferAttribute} attribute - The attribute.
  49225. * @return {BufferAttribute|InterleavedBuffer}
  49226. */
  49227. _getBufferAttribute( attribute ) {
  49228. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  49229. return attribute;
  49230. }
  49231. }
  49232. /**
  49233. * A WebGPU backend utility module for managing bindings.
  49234. *
  49235. * When reading the documentation it's helpful to keep in mind that
  49236. * all class definitions starting with 'GPU*' are modules from the
  49237. * WebGPU API. So for example `BindGroup` is a class from the engine
  49238. * whereas `GPUBindGroup` is a class from WebGPU.
  49239. *
  49240. * @private
  49241. */
  49242. class WebGPUBindingUtils {
  49243. /**
  49244. * Constructs a new utility object.
  49245. *
  49246. * @param {WebGPUBackend} backend - The WebGPU backend.
  49247. */
  49248. constructor( backend ) {
  49249. /**
  49250. * A reference to the WebGPU backend.
  49251. *
  49252. * @type {WebGPUBackend}
  49253. */
  49254. this.backend = backend;
  49255. /**
  49256. * A cache for managing bind group layouts.
  49257. *
  49258. * @type {WeakMap<Array<Binding>,GPUBindGroupLayout>}
  49259. */
  49260. this.bindGroupLayoutCache = new WeakMap();
  49261. }
  49262. /**
  49263. * Creates a GPU bind group layout for the given bind group.
  49264. *
  49265. * @param {BindGroup} bindGroup - The bind group.
  49266. * @return {GPUBindGroupLayout} The GPU bind group layout.
  49267. */
  49268. createBindingsLayout( bindGroup ) {
  49269. const backend = this.backend;
  49270. const device = backend.device;
  49271. const entries = [];
  49272. let index = 0;
  49273. for ( const binding of bindGroup.bindings ) {
  49274. const bindingGPU = {
  49275. binding: index ++,
  49276. visibility: binding.visibility
  49277. };
  49278. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  49279. const buffer = {}; // GPUBufferBindingLayout
  49280. if ( binding.isStorageBuffer ) {
  49281. if ( binding.visibility & 4 ) {
  49282. // compute
  49283. if ( binding.access === NodeAccess.READ_WRITE || binding.access === NodeAccess.WRITE_ONLY ) {
  49284. buffer.type = GPUBufferBindingType.Storage;
  49285. } else {
  49286. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  49287. }
  49288. } else {
  49289. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  49290. }
  49291. }
  49292. bindingGPU.buffer = buffer;
  49293. } else if ( binding.isSampler ) {
  49294. const sampler = {}; // GPUSamplerBindingLayout
  49295. if ( binding.texture.isDepthTexture ) {
  49296. if ( binding.texture.compareFunction !== null ) {
  49297. sampler.type = GPUSamplerBindingType.Comparison;
  49298. } else if ( backend.compatibilityMode ) {
  49299. sampler.type = GPUSamplerBindingType.NonFiltering;
  49300. }
  49301. }
  49302. bindingGPU.sampler = sampler;
  49303. } else if ( binding.isSampledTexture && binding.store ) {
  49304. const storageTexture = {}; // GPUStorageTextureBindingLayout
  49305. storageTexture.format = this.backend.get( binding.texture ).texture.format;
  49306. const access = binding.access;
  49307. if ( access === NodeAccess.READ_WRITE ) {
  49308. storageTexture.access = GPUStorageTextureAccess.ReadWrite;
  49309. } else if ( access === NodeAccess.WRITE_ONLY ) {
  49310. storageTexture.access = GPUStorageTextureAccess.WriteOnly;
  49311. } else {
  49312. storageTexture.access = GPUStorageTextureAccess.ReadOnly;
  49313. }
  49314. if ( binding.texture.isArrayTexture ) {
  49315. storageTexture.viewDimension = GPUTextureViewDimension.TwoDArray;
  49316. } else if ( binding.texture.is3DTexture ) {
  49317. storageTexture.viewDimension = GPUTextureViewDimension.ThreeD;
  49318. }
  49319. bindingGPU.storageTexture = storageTexture;
  49320. } else if ( binding.isSampledTexture ) {
  49321. const texture = {}; // GPUTextureBindingLayout
  49322. const { primarySamples } = backend.utils.getTextureSampleData( binding.texture );
  49323. if ( primarySamples > 1 ) {
  49324. texture.multisampled = true;
  49325. if ( ! binding.texture.isDepthTexture ) {
  49326. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  49327. }
  49328. }
  49329. if ( binding.texture.isDepthTexture ) {
  49330. if ( backend.compatibilityMode && binding.texture.compareFunction === null ) {
  49331. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  49332. } else {
  49333. texture.sampleType = GPUTextureSampleType.Depth;
  49334. }
  49335. } else if ( binding.texture.isDataTexture || binding.texture.isDataArrayTexture || binding.texture.isData3DTexture ) {
  49336. const type = binding.texture.type;
  49337. if ( type === IntType ) {
  49338. texture.sampleType = GPUTextureSampleType.SInt;
  49339. } else if ( type === UnsignedIntType ) {
  49340. texture.sampleType = GPUTextureSampleType.UInt;
  49341. } else if ( type === FloatType ) {
  49342. if ( this.backend.hasFeature( 'float32-filterable' ) ) {
  49343. texture.sampleType = GPUTextureSampleType.Float;
  49344. } else {
  49345. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  49346. }
  49347. }
  49348. }
  49349. if ( binding.isSampledCubeTexture ) {
  49350. texture.viewDimension = GPUTextureViewDimension.Cube;
  49351. } else if ( binding.texture.isArrayTexture || binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  49352. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  49353. } else if ( binding.isSampledTexture3D ) {
  49354. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  49355. }
  49356. bindingGPU.texture = texture;
  49357. } else {
  49358. console.error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  49359. }
  49360. entries.push( bindingGPU );
  49361. }
  49362. return device.createBindGroupLayout( { entries } );
  49363. }
  49364. /**
  49365. * Creates bindings from the given bind group definition.
  49366. *
  49367. * @param {BindGroup} bindGroup - The bind group.
  49368. * @param {Array<BindGroup>} bindings - Array of bind groups.
  49369. * @param {number} cacheIndex - The cache index.
  49370. * @param {number} version - The version.
  49371. */
  49372. createBindings( bindGroup, bindings, cacheIndex, version = 0 ) {
  49373. const { backend, bindGroupLayoutCache } = this;
  49374. const bindingsData = backend.get( bindGroup );
  49375. // setup (static) binding layout and (dynamic) binding group
  49376. let bindLayoutGPU = bindGroupLayoutCache.get( bindGroup.bindingsReference );
  49377. if ( bindLayoutGPU === undefined ) {
  49378. bindLayoutGPU = this.createBindingsLayout( bindGroup );
  49379. bindGroupLayoutCache.set( bindGroup.bindingsReference, bindLayoutGPU );
  49380. }
  49381. let bindGroupGPU;
  49382. if ( cacheIndex > 0 ) {
  49383. if ( bindingsData.groups === undefined ) {
  49384. bindingsData.groups = [];
  49385. bindingsData.versions = [];
  49386. }
  49387. if ( bindingsData.versions[ cacheIndex ] === version ) {
  49388. bindGroupGPU = bindingsData.groups[ cacheIndex ];
  49389. }
  49390. }
  49391. if ( bindGroupGPU === undefined ) {
  49392. bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  49393. if ( cacheIndex > 0 ) {
  49394. bindingsData.groups[ cacheIndex ] = bindGroupGPU;
  49395. bindingsData.versions[ cacheIndex ] = version;
  49396. }
  49397. }
  49398. bindingsData.group = bindGroupGPU;
  49399. bindingsData.layout = bindLayoutGPU;
  49400. }
  49401. /**
  49402. * Updates a buffer binding.
  49403. *
  49404. * @param {Buffer} binding - The buffer binding to update.
  49405. */
  49406. updateBinding( binding ) {
  49407. const backend = this.backend;
  49408. const device = backend.device;
  49409. const buffer = binding.buffer;
  49410. const bufferGPU = backend.get( binding ).buffer;
  49411. device.queue.writeBuffer( bufferGPU, 0, buffer, 0 );
  49412. }
  49413. /**
  49414. * Creates a GPU bind group for the camera index.
  49415. *
  49416. * @param {Uint32Array} data - The index data.
  49417. * @param {GPUBindGroupLayout} layout - The GPU bind group layout.
  49418. * @return {GPUBindGroup} The GPU bind group.
  49419. */
  49420. createBindGroupIndex( data, layout ) {
  49421. const backend = this.backend;
  49422. const device = backend.device;
  49423. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  49424. const index = data[ 0 ];
  49425. const buffer = device.createBuffer( {
  49426. label: 'bindingCameraIndex_' + index,
  49427. size: 16, // uint(4) * 4
  49428. usage: usage
  49429. } );
  49430. device.queue.writeBuffer( buffer, 0, data, 0 );
  49431. const entries = [ { binding: 0, resource: { buffer } } ];
  49432. return device.createBindGroup( {
  49433. label: 'bindGroupCameraIndex_' + index,
  49434. layout,
  49435. entries
  49436. } );
  49437. }
  49438. /**
  49439. * Creates a GPU bind group for the given bind group and GPU layout.
  49440. *
  49441. * @param {BindGroup} bindGroup - The bind group.
  49442. * @param {GPUBindGroupLayout} layoutGPU - The GPU bind group layout.
  49443. * @return {GPUBindGroup} The GPU bind group.
  49444. */
  49445. createBindGroup( bindGroup, layoutGPU ) {
  49446. const backend = this.backend;
  49447. const device = backend.device;
  49448. let bindingPoint = 0;
  49449. const entriesGPU = [];
  49450. for ( const binding of bindGroup.bindings ) {
  49451. if ( binding.isUniformBuffer ) {
  49452. const bindingData = backend.get( binding );
  49453. if ( bindingData.buffer === undefined ) {
  49454. const byteLength = binding.byteLength;
  49455. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  49456. const bufferGPU = device.createBuffer( {
  49457. label: 'bindingBuffer_' + binding.name,
  49458. size: byteLength,
  49459. usage: usage
  49460. } );
  49461. bindingData.buffer = bufferGPU;
  49462. }
  49463. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  49464. } else if ( binding.isStorageBuffer ) {
  49465. const bindingData = backend.get( binding );
  49466. if ( bindingData.buffer === undefined ) {
  49467. const attribute = binding.attribute;
  49468. //const usage = GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | /*GPUBufferUsage.COPY_SRC |*/ GPUBufferUsage.COPY_DST;
  49469. //backend.attributeUtils.createAttribute( attribute, usage ); // @TODO: Move it to universal renderer
  49470. bindingData.buffer = backend.get( attribute ).buffer;
  49471. }
  49472. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  49473. } else if ( binding.isSampler ) {
  49474. const textureGPU = backend.get( binding.texture );
  49475. entriesGPU.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  49476. } else if ( binding.isSampledTexture ) {
  49477. const textureData = backend.get( binding.texture );
  49478. let resourceGPU;
  49479. if ( textureData.externalTexture !== undefined ) {
  49480. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  49481. } else {
  49482. const mipLevelCount = binding.store ? 1 : textureData.texture.mipLevelCount;
  49483. let propertyName = `view-${ textureData.texture.width }-${ textureData.texture.height }`;
  49484. if ( textureData.texture.depthOrArrayLayers > 1 ) {
  49485. propertyName += `-${ textureData.texture.depthOrArrayLayers }`;
  49486. }
  49487. propertyName += `-${ mipLevelCount }`;
  49488. resourceGPU = textureData[ propertyName ];
  49489. if ( resourceGPU === undefined ) {
  49490. const aspectGPU = GPUTextureAspect.All;
  49491. let dimensionViewGPU;
  49492. if ( binding.isSampledCubeTexture ) {
  49493. dimensionViewGPU = GPUTextureViewDimension.Cube;
  49494. } else if ( binding.isSampledTexture3D ) {
  49495. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  49496. } else if ( binding.texture.isArrayTexture || binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  49497. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  49498. } else {
  49499. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  49500. }
  49501. resourceGPU = textureData[ propertyName ] = textureData.texture.createView( { aspect: aspectGPU, dimension: dimensionViewGPU, mipLevelCount } );
  49502. }
  49503. }
  49504. entriesGPU.push( { binding: bindingPoint, resource: resourceGPU } );
  49505. }
  49506. bindingPoint ++;
  49507. }
  49508. return device.createBindGroup( {
  49509. label: 'bindGroup_' + bindGroup.name,
  49510. layout: layoutGPU,
  49511. entries: entriesGPU
  49512. } );
  49513. }
  49514. }
  49515. /**
  49516. * A WebGPU backend utility module for managing pipelines.
  49517. *
  49518. * @private
  49519. */
  49520. class WebGPUPipelineUtils {
  49521. /**
  49522. * Constructs a new utility object.
  49523. *
  49524. * @param {WebGPUBackend} backend - The WebGPU backend.
  49525. */
  49526. constructor( backend ) {
  49527. /**
  49528. * A reference to the WebGPU backend.
  49529. *
  49530. * @type {WebGPUBackend}
  49531. */
  49532. this.backend = backend;
  49533. /**
  49534. * A Weak Map that tracks the active pipeline for render or compute passes.
  49535. *
  49536. * @private
  49537. * @type {WeakMap<(GPURenderPassEncoder|GPUComputePassEncoder),(GPURenderPipeline|GPUComputePipeline)>}
  49538. */
  49539. this._activePipelines = new WeakMap();
  49540. }
  49541. /**
  49542. * Sets the given pipeline for the given pass. The method makes sure to only set the
  49543. * pipeline when necessary.
  49544. *
  49545. * @param {(GPURenderPassEncoder|GPUComputePassEncoder)} pass - The pass encoder.
  49546. * @param {(GPURenderPipeline|GPUComputePipeline)} pipeline - The pipeline.
  49547. */
  49548. setPipeline( pass, pipeline ) {
  49549. const currentPipeline = this._activePipelines.get( pass );
  49550. if ( currentPipeline !== pipeline ) {
  49551. pass.setPipeline( pipeline );
  49552. this._activePipelines.set( pass, pipeline );
  49553. }
  49554. }
  49555. /**
  49556. * Returns the sample count derived from the given render context.
  49557. *
  49558. * @private
  49559. * @param {RenderContext} renderContext - The render context.
  49560. * @return {number} The sample count.
  49561. */
  49562. _getSampleCount( renderContext ) {
  49563. return this.backend.utils.getSampleCountRenderContext( renderContext );
  49564. }
  49565. /**
  49566. * Creates a render pipeline for the given render object.
  49567. *
  49568. * @param {RenderObject} renderObject - The render object.
  49569. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  49570. */
  49571. createRenderPipeline( renderObject, promises ) {
  49572. const { object, material, geometry, pipeline } = renderObject;
  49573. const { vertexProgram, fragmentProgram } = pipeline;
  49574. const backend = this.backend;
  49575. const device = backend.device;
  49576. const utils = backend.utils;
  49577. const pipelineData = backend.get( pipeline );
  49578. // bind group layouts
  49579. const bindGroupLayouts = [];
  49580. for ( const bindGroup of renderObject.getBindings() ) {
  49581. const bindingsData = backend.get( bindGroup );
  49582. bindGroupLayouts.push( bindingsData.layout );
  49583. }
  49584. // vertex buffers
  49585. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  49586. // blending
  49587. let blending;
  49588. if ( material.blending !== NoBlending && ( material.blending !== NormalBlending || material.transparent !== false ) ) {
  49589. blending = this._getBlending( material );
  49590. }
  49591. // stencil
  49592. let stencilFront = {};
  49593. if ( material.stencilWrite === true ) {
  49594. stencilFront = {
  49595. compare: this._getStencilCompare( material ),
  49596. failOp: this._getStencilOperation( material.stencilFail ),
  49597. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  49598. passOp: this._getStencilOperation( material.stencilZPass )
  49599. };
  49600. }
  49601. const colorWriteMask = this._getColorWriteMask( material );
  49602. const targets = [];
  49603. if ( renderObject.context.textures !== null ) {
  49604. const textures = renderObject.context.textures;
  49605. for ( let i = 0; i < textures.length; i ++ ) {
  49606. const colorFormat = utils.getTextureFormatGPU( textures[ i ] );
  49607. targets.push( {
  49608. format: colorFormat,
  49609. blend: blending,
  49610. writeMask: colorWriteMask
  49611. } );
  49612. }
  49613. } else {
  49614. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  49615. targets.push( {
  49616. format: colorFormat,
  49617. blend: blending,
  49618. writeMask: colorWriteMask
  49619. } );
  49620. }
  49621. const vertexModule = backend.get( vertexProgram ).module;
  49622. const fragmentModule = backend.get( fragmentProgram ).module;
  49623. const primitiveState = this._getPrimitiveState( object, geometry, material );
  49624. const depthCompare = this._getDepthCompare( material );
  49625. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  49626. const sampleCount = this._getSampleCount( renderObject.context );
  49627. const pipelineDescriptor = {
  49628. label: `renderPipeline_${ material.name || material.type }_${ material.id }`,
  49629. vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ),
  49630. fragment: Object.assign( {}, fragmentModule, { targets } ),
  49631. primitive: primitiveState,
  49632. multisample: {
  49633. count: sampleCount,
  49634. alphaToCoverageEnabled: material.alphaToCoverage && sampleCount > 1
  49635. },
  49636. layout: device.createPipelineLayout( {
  49637. bindGroupLayouts
  49638. } )
  49639. };
  49640. const depthStencil = {};
  49641. const renderDepth = renderObject.context.depth;
  49642. const renderStencil = renderObject.context.stencil;
  49643. if ( renderDepth === true || renderStencil === true ) {
  49644. if ( renderDepth === true ) {
  49645. depthStencil.format = depthStencilFormat;
  49646. depthStencil.depthWriteEnabled = material.depthWrite;
  49647. depthStencil.depthCompare = depthCompare;
  49648. }
  49649. if ( renderStencil === true ) {
  49650. depthStencil.stencilFront = stencilFront;
  49651. depthStencil.stencilBack = {}; // three.js does not provide an API to configure the back function (gl.stencilFuncSeparate() was never used)
  49652. depthStencil.stencilReadMask = material.stencilFuncMask;
  49653. depthStencil.stencilWriteMask = material.stencilWriteMask;
  49654. }
  49655. if ( material.polygonOffset === true ) {
  49656. depthStencil.depthBias = material.polygonOffsetUnits;
  49657. depthStencil.depthBiasSlopeScale = material.polygonOffsetFactor;
  49658. depthStencil.depthBiasClamp = 0; // three.js does not provide an API to configure this value
  49659. }
  49660. pipelineDescriptor.depthStencil = depthStencil;
  49661. }
  49662. if ( promises === null ) {
  49663. pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor );
  49664. } else {
  49665. const p = new Promise( ( resolve /*, reject*/ ) => {
  49666. device.createRenderPipelineAsync( pipelineDescriptor ).then( pipeline => {
  49667. pipelineData.pipeline = pipeline;
  49668. resolve();
  49669. } );
  49670. } );
  49671. promises.push( p );
  49672. }
  49673. }
  49674. /**
  49675. * Creates GPU render bundle encoder for the given render context.
  49676. *
  49677. * @param {RenderContext} renderContext - The render context.
  49678. * @param {?string} [label='renderBundleEncoder'] - The label.
  49679. * @return {GPURenderBundleEncoder} The GPU render bundle encoder.
  49680. */
  49681. createBundleEncoder( renderContext, label = 'renderBundleEncoder' ) {
  49682. const backend = this.backend;
  49683. const { utils, device } = backend;
  49684. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  49685. const colorFormat = utils.getCurrentColorFormat( renderContext );
  49686. const sampleCount = this._getSampleCount( renderContext );
  49687. const descriptor = {
  49688. label: label,
  49689. colorFormats: [ colorFormat ],
  49690. depthStencilFormat,
  49691. sampleCount
  49692. };
  49693. return device.createRenderBundleEncoder( descriptor );
  49694. }
  49695. /**
  49696. * Creates a compute pipeline for the given compute node.
  49697. *
  49698. * @param {ComputePipeline} pipeline - The compute pipeline.
  49699. * @param {Array<BindGroup>} bindings - The bindings.
  49700. */
  49701. createComputePipeline( pipeline, bindings ) {
  49702. const backend = this.backend;
  49703. const device = backend.device;
  49704. const computeProgram = backend.get( pipeline.computeProgram ).module;
  49705. const pipelineGPU = backend.get( pipeline );
  49706. // bind group layouts
  49707. const bindGroupLayouts = [];
  49708. for ( const bindingsGroup of bindings ) {
  49709. const bindingsData = backend.get( bindingsGroup );
  49710. bindGroupLayouts.push( bindingsData.layout );
  49711. }
  49712. pipelineGPU.pipeline = device.createComputePipeline( {
  49713. compute: computeProgram,
  49714. layout: device.createPipelineLayout( {
  49715. bindGroupLayouts
  49716. } )
  49717. } );
  49718. }
  49719. /**
  49720. * Returns the blending state as a descriptor object required
  49721. * for the pipeline creation.
  49722. *
  49723. * @private
  49724. * @param {Material} material - The material.
  49725. * @return {Object} The blending state.
  49726. */
  49727. _getBlending( material ) {
  49728. let color, alpha;
  49729. const blending = material.blending;
  49730. const blendSrc = material.blendSrc;
  49731. const blendDst = material.blendDst;
  49732. const blendEquation = material.blendEquation;
  49733. if ( blending === CustomBlending ) {
  49734. const blendSrcAlpha = material.blendSrcAlpha !== null ? material.blendSrcAlpha : blendSrc;
  49735. const blendDstAlpha = material.blendDstAlpha !== null ? material.blendDstAlpha : blendDst;
  49736. const blendEquationAlpha = material.blendEquationAlpha !== null ? material.blendEquationAlpha : blendEquation;
  49737. color = {
  49738. srcFactor: this._getBlendFactor( blendSrc ),
  49739. dstFactor: this._getBlendFactor( blendDst ),
  49740. operation: this._getBlendOperation( blendEquation )
  49741. };
  49742. alpha = {
  49743. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  49744. dstFactor: this._getBlendFactor( blendDstAlpha ),
  49745. operation: this._getBlendOperation( blendEquationAlpha )
  49746. };
  49747. } else {
  49748. const premultipliedAlpha = material.premultipliedAlpha;
  49749. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  49750. color = {
  49751. srcFactor: srcRGB,
  49752. dstFactor: dstRGB,
  49753. operation: GPUBlendOperation.Add
  49754. };
  49755. alpha = {
  49756. srcFactor: srcAlpha,
  49757. dstFactor: dstAlpha,
  49758. operation: GPUBlendOperation.Add
  49759. };
  49760. };
  49761. if ( premultipliedAlpha ) {
  49762. switch ( blending ) {
  49763. case NormalBlending:
  49764. setBlend( GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  49765. break;
  49766. case AdditiveBlending:
  49767. setBlend( GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  49768. break;
  49769. case SubtractiveBlending:
  49770. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  49771. break;
  49772. case MultiplyBlending:
  49773. setBlend( GPUBlendFactor.Dst, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.Zero, GPUBlendFactor.One );
  49774. break;
  49775. }
  49776. } else {
  49777. switch ( blending ) {
  49778. case NormalBlending:
  49779. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  49780. break;
  49781. case AdditiveBlending:
  49782. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  49783. break;
  49784. case SubtractiveBlending:
  49785. console.error( 'THREE.WebGPURenderer: SubtractiveBlending requires material.premultipliedAlpha = true' );
  49786. break;
  49787. case MultiplyBlending:
  49788. console.error( 'THREE.WebGPURenderer: MultiplyBlending requires material.premultipliedAlpha = true' );
  49789. break;
  49790. }
  49791. }
  49792. }
  49793. if ( color !== undefined && alpha !== undefined ) {
  49794. return { color, alpha };
  49795. } else {
  49796. console.error( 'THREE.WebGPURenderer: Invalid blending: ', blending );
  49797. }
  49798. }
  49799. /**
  49800. * Returns the GPU blend factor which is required for the pipeline creation.
  49801. *
  49802. * @private
  49803. * @param {number} blend - The blend factor as a three.js constant.
  49804. * @return {string} The GPU blend factor.
  49805. */
  49806. _getBlendFactor( blend ) {
  49807. let blendFactor;
  49808. switch ( blend ) {
  49809. case ZeroFactor:
  49810. blendFactor = GPUBlendFactor.Zero;
  49811. break;
  49812. case OneFactor:
  49813. blendFactor = GPUBlendFactor.One;
  49814. break;
  49815. case SrcColorFactor:
  49816. blendFactor = GPUBlendFactor.Src;
  49817. break;
  49818. case OneMinusSrcColorFactor:
  49819. blendFactor = GPUBlendFactor.OneMinusSrc;
  49820. break;
  49821. case SrcAlphaFactor:
  49822. blendFactor = GPUBlendFactor.SrcAlpha;
  49823. break;
  49824. case OneMinusSrcAlphaFactor:
  49825. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  49826. break;
  49827. case DstColorFactor:
  49828. blendFactor = GPUBlendFactor.Dst;
  49829. break;
  49830. case OneMinusDstColorFactor:
  49831. blendFactor = GPUBlendFactor.OneMinusDst;
  49832. break;
  49833. case DstAlphaFactor:
  49834. blendFactor = GPUBlendFactor.DstAlpha;
  49835. break;
  49836. case OneMinusDstAlphaFactor:
  49837. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  49838. break;
  49839. case SrcAlphaSaturateFactor:
  49840. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  49841. break;
  49842. case BlendColorFactor:
  49843. blendFactor = GPUBlendFactor.Constant;
  49844. break;
  49845. case OneMinusBlendColorFactor:
  49846. blendFactor = GPUBlendFactor.OneMinusConstant;
  49847. break;
  49848. default:
  49849. console.error( 'THREE.WebGPURenderer: Blend factor not supported.', blend );
  49850. }
  49851. return blendFactor;
  49852. }
  49853. /**
  49854. * Returns the GPU stencil compare function which is required for the pipeline creation.
  49855. *
  49856. * @private
  49857. * @param {Material} material - The material.
  49858. * @return {string} The GPU stencil compare function.
  49859. */
  49860. _getStencilCompare( material ) {
  49861. let stencilCompare;
  49862. const stencilFunc = material.stencilFunc;
  49863. switch ( stencilFunc ) {
  49864. case NeverStencilFunc:
  49865. stencilCompare = GPUCompareFunction.Never;
  49866. break;
  49867. case AlwaysStencilFunc:
  49868. stencilCompare = GPUCompareFunction.Always;
  49869. break;
  49870. case LessStencilFunc:
  49871. stencilCompare = GPUCompareFunction.Less;
  49872. break;
  49873. case LessEqualStencilFunc:
  49874. stencilCompare = GPUCompareFunction.LessEqual;
  49875. break;
  49876. case EqualStencilFunc:
  49877. stencilCompare = GPUCompareFunction.Equal;
  49878. break;
  49879. case GreaterEqualStencilFunc:
  49880. stencilCompare = GPUCompareFunction.GreaterEqual;
  49881. break;
  49882. case GreaterStencilFunc:
  49883. stencilCompare = GPUCompareFunction.Greater;
  49884. break;
  49885. case NotEqualStencilFunc:
  49886. stencilCompare = GPUCompareFunction.NotEqual;
  49887. break;
  49888. default:
  49889. console.error( 'THREE.WebGPURenderer: Invalid stencil function.', stencilFunc );
  49890. }
  49891. return stencilCompare;
  49892. }
  49893. /**
  49894. * Returns the GPU stencil operation which is required for the pipeline creation.
  49895. *
  49896. * @private
  49897. * @param {number} op - A three.js constant defining the stencil operation.
  49898. * @return {string} The GPU stencil operation.
  49899. */
  49900. _getStencilOperation( op ) {
  49901. let stencilOperation;
  49902. switch ( op ) {
  49903. case KeepStencilOp:
  49904. stencilOperation = GPUStencilOperation.Keep;
  49905. break;
  49906. case ZeroStencilOp:
  49907. stencilOperation = GPUStencilOperation.Zero;
  49908. break;
  49909. case ReplaceStencilOp:
  49910. stencilOperation = GPUStencilOperation.Replace;
  49911. break;
  49912. case InvertStencilOp:
  49913. stencilOperation = GPUStencilOperation.Invert;
  49914. break;
  49915. case IncrementStencilOp:
  49916. stencilOperation = GPUStencilOperation.IncrementClamp;
  49917. break;
  49918. case DecrementStencilOp:
  49919. stencilOperation = GPUStencilOperation.DecrementClamp;
  49920. break;
  49921. case IncrementWrapStencilOp:
  49922. stencilOperation = GPUStencilOperation.IncrementWrap;
  49923. break;
  49924. case DecrementWrapStencilOp:
  49925. stencilOperation = GPUStencilOperation.DecrementWrap;
  49926. break;
  49927. default:
  49928. console.error( 'THREE.WebGPURenderer: Invalid stencil operation.', stencilOperation );
  49929. }
  49930. return stencilOperation;
  49931. }
  49932. /**
  49933. * Returns the GPU blend operation which is required for the pipeline creation.
  49934. *
  49935. * @private
  49936. * @param {number} blendEquation - A three.js constant defining the blend equation.
  49937. * @return {string} The GPU blend operation.
  49938. */
  49939. _getBlendOperation( blendEquation ) {
  49940. let blendOperation;
  49941. switch ( blendEquation ) {
  49942. case AddEquation:
  49943. blendOperation = GPUBlendOperation.Add;
  49944. break;
  49945. case SubtractEquation:
  49946. blendOperation = GPUBlendOperation.Subtract;
  49947. break;
  49948. case ReverseSubtractEquation:
  49949. blendOperation = GPUBlendOperation.ReverseSubtract;
  49950. break;
  49951. case MinEquation:
  49952. blendOperation = GPUBlendOperation.Min;
  49953. break;
  49954. case MaxEquation:
  49955. blendOperation = GPUBlendOperation.Max;
  49956. break;
  49957. default:
  49958. console.error( 'THREE.WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  49959. }
  49960. return blendOperation;
  49961. }
  49962. /**
  49963. * Returns the primitive state as a descriptor object required
  49964. * for the pipeline creation.
  49965. *
  49966. * @private
  49967. * @param {Object3D} object - The 3D object.
  49968. * @param {BufferGeometry} geometry - The geometry.
  49969. * @param {Material} material - The material.
  49970. * @return {Object} The primitive state.
  49971. */
  49972. _getPrimitiveState( object, geometry, material ) {
  49973. const descriptor = {};
  49974. const utils = this.backend.utils;
  49975. descriptor.topology = utils.getPrimitiveTopology( object, material );
  49976. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  49977. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  49978. }
  49979. switch ( material.side ) {
  49980. case FrontSide:
  49981. descriptor.frontFace = GPUFrontFace.CCW;
  49982. descriptor.cullMode = GPUCullMode.Back;
  49983. break;
  49984. case BackSide:
  49985. descriptor.frontFace = GPUFrontFace.CCW;
  49986. descriptor.cullMode = GPUCullMode.Front;
  49987. break;
  49988. case DoubleSide:
  49989. descriptor.frontFace = GPUFrontFace.CCW;
  49990. descriptor.cullMode = GPUCullMode.None;
  49991. break;
  49992. default:
  49993. console.error( 'THREE.WebGPUPipelineUtils: Unknown material.side value.', material.side );
  49994. break;
  49995. }
  49996. return descriptor;
  49997. }
  49998. /**
  49999. * Returns the GPU color write mask which is required for the pipeline creation.
  50000. *
  50001. * @private
  50002. * @param {Material} material - The material.
  50003. * @return {number} The GPU color write mask.
  50004. */
  50005. _getColorWriteMask( material ) {
  50006. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  50007. }
  50008. /**
  50009. * Returns the GPU depth compare function which is required for the pipeline creation.
  50010. *
  50011. * @private
  50012. * @param {Material} material - The material.
  50013. * @return {string} The GPU depth compare function.
  50014. */
  50015. _getDepthCompare( material ) {
  50016. let depthCompare;
  50017. if ( material.depthTest === false ) {
  50018. depthCompare = GPUCompareFunction.Always;
  50019. } else {
  50020. const depthFunc = material.depthFunc;
  50021. switch ( depthFunc ) {
  50022. case NeverDepth:
  50023. depthCompare = GPUCompareFunction.Never;
  50024. break;
  50025. case AlwaysDepth:
  50026. depthCompare = GPUCompareFunction.Always;
  50027. break;
  50028. case LessDepth:
  50029. depthCompare = GPUCompareFunction.Less;
  50030. break;
  50031. case LessEqualDepth:
  50032. depthCompare = GPUCompareFunction.LessEqual;
  50033. break;
  50034. case EqualDepth:
  50035. depthCompare = GPUCompareFunction.Equal;
  50036. break;
  50037. case GreaterEqualDepth:
  50038. depthCompare = GPUCompareFunction.GreaterEqual;
  50039. break;
  50040. case GreaterDepth:
  50041. depthCompare = GPUCompareFunction.Greater;
  50042. break;
  50043. case NotEqualDepth:
  50044. depthCompare = GPUCompareFunction.NotEqual;
  50045. break;
  50046. default:
  50047. console.error( 'THREE.WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  50048. }
  50049. }
  50050. return depthCompare;
  50051. }
  50052. }
  50053. /**
  50054. * Manages a pool of WebGPU timestamp queries for performance measurement.
  50055. * Extends the base TimestampQueryPool to provide WebGPU-specific implementation.
  50056. *
  50057. * @augments TimestampQueryPool
  50058. */
  50059. class WebGPUTimestampQueryPool extends TimestampQueryPool {
  50060. /**
  50061. * Creates a new WebGPU timestamp query pool.
  50062. *
  50063. * @param {GPUDevice} device - The WebGPU device to create queries on.
  50064. * @param {string} type - The type identifier for this query pool.
  50065. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  50066. */
  50067. constructor( device, type, maxQueries = 2048 ) {
  50068. super( maxQueries );
  50069. this.device = device;
  50070. this.type = type;
  50071. this.querySet = this.device.createQuerySet( {
  50072. type: 'timestamp',
  50073. count: this.maxQueries,
  50074. label: `queryset_global_timestamp_${type}`
  50075. } );
  50076. const bufferSize = this.maxQueries * 8;
  50077. this.resolveBuffer = this.device.createBuffer( {
  50078. label: `buffer_timestamp_resolve_${type}`,
  50079. size: bufferSize,
  50080. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  50081. } );
  50082. this.resultBuffer = this.device.createBuffer( {
  50083. label: `buffer_timestamp_result_${type}`,
  50084. size: bufferSize,
  50085. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  50086. } );
  50087. }
  50088. /**
  50089. * Allocates a pair of queries for a given render context.
  50090. *
  50091. * @param {Object} renderContext - The render context to allocate queries for.
  50092. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  50093. */
  50094. allocateQueriesForContext( renderContext ) {
  50095. if ( ! this.trackTimestamp || this.isDisposed ) return null;
  50096. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  50097. 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() } ).` );
  50098. return null;
  50099. }
  50100. const baseOffset = this.currentQueryIndex;
  50101. this.currentQueryIndex += 2;
  50102. this.queryOffsets.set( renderContext.id, baseOffset );
  50103. return baseOffset;
  50104. }
  50105. /**
  50106. * Asynchronously resolves all pending queries and returns the total duration.
  50107. * If there's already a pending resolve operation, returns that promise instead.
  50108. *
  50109. * @async
  50110. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  50111. */
  50112. async resolveQueriesAsync() {
  50113. if ( ! this.trackTimestamp || this.currentQueryIndex === 0 || this.isDisposed ) {
  50114. return this.lastValue;
  50115. }
  50116. if ( this.pendingResolve ) {
  50117. return this.pendingResolve;
  50118. }
  50119. this.pendingResolve = this._resolveQueries();
  50120. try {
  50121. const result = await this.pendingResolve;
  50122. return result;
  50123. } finally {
  50124. this.pendingResolve = null;
  50125. }
  50126. }
  50127. /**
  50128. * Internal method to resolve queries and calculate total duration.
  50129. *
  50130. * @async
  50131. * @private
  50132. * @returns {Promise<number>} The total duration in milliseconds.
  50133. */
  50134. async _resolveQueries() {
  50135. if ( this.isDisposed ) {
  50136. return this.lastValue;
  50137. }
  50138. try {
  50139. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  50140. return this.lastValue;
  50141. }
  50142. const currentOffsets = new Map( this.queryOffsets );
  50143. const queryCount = this.currentQueryIndex;
  50144. const bytesUsed = queryCount * 8;
  50145. // Reset state before GPU work
  50146. this.currentQueryIndex = 0;
  50147. this.queryOffsets.clear();
  50148. const commandEncoder = this.device.createCommandEncoder();
  50149. commandEncoder.resolveQuerySet(
  50150. this.querySet,
  50151. 0,
  50152. queryCount,
  50153. this.resolveBuffer,
  50154. 0
  50155. );
  50156. commandEncoder.copyBufferToBuffer(
  50157. this.resolveBuffer,
  50158. 0,
  50159. this.resultBuffer,
  50160. 0,
  50161. bytesUsed
  50162. );
  50163. const commandBuffer = commandEncoder.finish();
  50164. this.device.queue.submit( [ commandBuffer ] );
  50165. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  50166. return this.lastValue;
  50167. }
  50168. // Create and track the mapping operation
  50169. await this.resultBuffer.mapAsync( GPUMapMode.READ, 0, bytesUsed );
  50170. if ( this.isDisposed ) {
  50171. if ( this.resultBuffer.mapState === 'mapped' ) {
  50172. this.resultBuffer.unmap();
  50173. }
  50174. return this.lastValue;
  50175. }
  50176. const times = new BigUint64Array( this.resultBuffer.getMappedRange( 0, bytesUsed ) );
  50177. let totalDuration = 0;
  50178. for ( const [ , baseOffset ] of currentOffsets ) {
  50179. const startTime = times[ baseOffset ];
  50180. const endTime = times[ baseOffset + 1 ];
  50181. const duration = Number( endTime - startTime ) / 1e6;
  50182. totalDuration += duration;
  50183. }
  50184. this.resultBuffer.unmap();
  50185. this.lastValue = totalDuration;
  50186. return totalDuration;
  50187. } catch ( error ) {
  50188. console.error( 'Error resolving queries:', error );
  50189. if ( this.resultBuffer.mapState === 'mapped' ) {
  50190. this.resultBuffer.unmap();
  50191. }
  50192. return this.lastValue;
  50193. }
  50194. }
  50195. /**
  50196. * Dispose of the query pool.
  50197. *
  50198. * @async
  50199. * @returns {Promise} A Promise that resolves when the dispose has been executed.
  50200. */
  50201. async dispose() {
  50202. if ( this.isDisposed ) {
  50203. return;
  50204. }
  50205. this.isDisposed = true;
  50206. // Wait for pending resolve operation
  50207. if ( this.pendingResolve ) {
  50208. try {
  50209. await this.pendingResolve;
  50210. } catch ( error ) {
  50211. console.error( 'Error waiting for pending resolve:', error );
  50212. }
  50213. }
  50214. // Ensure buffer is unmapped before destroying
  50215. if ( this.resultBuffer && this.resultBuffer.mapState === 'mapped' ) {
  50216. try {
  50217. this.resultBuffer.unmap();
  50218. } catch ( error ) {
  50219. console.error( 'Error unmapping buffer:', error );
  50220. }
  50221. }
  50222. // Destroy resources
  50223. if ( this.querySet ) {
  50224. this.querySet.destroy();
  50225. this.querySet = null;
  50226. }
  50227. if ( this.resolveBuffer ) {
  50228. this.resolveBuffer.destroy();
  50229. this.resolveBuffer = null;
  50230. }
  50231. if ( this.resultBuffer ) {
  50232. this.resultBuffer.destroy();
  50233. this.resultBuffer = null;
  50234. }
  50235. this.queryOffsets.clear();
  50236. this.pendingResolve = null;
  50237. }
  50238. }
  50239. /*// debugger tools
  50240. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  50241. //*/
  50242. /**
  50243. * A backend implementation targeting WebGPU.
  50244. *
  50245. * @private
  50246. * @augments Backend
  50247. */
  50248. class WebGPUBackend extends Backend {
  50249. /**
  50250. * WebGPUBackend options.
  50251. *
  50252. * @typedef {Object} WebGPUBackend~Options
  50253. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  50254. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  50255. * @property {boolean} [compatibilityMode=false] - Whether the backend should be in compatibility mode or not.
  50256. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  50257. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  50258. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  50259. * @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.
  50260. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  50261. * @property {boolean} [trackTimestamp=false] - Whether to track timestamps with a Timestamp Query API or not.
  50262. * @property {string} [powerPreference=undefined] - The power preference.
  50263. * @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.
  50264. * @property {GPUDevice} [device=undefined] - If there is an existing GPU device on app level, it can be passed to the renderer as a parameter.
  50265. * @property {number} [outputType=undefined] - Texture type for output to canvas. By default, device's preferred format is used; other formats may incur overhead.
  50266. */
  50267. /**
  50268. * Constructs a new WebGPU backend.
  50269. *
  50270. * @param {WebGPUBackend~Options} [parameters] - The configuration parameter.
  50271. */
  50272. constructor( parameters = {} ) {
  50273. super( parameters );
  50274. /**
  50275. * This flag can be used for type testing.
  50276. *
  50277. * @type {boolean}
  50278. * @readonly
  50279. * @default true
  50280. */
  50281. this.isWebGPUBackend = true;
  50282. // some parameters require default values other than "undefined"
  50283. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  50284. this.parameters.compatibilityMode = ( parameters.compatibilityMode === undefined ) ? false : parameters.compatibilityMode;
  50285. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  50286. /**
  50287. * Indicates whether the backend is in compatibility mode or not.
  50288. * @type {boolean}
  50289. * @default false
  50290. */
  50291. this.compatibilityMode = this.parameters.compatibilityMode;
  50292. /**
  50293. * A reference to the device.
  50294. *
  50295. * @type {?GPUDevice}
  50296. * @default null
  50297. */
  50298. this.device = null;
  50299. /**
  50300. * A reference to the context.
  50301. *
  50302. * @type {?GPUCanvasContext}
  50303. * @default null
  50304. */
  50305. this.context = null;
  50306. /**
  50307. * A reference to the color attachment of the default framebuffer.
  50308. *
  50309. * @type {?GPUTexture}
  50310. * @default null
  50311. */
  50312. this.colorBuffer = null;
  50313. /**
  50314. * A reference to the default render pass descriptor.
  50315. *
  50316. * @type {?Object}
  50317. * @default null
  50318. */
  50319. this.defaultRenderPassdescriptor = null;
  50320. /**
  50321. * A reference to a backend module holding common utility functions.
  50322. *
  50323. * @type {WebGPUUtils}
  50324. */
  50325. this.utils = new WebGPUUtils( this );
  50326. /**
  50327. * A reference to a backend module holding shader attribute-related
  50328. * utility functions.
  50329. *
  50330. * @type {WebGPUAttributeUtils}
  50331. */
  50332. this.attributeUtils = new WebGPUAttributeUtils( this );
  50333. /**
  50334. * A reference to a backend module holding shader binding-related
  50335. * utility functions.
  50336. *
  50337. * @type {WebGPUBindingUtils}
  50338. */
  50339. this.bindingUtils = new WebGPUBindingUtils( this );
  50340. /**
  50341. * A reference to a backend module holding shader pipeline-related
  50342. * utility functions.
  50343. *
  50344. * @type {WebGPUPipelineUtils}
  50345. */
  50346. this.pipelineUtils = new WebGPUPipelineUtils( this );
  50347. /**
  50348. * A reference to a backend module holding shader texture-related
  50349. * utility functions.
  50350. *
  50351. * @type {WebGPUTextureUtils}
  50352. */
  50353. this.textureUtils = new WebGPUTextureUtils( this );
  50354. /**
  50355. * A map that manages the resolve buffers for occlusion queries.
  50356. *
  50357. * @type {Map<number,GPUBuffer>}
  50358. */
  50359. this.occludedResolveCache = new Map();
  50360. }
  50361. /**
  50362. * Initializes the backend so it is ready for usage.
  50363. *
  50364. * @async
  50365. * @param {Renderer} renderer - The renderer.
  50366. * @return {Promise} A Promise that resolves when the backend has been initialized.
  50367. */
  50368. async init( renderer ) {
  50369. await super.init( renderer );
  50370. //
  50371. const parameters = this.parameters;
  50372. // create the device if it is not passed with parameters
  50373. let device;
  50374. if ( parameters.device === undefined ) {
  50375. const adapterOptions = {
  50376. powerPreference: parameters.powerPreference,
  50377. featureLevel: parameters.compatibilityMode ? 'compatibility' : undefined
  50378. };
  50379. const adapter = ( typeof navigator !== 'undefined' ) ? await navigator.gpu.requestAdapter( adapterOptions ) : null;
  50380. if ( adapter === null ) {
  50381. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  50382. }
  50383. // feature support
  50384. const features = Object.values( GPUFeatureName );
  50385. const supportedFeatures = [];
  50386. for ( const name of features ) {
  50387. if ( adapter.features.has( name ) ) {
  50388. supportedFeatures.push( name );
  50389. }
  50390. }
  50391. const deviceDescriptor = {
  50392. requiredFeatures: supportedFeatures,
  50393. requiredLimits: parameters.requiredLimits
  50394. };
  50395. device = await adapter.requestDevice( deviceDescriptor );
  50396. } else {
  50397. device = parameters.device;
  50398. }
  50399. device.lost.then( ( info ) => {
  50400. const deviceLossInfo = {
  50401. api: 'WebGPU',
  50402. message: info.message || 'Unknown reason',
  50403. reason: info.reason || null,
  50404. originalEvent: info
  50405. };
  50406. renderer.onDeviceLost( deviceLossInfo );
  50407. } );
  50408. const context = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgpu' );
  50409. this.device = device;
  50410. this.context = context;
  50411. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  50412. this.trackTimestamp = this.trackTimestamp && this.hasFeature( GPUFeatureName.TimestampQuery );
  50413. this.context.configure( {
  50414. device: this.device,
  50415. format: this.utils.getPreferredCanvasFormat(),
  50416. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  50417. alphaMode: alphaMode
  50418. } );
  50419. this.updateSize();
  50420. }
  50421. /**
  50422. * The coordinate system of the backend.
  50423. *
  50424. * @type {number}
  50425. * @readonly
  50426. */
  50427. get coordinateSystem() {
  50428. return WebGPUCoordinateSystem;
  50429. }
  50430. /**
  50431. * This method performs a readback operation by moving buffer data from
  50432. * a storage buffer attribute from the GPU to the CPU.
  50433. *
  50434. * @async
  50435. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  50436. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  50437. */
  50438. async getArrayBufferAsync( attribute ) {
  50439. return await this.attributeUtils.getArrayBufferAsync( attribute );
  50440. }
  50441. /**
  50442. * Returns the backend's rendering context.
  50443. *
  50444. * @return {GPUCanvasContext} The rendering context.
  50445. */
  50446. getContext() {
  50447. return this.context;
  50448. }
  50449. /**
  50450. * Returns the default render pass descriptor.
  50451. *
  50452. * In WebGPU, the default framebuffer must be configured
  50453. * like custom framebuffers so the backend needs a render
  50454. * pass descriptor even when rendering directly to screen.
  50455. *
  50456. * @private
  50457. * @return {Object} The render pass descriptor.
  50458. */
  50459. _getDefaultRenderPassDescriptor() {
  50460. let descriptor = this.defaultRenderPassdescriptor;
  50461. if ( descriptor === null ) {
  50462. const renderer = this.renderer;
  50463. descriptor = {
  50464. colorAttachments: [ {
  50465. view: null
  50466. } ],
  50467. };
  50468. if ( this.renderer.depth === true || this.renderer.stencil === true ) {
  50469. descriptor.depthStencilAttachment = {
  50470. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  50471. };
  50472. }
  50473. const colorAttachment = descriptor.colorAttachments[ 0 ];
  50474. if ( this.renderer.samples > 0 ) {
  50475. colorAttachment.view = this.colorBuffer.createView();
  50476. } else {
  50477. colorAttachment.resolveTarget = undefined;
  50478. }
  50479. this.defaultRenderPassdescriptor = descriptor;
  50480. }
  50481. const colorAttachment = descriptor.colorAttachments[ 0 ];
  50482. if ( this.renderer.samples > 0 ) {
  50483. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  50484. } else {
  50485. colorAttachment.view = this.context.getCurrentTexture().createView();
  50486. }
  50487. return descriptor;
  50488. }
  50489. /**
  50490. * Internal to determine if the current render target is a render target array with depth 2D array texture.
  50491. *
  50492. * @param {RenderContext} renderContext - The render context.
  50493. * @return {boolean} Whether the render target is a render target array with depth 2D array texture.
  50494. *
  50495. * @private
  50496. */
  50497. _isRenderCameraDepthArray( renderContext ) {
  50498. return renderContext.depthTexture && renderContext.depthTexture.image.depth > 1 && renderContext.camera.isArrayCamera;
  50499. }
  50500. /**
  50501. * Returns the render pass descriptor for the given render context.
  50502. *
  50503. * @private
  50504. * @param {RenderContext} renderContext - The render context.
  50505. * @param {Object} colorAttachmentsConfig - Configuration object for the color attachments.
  50506. * @return {Object} The render pass descriptor.
  50507. */
  50508. _getRenderPassDescriptor( renderContext, colorAttachmentsConfig = {} ) {
  50509. const renderTarget = renderContext.renderTarget;
  50510. const renderTargetData = this.get( renderTarget );
  50511. let descriptors = renderTargetData.descriptors;
  50512. if ( descriptors === undefined ||
  50513. renderTargetData.width !== renderTarget.width ||
  50514. renderTargetData.height !== renderTarget.height ||
  50515. renderTargetData.dimensions !== renderTarget.dimensions ||
  50516. renderTargetData.activeMipmapLevel !== renderContext.activeMipmapLevel ||
  50517. renderTargetData.activeCubeFace !== renderContext.activeCubeFace ||
  50518. renderTargetData.samples !== renderTarget.samples
  50519. ) {
  50520. descriptors = {};
  50521. renderTargetData.descriptors = descriptors;
  50522. // dispose
  50523. const onDispose = () => {
  50524. renderTarget.removeEventListener( 'dispose', onDispose );
  50525. this.delete( renderTarget );
  50526. };
  50527. if ( renderTarget.hasEventListener( 'dispose', onDispose ) === false ) {
  50528. renderTarget.addEventListener( 'dispose', onDispose );
  50529. }
  50530. }
  50531. const cacheKey = renderContext.getCacheKey();
  50532. let descriptorBase = descriptors[ cacheKey ];
  50533. if ( descriptorBase === undefined ) {
  50534. const textures = renderContext.textures;
  50535. const textureViews = [];
  50536. let sliceIndex;
  50537. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( renderContext );
  50538. for ( let i = 0; i < textures.length; i ++ ) {
  50539. const textureData = this.get( textures[ i ] );
  50540. const viewDescriptor = {
  50541. label: `colorAttachment_${ i }`,
  50542. baseMipLevel: renderContext.activeMipmapLevel,
  50543. mipLevelCount: 1,
  50544. baseArrayLayer: renderContext.activeCubeFace,
  50545. arrayLayerCount: 1,
  50546. dimension: GPUTextureViewDimension.TwoD
  50547. };
  50548. if ( renderTarget.isRenderTarget3D ) {
  50549. sliceIndex = renderContext.activeCubeFace;
  50550. viewDescriptor.baseArrayLayer = 0;
  50551. viewDescriptor.dimension = GPUTextureViewDimension.ThreeD;
  50552. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  50553. } else if ( renderTarget.isRenderTarget && textures[ i ].image.depth > 1 ) {
  50554. if ( isRenderCameraDepthArray === true ) {
  50555. const cameras = renderContext.camera.cameras;
  50556. for ( let layer = 0; layer < cameras.length; layer ++ ) {
  50557. const layerViewDescriptor = {
  50558. ...viewDescriptor,
  50559. baseArrayLayer: layer,
  50560. arrayLayerCount: 1,
  50561. dimension: GPUTextureViewDimension.TwoD
  50562. };
  50563. const textureView = textureData.texture.createView( layerViewDescriptor );
  50564. textureViews.push( {
  50565. view: textureView,
  50566. resolveTarget: undefined,
  50567. depthSlice: undefined
  50568. } );
  50569. }
  50570. } else {
  50571. viewDescriptor.dimension = GPUTextureViewDimension.TwoDArray;
  50572. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  50573. }
  50574. }
  50575. if ( isRenderCameraDepthArray !== true ) {
  50576. const textureView = textureData.texture.createView( viewDescriptor );
  50577. let view, resolveTarget;
  50578. if ( textureData.msaaTexture !== undefined ) {
  50579. view = textureData.msaaTexture.createView();
  50580. resolveTarget = textureView;
  50581. } else {
  50582. view = textureView;
  50583. resolveTarget = undefined;
  50584. }
  50585. textureViews.push( {
  50586. view,
  50587. resolveTarget,
  50588. depthSlice: sliceIndex
  50589. } );
  50590. }
  50591. }
  50592. descriptorBase = { textureViews };
  50593. if ( renderContext.depth ) {
  50594. const depthTextureData = this.get( renderContext.depthTexture );
  50595. const options = {};
  50596. if ( renderContext.depthTexture.isArrayTexture ) {
  50597. options.dimension = GPUTextureViewDimension.TwoD;
  50598. options.arrayLayerCount = 1;
  50599. options.baseArrayLayer = renderContext.activeCubeFace;
  50600. }
  50601. descriptorBase.depthStencilView = depthTextureData.texture.createView( options );
  50602. }
  50603. descriptors[ cacheKey ] = descriptorBase;
  50604. renderTargetData.width = renderTarget.width;
  50605. renderTargetData.height = renderTarget.height;
  50606. renderTargetData.samples = renderTarget.samples;
  50607. renderTargetData.activeMipmapLevel = renderContext.activeMipmapLevel;
  50608. renderTargetData.activeCubeFace = renderContext.activeCubeFace;
  50609. renderTargetData.dimensions = renderTarget.dimensions;
  50610. }
  50611. const descriptor = {
  50612. colorAttachments: []
  50613. };
  50614. // Apply dynamic properties to cached views
  50615. for ( let i = 0; i < descriptorBase.textureViews.length; i ++ ) {
  50616. const viewInfo = descriptorBase.textureViews[ i ];
  50617. let clearValue = { r: 0, g: 0, b: 0, a: 1 };
  50618. if ( i === 0 && colorAttachmentsConfig.clearValue ) {
  50619. clearValue = colorAttachmentsConfig.clearValue;
  50620. }
  50621. descriptor.colorAttachments.push( {
  50622. view: viewInfo.view,
  50623. depthSlice: viewInfo.depthSlice,
  50624. resolveTarget: viewInfo.resolveTarget,
  50625. loadOp: colorAttachmentsConfig.loadOp || GPULoadOp.Load,
  50626. storeOp: colorAttachmentsConfig.storeOp || GPUStoreOp.Store,
  50627. clearValue: clearValue
  50628. } );
  50629. }
  50630. if ( descriptorBase.depthStencilView ) {
  50631. descriptor.depthStencilAttachment = {
  50632. view: descriptorBase.depthStencilView
  50633. };
  50634. }
  50635. return descriptor;
  50636. }
  50637. /**
  50638. * This method is executed at the beginning of a render call and prepares
  50639. * the WebGPU state for upcoming render calls
  50640. *
  50641. * @param {RenderContext} renderContext - The render context.
  50642. */
  50643. beginRender( renderContext ) {
  50644. const renderContextData = this.get( renderContext );
  50645. const device = this.device;
  50646. const occlusionQueryCount = renderContext.occlusionQueryCount;
  50647. let occlusionQuerySet;
  50648. if ( occlusionQueryCount > 0 ) {
  50649. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  50650. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  50651. // Get a reference to the array of objects with queries. The renderContextData property
  50652. // can be changed by another render pass before the buffer.mapAsyc() completes.
  50653. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  50654. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  50655. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  50656. //
  50657. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount, label: `occlusionQuerySet_${ renderContext.id }` } );
  50658. renderContextData.occlusionQuerySet = occlusionQuerySet;
  50659. renderContextData.occlusionQueryIndex = 0;
  50660. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  50661. renderContextData.lastOcclusionObject = null;
  50662. }
  50663. let descriptor;
  50664. if ( renderContext.textures === null ) {
  50665. descriptor = this._getDefaultRenderPassDescriptor();
  50666. } else {
  50667. descriptor = this._getRenderPassDescriptor( renderContext, { loadOp: GPULoadOp.Load } );
  50668. }
  50669. this.initTimestampQuery( renderContext, descriptor );
  50670. descriptor.occlusionQuerySet = occlusionQuerySet;
  50671. const depthStencilAttachment = descriptor.depthStencilAttachment;
  50672. if ( renderContext.textures !== null ) {
  50673. const colorAttachments = descriptor.colorAttachments;
  50674. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  50675. const colorAttachment = colorAttachments[ i ];
  50676. if ( renderContext.clearColor ) {
  50677. colorAttachment.clearValue = i === 0 ? renderContext.clearColorValue : { r: 0, g: 0, b: 0, a: 1 };
  50678. colorAttachment.loadOp = GPULoadOp.Clear;
  50679. } else {
  50680. colorAttachment.loadOp = GPULoadOp.Load;
  50681. }
  50682. colorAttachment.storeOp = GPUStoreOp.Store;
  50683. }
  50684. } else {
  50685. const colorAttachment = descriptor.colorAttachments[ 0 ];
  50686. if ( renderContext.clearColor ) {
  50687. colorAttachment.clearValue = renderContext.clearColorValue;
  50688. colorAttachment.loadOp = GPULoadOp.Clear;
  50689. } else {
  50690. colorAttachment.loadOp = GPULoadOp.Load;
  50691. }
  50692. colorAttachment.storeOp = GPUStoreOp.Store;
  50693. }
  50694. //
  50695. if ( renderContext.depth ) {
  50696. if ( renderContext.clearDepth ) {
  50697. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  50698. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  50699. } else {
  50700. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  50701. }
  50702. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  50703. }
  50704. if ( renderContext.stencil ) {
  50705. if ( renderContext.clearStencil ) {
  50706. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  50707. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  50708. } else {
  50709. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  50710. }
  50711. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  50712. }
  50713. //
  50714. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  50715. // shadow arrays - prepare bundle encoders for each camera in an array camera
  50716. if ( this._isRenderCameraDepthArray( renderContext ) === true ) {
  50717. const cameras = renderContext.camera.cameras;
  50718. if ( ! renderContextData.layerDescriptors || renderContextData.layerDescriptors.length !== cameras.length ) {
  50719. this._createDepthLayerDescriptors( renderContext, renderContextData, descriptor, cameras );
  50720. } else {
  50721. this._updateDepthLayerDescriptors( renderContext, renderContextData, cameras );
  50722. }
  50723. // Create bundle encoders for each layer
  50724. renderContextData.bundleEncoders = [];
  50725. renderContextData.bundleSets = [];
  50726. // Create separate bundle encoders for each camera in the array
  50727. for ( let i = 0; i < cameras.length; i ++ ) {
  50728. const bundleEncoder = this.pipelineUtils.createBundleEncoder(
  50729. renderContext,
  50730. 'renderBundleArrayCamera_' + i
  50731. );
  50732. // Initialize state tracking for this bundle
  50733. const bundleSets = {
  50734. attributes: {},
  50735. bindingGroups: [],
  50736. pipeline: null,
  50737. index: null
  50738. };
  50739. renderContextData.bundleEncoders.push( bundleEncoder );
  50740. renderContextData.bundleSets.push( bundleSets );
  50741. }
  50742. // We'll complete the bundles in finishRender
  50743. renderContextData.currentPass = null;
  50744. } else {
  50745. const currentPass = encoder.beginRenderPass( descriptor );
  50746. renderContextData.currentPass = currentPass;
  50747. if ( renderContext.viewport ) {
  50748. this.updateViewport( renderContext );
  50749. }
  50750. if ( renderContext.scissor ) {
  50751. const { x, y, width, height } = renderContext.scissorValue;
  50752. currentPass.setScissorRect( x, y, width, height );
  50753. }
  50754. }
  50755. //
  50756. renderContextData.descriptor = descriptor;
  50757. renderContextData.encoder = encoder;
  50758. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  50759. renderContextData.renderBundles = [];
  50760. }
  50761. /**
  50762. * This method creates layer descriptors for each camera in an array camera
  50763. * to prepare for rendering to a depth array texture.
  50764. *
  50765. * @param {RenderContext} renderContext - The render context.
  50766. * @param {Object} renderContextData - The render context data.
  50767. * @param {Object} descriptor - The render pass descriptor.
  50768. * @param {ArrayCamera} cameras - The array camera.
  50769. *
  50770. * @private
  50771. */
  50772. _createDepthLayerDescriptors( renderContext, renderContextData, descriptor, cameras ) {
  50773. const depthStencilAttachment = descriptor.depthStencilAttachment;
  50774. renderContextData.layerDescriptors = [];
  50775. const depthTextureData = this.get( renderContext.depthTexture );
  50776. if ( ! depthTextureData.viewCache ) {
  50777. depthTextureData.viewCache = [];
  50778. }
  50779. for ( let i = 0; i < cameras.length; i ++ ) {
  50780. const layerDescriptor = {
  50781. ...descriptor,
  50782. colorAttachments: [ {
  50783. ...descriptor.colorAttachments[ 0 ],
  50784. view: descriptor.colorAttachments[ i ].view
  50785. } ]
  50786. };
  50787. if ( descriptor.depthStencilAttachment ) {
  50788. const layerIndex = i;
  50789. if ( ! depthTextureData.viewCache[ layerIndex ] ) {
  50790. depthTextureData.viewCache[ layerIndex ] = depthTextureData.texture.createView( {
  50791. dimension: GPUTextureViewDimension.TwoD,
  50792. baseArrayLayer: i,
  50793. arrayLayerCount: 1
  50794. } );
  50795. }
  50796. layerDescriptor.depthStencilAttachment = {
  50797. view: depthTextureData.viewCache[ layerIndex ],
  50798. depthLoadOp: depthStencilAttachment.depthLoadOp || GPULoadOp.Clear,
  50799. depthStoreOp: depthStencilAttachment.depthStoreOp || GPUStoreOp.Store,
  50800. depthClearValue: depthStencilAttachment.depthClearValue || 1.0
  50801. };
  50802. if ( renderContext.stencil ) {
  50803. layerDescriptor.depthStencilAttachment.stencilLoadOp = depthStencilAttachment.stencilLoadOp;
  50804. layerDescriptor.depthStencilAttachment.stencilStoreOp = depthStencilAttachment.stencilStoreOp;
  50805. layerDescriptor.depthStencilAttachment.stencilClearValue = depthStencilAttachment.stencilClearValue;
  50806. }
  50807. } else {
  50808. layerDescriptor.depthStencilAttachment = { ...depthStencilAttachment };
  50809. }
  50810. renderContextData.layerDescriptors.push( layerDescriptor );
  50811. }
  50812. }
  50813. /**
  50814. * This method updates the layer descriptors for each camera in an array camera
  50815. * to prepare for rendering to a depth array texture.
  50816. *
  50817. * @param {RenderContext} renderContext - The render context.
  50818. * @param {Object} renderContextData - The render context data.
  50819. * @param {ArrayCamera} cameras - The array camera.
  50820. *
  50821. */
  50822. _updateDepthLayerDescriptors( renderContext, renderContextData, cameras ) {
  50823. for ( let i = 0; i < cameras.length; i ++ ) {
  50824. const layerDescriptor = renderContextData.layerDescriptors[ i ];
  50825. if ( layerDescriptor.depthStencilAttachment ) {
  50826. const depthAttachment = layerDescriptor.depthStencilAttachment;
  50827. if ( renderContext.depth ) {
  50828. if ( renderContext.clearDepth ) {
  50829. depthAttachment.depthClearValue = renderContext.clearDepthValue;
  50830. depthAttachment.depthLoadOp = GPULoadOp.Clear;
  50831. } else {
  50832. depthAttachment.depthLoadOp = GPULoadOp.Load;
  50833. }
  50834. }
  50835. if ( renderContext.stencil ) {
  50836. if ( renderContext.clearStencil ) {
  50837. depthAttachment.stencilClearValue = renderContext.clearStencilValue;
  50838. depthAttachment.stencilLoadOp = GPULoadOp.Clear;
  50839. } else {
  50840. depthAttachment.stencilLoadOp = GPULoadOp.Load;
  50841. }
  50842. }
  50843. }
  50844. }
  50845. }
  50846. /**
  50847. * This method is executed at the end of a render call and finalizes work
  50848. * after draw calls.
  50849. *
  50850. * @param {RenderContext} renderContext - The render context.
  50851. */
  50852. finishRender( renderContext ) {
  50853. const renderContextData = this.get( renderContext );
  50854. const occlusionQueryCount = renderContext.occlusionQueryCount;
  50855. if ( renderContextData.renderBundles.length > 0 ) {
  50856. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  50857. }
  50858. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  50859. renderContextData.currentPass.endOcclusionQuery();
  50860. }
  50861. // shadow arrays - Execute bundles for each layer
  50862. const encoder = renderContextData.encoder;
  50863. if ( this._isRenderCameraDepthArray( renderContext ) === true ) {
  50864. const bundles = [];
  50865. for ( let i = 0; i < renderContextData.bundleEncoders.length; i ++ ) {
  50866. const bundleEncoder = renderContextData.bundleEncoders[ i ];
  50867. bundles.push( bundleEncoder.finish() );
  50868. }
  50869. for ( let i = 0; i < renderContextData.layerDescriptors.length; i ++ ) {
  50870. if ( i < bundles.length ) {
  50871. const layerDescriptor = renderContextData.layerDescriptors[ i ];
  50872. const renderPass = encoder.beginRenderPass( layerDescriptor );
  50873. if ( renderContext.viewport ) {
  50874. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  50875. renderPass.setViewport( x, y, width, height, minDepth, maxDepth );
  50876. }
  50877. if ( renderContext.scissor ) {
  50878. const { x, y, width, height } = renderContext.scissorValue;
  50879. renderPass.setScissorRect( x, y, width, height );
  50880. }
  50881. renderPass.executeBundles( [ bundles[ i ] ] );
  50882. renderPass.end();
  50883. }
  50884. }
  50885. } else if ( renderContextData.currentPass ) {
  50886. renderContextData.currentPass.end();
  50887. }
  50888. if ( occlusionQueryCount > 0 ) {
  50889. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  50890. //
  50891. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  50892. if ( queryResolveBuffer === undefined ) {
  50893. queryResolveBuffer = this.device.createBuffer(
  50894. {
  50895. size: bufferSize,
  50896. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  50897. }
  50898. );
  50899. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  50900. }
  50901. //
  50902. const readBuffer = this.device.createBuffer(
  50903. {
  50904. size: bufferSize,
  50905. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  50906. }
  50907. );
  50908. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  50909. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  50910. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  50911. renderContextData.occlusionQueryBuffer = readBuffer;
  50912. //
  50913. this.resolveOccludedAsync( renderContext );
  50914. }
  50915. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  50916. //
  50917. if ( renderContext.textures !== null ) {
  50918. const textures = renderContext.textures;
  50919. for ( let i = 0; i < textures.length; i ++ ) {
  50920. const texture = textures[ i ];
  50921. if ( texture.generateMipmaps === true ) {
  50922. this.textureUtils.generateMipmaps( texture );
  50923. }
  50924. }
  50925. }
  50926. }
  50927. /**
  50928. * Returns `true` if the given 3D object is fully occluded by other
  50929. * 3D objects in the scene.
  50930. *
  50931. * @param {RenderContext} renderContext - The render context.
  50932. * @param {Object3D} object - The 3D object to test.
  50933. * @return {boolean} Whether the 3D object is fully occluded or not.
  50934. */
  50935. isOccluded( renderContext, object ) {
  50936. const renderContextData = this.get( renderContext );
  50937. return renderContextData.occluded && renderContextData.occluded.has( object );
  50938. }
  50939. /**
  50940. * This method processes the result of occlusion queries and writes it
  50941. * into render context data.
  50942. *
  50943. * @async
  50944. * @param {RenderContext} renderContext - The render context.
  50945. * @return {Promise} A Promise that resolves when the occlusion query results have been processed.
  50946. */
  50947. async resolveOccludedAsync( renderContext ) {
  50948. const renderContextData = this.get( renderContext );
  50949. // handle occlusion query results
  50950. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  50951. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  50952. const occluded = new WeakSet();
  50953. renderContextData.currentOcclusionQueryObjects = null;
  50954. renderContextData.currentOcclusionQueryBuffer = null;
  50955. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  50956. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  50957. const results = new BigUint64Array( buffer );
  50958. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  50959. if ( results[ i ] === BigInt( 0 ) ) {
  50960. occluded.add( currentOcclusionQueryObjects[ i ] );
  50961. }
  50962. }
  50963. currentOcclusionQueryBuffer.destroy();
  50964. renderContextData.occluded = occluded;
  50965. }
  50966. }
  50967. /**
  50968. * Updates the viewport with the values from the given render context.
  50969. *
  50970. * @param {RenderContext} renderContext - The render context.
  50971. */
  50972. updateViewport( renderContext ) {
  50973. const { currentPass } = this.get( renderContext );
  50974. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  50975. currentPass.setViewport( x, y, width, height, minDepth, maxDepth );
  50976. }
  50977. /**
  50978. * Returns the clear color and alpha into a single
  50979. * color object.
  50980. *
  50981. * @return {Color4} The clear color.
  50982. */
  50983. getClearColor() {
  50984. const clearColor = super.getClearColor();
  50985. // only premultiply alpha when alphaMode is "premultiplied"
  50986. if ( this.renderer.alpha === true ) {
  50987. clearColor.r *= clearColor.a;
  50988. clearColor.g *= clearColor.a;
  50989. clearColor.b *= clearColor.a;
  50990. }
  50991. return clearColor;
  50992. }
  50993. /**
  50994. * Performs a clear operation.
  50995. *
  50996. * @param {boolean} color - Whether the color buffer should be cleared or not.
  50997. * @param {boolean} depth - Whether the depth buffer should be cleared or not.
  50998. * @param {boolean} stencil - Whether the stencil buffer should be cleared or not.
  50999. * @param {?RenderContext} [renderTargetContext=null] - The render context of the current set render target.
  51000. */
  51001. clear( color, depth, stencil, renderTargetContext = null ) {
  51002. const device = this.device;
  51003. const renderer = this.renderer;
  51004. let colorAttachments = [];
  51005. let depthStencilAttachment;
  51006. let clearValue;
  51007. let supportsDepth;
  51008. let supportsStencil;
  51009. if ( color ) {
  51010. const clearColor = this.getClearColor();
  51011. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  51012. }
  51013. if ( renderTargetContext === null ) {
  51014. supportsDepth = renderer.depth;
  51015. supportsStencil = renderer.stencil;
  51016. const descriptor = this._getDefaultRenderPassDescriptor();
  51017. if ( color ) {
  51018. colorAttachments = descriptor.colorAttachments;
  51019. const colorAttachment = colorAttachments[ 0 ];
  51020. colorAttachment.clearValue = clearValue;
  51021. colorAttachment.loadOp = GPULoadOp.Clear;
  51022. colorAttachment.storeOp = GPUStoreOp.Store;
  51023. }
  51024. if ( supportsDepth || supportsStencil ) {
  51025. depthStencilAttachment = descriptor.depthStencilAttachment;
  51026. }
  51027. } else {
  51028. supportsDepth = renderTargetContext.depth;
  51029. supportsStencil = renderTargetContext.stencil;
  51030. const clearConfig = {
  51031. loadOp: color ? GPULoadOp.Clear : GPULoadOp.Load,
  51032. clearValue: color ? clearValue : undefined
  51033. };
  51034. if ( supportsDepth ) {
  51035. clearConfig.depthLoadOp = depth ? GPULoadOp.Clear : GPULoadOp.Load;
  51036. clearConfig.depthClearValue = depth ? renderer.getClearDepth() : undefined;
  51037. clearConfig.depthStoreOp = GPUStoreOp.Store;
  51038. }
  51039. if ( supportsStencil ) {
  51040. clearConfig.stencilLoadOp = stencil ? GPULoadOp.Clear : GPULoadOp.Load;
  51041. clearConfig.stencilClearValue = stencil ? renderer.getClearStencil() : undefined;
  51042. clearConfig.stencilStoreOp = GPUStoreOp.Store;
  51043. }
  51044. const descriptor = this._getRenderPassDescriptor( renderTargetContext, clearConfig );
  51045. colorAttachments = descriptor.colorAttachments;
  51046. depthStencilAttachment = descriptor.depthStencilAttachment;
  51047. }
  51048. if ( supportsDepth && depthStencilAttachment ) {
  51049. if ( depth ) {
  51050. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  51051. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  51052. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  51053. } else {
  51054. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  51055. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  51056. }
  51057. }
  51058. //
  51059. if ( supportsStencil && depthStencilAttachment ) {
  51060. if ( stencil ) {
  51061. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  51062. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  51063. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  51064. } else {
  51065. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  51066. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  51067. }
  51068. }
  51069. //
  51070. const encoder = device.createCommandEncoder( { label: 'clear' } );
  51071. const currentPass = encoder.beginRenderPass( {
  51072. colorAttachments,
  51073. depthStencilAttachment
  51074. } );
  51075. currentPass.end();
  51076. device.queue.submit( [ encoder.finish() ] );
  51077. }
  51078. // compute
  51079. /**
  51080. * This method is executed at the beginning of a compute call and
  51081. * prepares the state for upcoming compute tasks.
  51082. *
  51083. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  51084. */
  51085. beginCompute( computeGroup ) {
  51086. const groupGPU = this.get( computeGroup );
  51087. const descriptor = {
  51088. label: 'computeGroup_' + computeGroup.id
  51089. };
  51090. this.initTimestampQuery( computeGroup, descriptor );
  51091. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder( { label: 'computeGroup_' + computeGroup.id } );
  51092. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  51093. }
  51094. /**
  51095. * Executes a compute command for the given compute node.
  51096. *
  51097. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  51098. * @param {Node} computeNode - The compute node.
  51099. * @param {Array<BindGroup>} bindings - The bindings.
  51100. * @param {ComputePipeline} pipeline - The compute pipeline.
  51101. * @param {Array<number>|number} [dispatchSizeOrCount=null] - Array with [ x, y, z ] values for dispatch or a single number for the count.
  51102. */
  51103. compute( computeGroup, computeNode, bindings, pipeline, dispatchSizeOrCount = null ) {
  51104. const computeNodeData = this.get( computeNode );
  51105. const { passEncoderGPU } = this.get( computeGroup );
  51106. // pipeline
  51107. const pipelineGPU = this.get( pipeline ).pipeline;
  51108. this.pipelineUtils.setPipeline( passEncoderGPU, pipelineGPU );
  51109. // bind groups
  51110. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  51111. const bindGroup = bindings[ i ];
  51112. const bindingsData = this.get( bindGroup );
  51113. passEncoderGPU.setBindGroup( i, bindingsData.group );
  51114. }
  51115. let dispatchSize;
  51116. if ( dispatchSizeOrCount === null ) {
  51117. dispatchSizeOrCount = computeNode.count;
  51118. }
  51119. if ( typeof dispatchSizeOrCount === 'number' ) {
  51120. // If a single number is given, we calculate the dispatch size based on the workgroup size
  51121. const count = dispatchSizeOrCount;
  51122. if ( computeNodeData.dispatchSize === undefined || computeNodeData.count !== count ) {
  51123. // cache dispatch size to avoid recalculating it every time
  51124. computeNodeData.dispatchSize = [ 0, 1, 1 ];
  51125. computeNodeData.count = count;
  51126. const workgroupSize = computeNode.workgroupSize;
  51127. let size = workgroupSize[ 0 ];
  51128. for ( let i = 1; i < workgroupSize.length; i ++ )
  51129. size *= workgroupSize[ i ];
  51130. const dispatchCount = Math.ceil( count / size );
  51131. //
  51132. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  51133. dispatchSize = [ dispatchCount, 1, 1 ];
  51134. if ( dispatchCount > maxComputeWorkgroupsPerDimension ) {
  51135. dispatchSize[ 0 ] = Math.min( dispatchCount, maxComputeWorkgroupsPerDimension );
  51136. dispatchSize[ 1 ] = Math.ceil( dispatchCount / maxComputeWorkgroupsPerDimension );
  51137. }
  51138. computeNodeData.dispatchSize = dispatchSize;
  51139. }
  51140. dispatchSize = computeNodeData.dispatchSize;
  51141. } else {
  51142. dispatchSize = dispatchSizeOrCount;
  51143. }
  51144. //
  51145. passEncoderGPU.dispatchWorkgroups(
  51146. dispatchSize[ 0 ],
  51147. dispatchSize[ 1 ] || 1,
  51148. dispatchSize[ 2 ] || 1
  51149. );
  51150. }
  51151. /**
  51152. * This method is executed at the end of a compute call and
  51153. * finalizes work after compute tasks.
  51154. *
  51155. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  51156. */
  51157. finishCompute( computeGroup ) {
  51158. const groupData = this.get( computeGroup );
  51159. groupData.passEncoderGPU.end();
  51160. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  51161. }
  51162. /**
  51163. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  51164. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  51165. *
  51166. * @async
  51167. * @return {Promise} A Promise that resolves when synchronization has been finished.
  51168. */
  51169. async waitForGPU() {
  51170. await this.device.queue.onSubmittedWorkDone();
  51171. }
  51172. // render object
  51173. /**
  51174. * Executes a draw command for the given render object.
  51175. *
  51176. * @param {RenderObject} renderObject - The render object to draw.
  51177. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  51178. */
  51179. draw( renderObject, info ) {
  51180. const { object, material, context, pipeline } = renderObject;
  51181. const bindings = renderObject.getBindings();
  51182. const renderContextData = this.get( context );
  51183. const pipelineGPU = this.get( pipeline ).pipeline;
  51184. const index = renderObject.getIndex();
  51185. const hasIndex = ( index !== null );
  51186. const drawParams = renderObject.getDrawParameters();
  51187. if ( drawParams === null ) return;
  51188. // pipeline
  51189. const setPipelineAndBindings = ( passEncoderGPU, currentSets ) => {
  51190. // pipeline
  51191. this.pipelineUtils.setPipeline( passEncoderGPU, pipelineGPU );
  51192. currentSets.pipeline = pipelineGPU;
  51193. // bind groups
  51194. const currentBindingGroups = currentSets.bindingGroups;
  51195. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  51196. const bindGroup = bindings[ i ];
  51197. const bindingsData = this.get( bindGroup );
  51198. if ( currentBindingGroups[ bindGroup.index ] !== bindGroup.id ) {
  51199. passEncoderGPU.setBindGroup( bindGroup.index, bindingsData.group );
  51200. currentBindingGroups[ bindGroup.index ] = bindGroup.id;
  51201. }
  51202. }
  51203. // attributes
  51204. // index
  51205. if ( hasIndex === true ) {
  51206. if ( currentSets.index !== index ) {
  51207. const buffer = this.get( index ).buffer;
  51208. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  51209. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  51210. currentSets.index = index;
  51211. }
  51212. }
  51213. // vertex buffers
  51214. const vertexBuffers = renderObject.getVertexBuffers();
  51215. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  51216. const vertexBuffer = vertexBuffers[ i ];
  51217. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  51218. const buffer = this.get( vertexBuffer ).buffer;
  51219. passEncoderGPU.setVertexBuffer( i, buffer );
  51220. currentSets.attributes[ i ] = vertexBuffer;
  51221. }
  51222. }
  51223. // stencil
  51224. if ( context.stencil === true && material.stencilWrite === true && renderContextData.currentStencilRef !== material.stencilRef ) {
  51225. passEncoderGPU.setStencilReference( material.stencilRef );
  51226. renderContextData.currentStencilRef = material.stencilRef;
  51227. }
  51228. };
  51229. // Define draw function
  51230. const draw = ( passEncoderGPU, currentSets ) => {
  51231. setPipelineAndBindings( passEncoderGPU, currentSets );
  51232. if ( object.isBatchedMesh === true ) {
  51233. const starts = object._multiDrawStarts;
  51234. const counts = object._multiDrawCounts;
  51235. const drawCount = object._multiDrawCount;
  51236. const drawInstances = object._multiDrawInstances;
  51237. if ( drawInstances !== null ) {
  51238. // @deprecated, r174
  51239. warnOnce( 'THREE.WebGPUBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  51240. }
  51241. for ( let i = 0; i < drawCount; i ++ ) {
  51242. const count = drawInstances ? drawInstances[ i ] : 1;
  51243. const firstInstance = count > 1 ? 0 : i;
  51244. if ( hasIndex === true ) {
  51245. passEncoderGPU.drawIndexed( counts[ i ], count, starts[ i ] / index.array.BYTES_PER_ELEMENT, 0, firstInstance );
  51246. } else {
  51247. passEncoderGPU.draw( counts[ i ], count, starts[ i ], firstInstance );
  51248. }
  51249. info.update( object, counts[ i ], count );
  51250. }
  51251. } else if ( hasIndex === true ) {
  51252. const { vertexCount: indexCount, instanceCount, firstVertex: firstIndex } = drawParams;
  51253. const indirect = renderObject.getIndirect();
  51254. if ( indirect !== null ) {
  51255. const buffer = this.get( indirect ).buffer;
  51256. passEncoderGPU.drawIndexedIndirect( buffer, 0 );
  51257. } else {
  51258. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstIndex, 0, 0 );
  51259. }
  51260. info.update( object, indexCount, instanceCount );
  51261. } else {
  51262. const { vertexCount, instanceCount, firstVertex } = drawParams;
  51263. const indirect = renderObject.getIndirect();
  51264. if ( indirect !== null ) {
  51265. const buffer = this.get( indirect ).buffer;
  51266. passEncoderGPU.drawIndirect( buffer, 0 );
  51267. } else {
  51268. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  51269. }
  51270. info.update( object, vertexCount, instanceCount );
  51271. }
  51272. };
  51273. if ( renderObject.camera.isArrayCamera && renderObject.camera.cameras.length > 0 ) {
  51274. const cameraData = this.get( renderObject.camera );
  51275. const cameras = renderObject.camera.cameras;
  51276. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' );
  51277. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  51278. const bindingsData = this.get( cameraIndex );
  51279. const indexesGPU = [];
  51280. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  51281. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  51282. data[ 0 ] = i;
  51283. const bindGroupIndex = this.bindingUtils.createBindGroupIndex( data, bindingsData.layout );
  51284. indexesGPU.push( bindGroupIndex );
  51285. }
  51286. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  51287. }
  51288. const pixelRatio = this.renderer.getPixelRatio();
  51289. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  51290. const subCamera = cameras[ i ];
  51291. if ( object.layers.test( subCamera.layers ) ) {
  51292. const vp = subCamera.viewport;
  51293. let pass = renderContextData.currentPass;
  51294. let sets = renderContextData.currentSets;
  51295. if ( renderContextData.bundleEncoders ) {
  51296. const bundleEncoder = renderContextData.bundleEncoders[ i ];
  51297. const bundleSets = renderContextData.bundleSets[ i ];
  51298. pass = bundleEncoder;
  51299. sets = bundleSets;
  51300. }
  51301. if ( vp ) {
  51302. pass.setViewport(
  51303. Math.floor( vp.x * pixelRatio ),
  51304. Math.floor( vp.y * pixelRatio ),
  51305. Math.floor( vp.width * pixelRatio ),
  51306. Math.floor( vp.height * pixelRatio ),
  51307. context.viewportValue.minDepth,
  51308. context.viewportValue.maxDepth
  51309. );
  51310. }
  51311. // Set camera index binding for this layer
  51312. if ( cameraIndex && cameraData.indexesGPU ) {
  51313. pass.setBindGroup( cameraIndex.index, cameraData.indexesGPU[ i ] );
  51314. sets.bindingGroups[ cameraIndex.index ] = cameraIndex.id;
  51315. }
  51316. draw( pass, sets );
  51317. }
  51318. }
  51319. } else {
  51320. // Regular single camera rendering
  51321. if ( renderContextData.currentPass ) {
  51322. // Handle occlusion queries
  51323. if ( renderContextData.occlusionQuerySet !== undefined ) {
  51324. const lastObject = renderContextData.lastOcclusionObject;
  51325. if ( lastObject !== object ) {
  51326. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  51327. renderContextData.currentPass.endOcclusionQuery();
  51328. renderContextData.occlusionQueryIndex ++;
  51329. }
  51330. if ( object.occlusionTest === true ) {
  51331. renderContextData.currentPass.beginOcclusionQuery( renderContextData.occlusionQueryIndex );
  51332. renderContextData.occlusionQueryObjects[ renderContextData.occlusionQueryIndex ] = object;
  51333. }
  51334. renderContextData.lastOcclusionObject = object;
  51335. }
  51336. }
  51337. draw( renderContextData.currentPass, renderContextData.currentSets );
  51338. }
  51339. }
  51340. }
  51341. // cache key
  51342. /**
  51343. * Returns `true` if the render pipeline requires an update.
  51344. *
  51345. * @param {RenderObject} renderObject - The render object.
  51346. * @return {boolean} Whether the render pipeline requires an update or not.
  51347. */
  51348. needsRenderUpdate( renderObject ) {
  51349. const data = this.get( renderObject );
  51350. const { object, material } = renderObject;
  51351. const utils = this.utils;
  51352. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  51353. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  51354. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  51355. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  51356. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  51357. let needsUpdate = false;
  51358. if ( data.material !== material || data.materialVersion !== material.version ||
  51359. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  51360. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  51361. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  51362. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  51363. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  51364. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  51365. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  51366. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  51367. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  51368. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  51369. data.primitiveTopology !== primitiveTopology ||
  51370. data.clippingContextCacheKey !== renderObject.clippingContextCacheKey
  51371. ) {
  51372. data.material = material; data.materialVersion = material.version;
  51373. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  51374. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  51375. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  51376. data.colorWrite = material.colorWrite;
  51377. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  51378. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  51379. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  51380. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  51381. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  51382. data.sampleCount = sampleCount;
  51383. data.colorSpace = colorSpace;
  51384. data.colorFormat = colorFormat;
  51385. data.depthStencilFormat = depthStencilFormat;
  51386. data.primitiveTopology = primitiveTopology;
  51387. data.clippingContextCacheKey = renderObject.clippingContextCacheKey;
  51388. needsUpdate = true;
  51389. }
  51390. return needsUpdate;
  51391. }
  51392. /**
  51393. * Returns a cache key that is used to identify render pipelines.
  51394. *
  51395. * @param {RenderObject} renderObject - The render object.
  51396. * @return {string} The cache key.
  51397. */
  51398. getRenderCacheKey( renderObject ) {
  51399. const { object, material } = renderObject;
  51400. const utils = this.utils;
  51401. const renderContext = renderObject.context;
  51402. return [
  51403. material.transparent, material.blending, material.premultipliedAlpha,
  51404. material.blendSrc, material.blendDst, material.blendEquation,
  51405. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  51406. material.colorWrite,
  51407. material.depthWrite, material.depthTest, material.depthFunc,
  51408. material.stencilWrite, material.stencilFunc,
  51409. material.stencilFail, material.stencilZFail, material.stencilZPass,
  51410. material.stencilFuncMask, material.stencilWriteMask,
  51411. material.side,
  51412. utils.getSampleCountRenderContext( renderContext ),
  51413. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  51414. utils.getPrimitiveTopology( object, material ),
  51415. renderObject.getGeometryCacheKey(),
  51416. renderObject.clippingContextCacheKey
  51417. ].join();
  51418. }
  51419. // textures
  51420. /**
  51421. * Creates a GPU sampler for the given texture.
  51422. *
  51423. * @param {Texture} texture - The texture to create the sampler for.
  51424. */
  51425. createSampler( texture ) {
  51426. this.textureUtils.createSampler( texture );
  51427. }
  51428. /**
  51429. * Destroys the GPU sampler for the given texture.
  51430. *
  51431. * @param {Texture} texture - The texture to destroy the sampler for.
  51432. */
  51433. destroySampler( texture ) {
  51434. this.textureUtils.destroySampler( texture );
  51435. }
  51436. /**
  51437. * Creates a default texture for the given texture that can be used
  51438. * as a placeholder until the actual texture is ready for usage.
  51439. *
  51440. * @param {Texture} texture - The texture to create a default texture for.
  51441. */
  51442. createDefaultTexture( texture ) {
  51443. this.textureUtils.createDefaultTexture( texture );
  51444. }
  51445. /**
  51446. * Defines a texture on the GPU for the given texture object.
  51447. *
  51448. * @param {Texture} texture - The texture.
  51449. * @param {Object} [options={}] - Optional configuration parameter.
  51450. */
  51451. createTexture( texture, options ) {
  51452. this.textureUtils.createTexture( texture, options );
  51453. }
  51454. /**
  51455. * Uploads the updated texture data to the GPU.
  51456. *
  51457. * @param {Texture} texture - The texture.
  51458. * @param {Object} [options={}] - Optional configuration parameter.
  51459. */
  51460. updateTexture( texture, options ) {
  51461. this.textureUtils.updateTexture( texture, options );
  51462. }
  51463. /**
  51464. * Generates mipmaps for the given texture.
  51465. *
  51466. * @param {Texture} texture - The texture.
  51467. */
  51468. generateMipmaps( texture ) {
  51469. this.textureUtils.generateMipmaps( texture );
  51470. }
  51471. /**
  51472. * Destroys the GPU data for the given texture object.
  51473. *
  51474. * @param {Texture} texture - The texture.
  51475. */
  51476. destroyTexture( texture ) {
  51477. this.textureUtils.destroyTexture( texture );
  51478. }
  51479. /**
  51480. * Returns texture data as a typed array.
  51481. *
  51482. * @async
  51483. * @param {Texture} texture - The texture to copy.
  51484. * @param {number} x - The x coordinate of the copy origin.
  51485. * @param {number} y - The y coordinate of the copy origin.
  51486. * @param {number} width - The width of the copy.
  51487. * @param {number} height - The height of the copy.
  51488. * @param {number} faceIndex - The face index.
  51489. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  51490. */
  51491. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  51492. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  51493. }
  51494. /**
  51495. * Inits a time stamp query for the given render context.
  51496. *
  51497. * @param {RenderContext} renderContext - The render context.
  51498. * @param {Object} descriptor - The query descriptor.
  51499. */
  51500. initTimestampQuery( renderContext, descriptor ) {
  51501. if ( ! this.trackTimestamp ) return;
  51502. const type = renderContext.isComputeNode ? 'compute' : 'render';
  51503. if ( ! this.timestampQueryPool[ type ] ) {
  51504. // TODO: Variable maxQueries?
  51505. this.timestampQueryPool[ type ] = new WebGPUTimestampQueryPool( this.device, type, 2048 );
  51506. }
  51507. const timestampQueryPool = this.timestampQueryPool[ type ];
  51508. const baseOffset = timestampQueryPool.allocateQueriesForContext( renderContext );
  51509. descriptor.timestampWrites = {
  51510. querySet: timestampQueryPool.querySet,
  51511. beginningOfPassWriteIndex: baseOffset,
  51512. endOfPassWriteIndex: baseOffset + 1,
  51513. };
  51514. }
  51515. // node builder
  51516. /**
  51517. * Returns a node builder for the given render object.
  51518. *
  51519. * @param {RenderObject} object - The render object.
  51520. * @param {Renderer} renderer - The renderer.
  51521. * @return {WGSLNodeBuilder} The node builder.
  51522. */
  51523. createNodeBuilder( object, renderer ) {
  51524. return new WGSLNodeBuilder( object, renderer );
  51525. }
  51526. // program
  51527. /**
  51528. * Creates a shader program from the given programmable stage.
  51529. *
  51530. * @param {ProgrammableStage} program - The programmable stage.
  51531. */
  51532. createProgram( program ) {
  51533. const programGPU = this.get( program );
  51534. programGPU.module = {
  51535. module: this.device.createShaderModule( { code: program.code, label: program.stage + ( program.name !== '' ? `_${ program.name }` : '' ) } ),
  51536. entryPoint: 'main'
  51537. };
  51538. }
  51539. /**
  51540. * Destroys the shader program of the given programmable stage.
  51541. *
  51542. * @param {ProgrammableStage} program - The programmable stage.
  51543. */
  51544. destroyProgram( program ) {
  51545. this.delete( program );
  51546. }
  51547. // pipelines
  51548. /**
  51549. * Creates a render pipeline for the given render object.
  51550. *
  51551. * @param {RenderObject} renderObject - The render object.
  51552. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  51553. */
  51554. createRenderPipeline( renderObject, promises ) {
  51555. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  51556. }
  51557. /**
  51558. * Creates a compute pipeline for the given compute node.
  51559. *
  51560. * @param {ComputePipeline} computePipeline - The compute pipeline.
  51561. * @param {Array<BindGroup>} bindings - The bindings.
  51562. */
  51563. createComputePipeline( computePipeline, bindings ) {
  51564. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  51565. }
  51566. /**
  51567. * Prepares the state for encoding render bundles.
  51568. *
  51569. * @param {RenderContext} renderContext - The render context.
  51570. */
  51571. beginBundle( renderContext ) {
  51572. const renderContextData = this.get( renderContext );
  51573. renderContextData._currentPass = renderContextData.currentPass;
  51574. renderContextData._currentSets = renderContextData.currentSets;
  51575. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  51576. renderContextData.currentPass = this.pipelineUtils.createBundleEncoder( renderContext );
  51577. }
  51578. /**
  51579. * After processing render bundles this method finalizes related work.
  51580. *
  51581. * @param {RenderContext} renderContext - The render context.
  51582. * @param {RenderBundle} bundle - The render bundle.
  51583. */
  51584. finishBundle( renderContext, bundle ) {
  51585. const renderContextData = this.get( renderContext );
  51586. const bundleEncoder = renderContextData.currentPass;
  51587. const bundleGPU = bundleEncoder.finish();
  51588. this.get( bundle ).bundleGPU = bundleGPU;
  51589. // restore render pass state
  51590. renderContextData.currentSets = renderContextData._currentSets;
  51591. renderContextData.currentPass = renderContextData._currentPass;
  51592. }
  51593. /**
  51594. * Adds a render bundle to the render context data.
  51595. *
  51596. * @param {RenderContext} renderContext - The render context.
  51597. * @param {RenderBundle} bundle - The render bundle to add.
  51598. */
  51599. addBundle( renderContext, bundle ) {
  51600. const renderContextData = this.get( renderContext );
  51601. renderContextData.renderBundles.push( this.get( bundle ).bundleGPU );
  51602. }
  51603. // bindings
  51604. /**
  51605. * Creates bindings from the given bind group definition.
  51606. *
  51607. * @param {BindGroup} bindGroup - The bind group.
  51608. * @param {Array<BindGroup>} bindings - Array of bind groups.
  51609. * @param {number} cacheIndex - The cache index.
  51610. * @param {number} version - The version.
  51611. */
  51612. createBindings( bindGroup, bindings, cacheIndex, version ) {
  51613. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  51614. }
  51615. /**
  51616. * Updates the given bind group definition.
  51617. *
  51618. * @param {BindGroup} bindGroup - The bind group.
  51619. * @param {Array<BindGroup>} bindings - Array of bind groups.
  51620. * @param {number} cacheIndex - The cache index.
  51621. * @param {number} version - The version.
  51622. */
  51623. updateBindings( bindGroup, bindings, cacheIndex, version ) {
  51624. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  51625. }
  51626. /**
  51627. * Updates a buffer binding.
  51628. *
  51629. * @param {Buffer} binding - The buffer binding to update.
  51630. */
  51631. updateBinding( binding ) {
  51632. this.bindingUtils.updateBinding( binding );
  51633. }
  51634. // attributes
  51635. /**
  51636. * Creates the buffer of an indexed shader attribute.
  51637. *
  51638. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  51639. */
  51640. createIndexAttribute( attribute ) {
  51641. let usage = GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST;
  51642. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  51643. usage |= GPUBufferUsage.STORAGE;
  51644. }
  51645. this.attributeUtils.createAttribute( attribute, usage );
  51646. }
  51647. /**
  51648. * Creates the GPU buffer of a shader attribute.
  51649. *
  51650. * @param {BufferAttribute} attribute - The buffer attribute.
  51651. */
  51652. createAttribute( attribute ) {
  51653. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  51654. }
  51655. /**
  51656. * Creates the GPU buffer of a storage attribute.
  51657. *
  51658. * @param {BufferAttribute} attribute - The buffer attribute.
  51659. */
  51660. createStorageAttribute( attribute ) {
  51661. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  51662. }
  51663. /**
  51664. * Creates the GPU buffer of an indirect storage attribute.
  51665. *
  51666. * @param {BufferAttribute} attribute - The buffer attribute.
  51667. */
  51668. createIndirectStorageAttribute( attribute ) {
  51669. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  51670. }
  51671. /**
  51672. * Updates the GPU buffer of a shader attribute.
  51673. *
  51674. * @param {BufferAttribute} attribute - The buffer attribute to update.
  51675. */
  51676. updateAttribute( attribute ) {
  51677. this.attributeUtils.updateAttribute( attribute );
  51678. }
  51679. /**
  51680. * Destroys the GPU buffer of a shader attribute.
  51681. *
  51682. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  51683. */
  51684. destroyAttribute( attribute ) {
  51685. this.attributeUtils.destroyAttribute( attribute );
  51686. }
  51687. // canvas
  51688. /**
  51689. * Triggers an update of the default render pass descriptor.
  51690. */
  51691. updateSize() {
  51692. this.colorBuffer = this.textureUtils.getColorBuffer();
  51693. this.defaultRenderPassdescriptor = null;
  51694. }
  51695. // utils public
  51696. /**
  51697. * Returns the maximum anisotropy texture filtering value.
  51698. *
  51699. * @return {number} The maximum anisotropy texture filtering value.
  51700. */
  51701. getMaxAnisotropy() {
  51702. return 16;
  51703. }
  51704. /**
  51705. * Checks if the given feature is supported by the backend.
  51706. *
  51707. * @param {string} name - The feature's name.
  51708. * @return {boolean} Whether the feature is supported or not.
  51709. */
  51710. hasFeature( name ) {
  51711. return this.device.features.has( name );
  51712. }
  51713. /**
  51714. * Copies data of the given source texture to the given destination texture.
  51715. *
  51716. * @param {Texture} srcTexture - The source texture.
  51717. * @param {Texture} dstTexture - The destination texture.
  51718. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  51719. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  51720. * @param {number} [srcLevel=0] - The mipmap level to copy.
  51721. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  51722. */
  51723. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  51724. let dstX = 0;
  51725. let dstY = 0;
  51726. let dstZ = 0;
  51727. let srcX = 0;
  51728. let srcY = 0;
  51729. let srcZ = 0;
  51730. let srcWidth = srcTexture.image.width;
  51731. let srcHeight = srcTexture.image.height;
  51732. let srcDepth = 1;
  51733. if ( srcRegion !== null ) {
  51734. if ( srcRegion.isBox3 === true ) {
  51735. srcX = srcRegion.min.x;
  51736. srcY = srcRegion.min.y;
  51737. srcZ = srcRegion.min.z;
  51738. srcWidth = srcRegion.max.x - srcRegion.min.x;
  51739. srcHeight = srcRegion.max.y - srcRegion.min.y;
  51740. srcDepth = srcRegion.max.z - srcRegion.min.z;
  51741. } else {
  51742. // Assume it's a Box2
  51743. srcX = srcRegion.min.x;
  51744. srcY = srcRegion.min.y;
  51745. srcWidth = srcRegion.max.x - srcRegion.min.x;
  51746. srcHeight = srcRegion.max.y - srcRegion.min.y;
  51747. srcDepth = 1;
  51748. }
  51749. }
  51750. if ( dstPosition !== null ) {
  51751. dstX = dstPosition.x;
  51752. dstY = dstPosition.y;
  51753. dstZ = dstPosition.z || 0;
  51754. }
  51755. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  51756. const sourceGPU = this.get( srcTexture ).texture;
  51757. const destinationGPU = this.get( dstTexture ).texture;
  51758. encoder.copyTextureToTexture(
  51759. {
  51760. texture: sourceGPU,
  51761. mipLevel: srcLevel,
  51762. origin: { x: srcX, y: srcY, z: srcZ }
  51763. },
  51764. {
  51765. texture: destinationGPU,
  51766. mipLevel: dstLevel,
  51767. origin: { x: dstX, y: dstY, z: dstZ }
  51768. },
  51769. [
  51770. srcWidth,
  51771. srcHeight,
  51772. srcDepth
  51773. ]
  51774. );
  51775. this.device.queue.submit( [ encoder.finish() ] );
  51776. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  51777. this.textureUtils.generateMipmaps( dstTexture );
  51778. }
  51779. }
  51780. /**
  51781. * Copies the current bound framebuffer to the given texture.
  51782. *
  51783. * @param {Texture} texture - The destination texture.
  51784. * @param {RenderContext} renderContext - The render context.
  51785. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  51786. */
  51787. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  51788. const renderContextData = this.get( renderContext );
  51789. let sourceGPU = null;
  51790. if ( renderContext.renderTarget ) {
  51791. if ( texture.isDepthTexture ) {
  51792. sourceGPU = this.get( renderContext.depthTexture ).texture;
  51793. } else {
  51794. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  51795. }
  51796. } else {
  51797. if ( texture.isDepthTexture ) {
  51798. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  51799. } else {
  51800. sourceGPU = this.context.getCurrentTexture();
  51801. }
  51802. }
  51803. const destinationGPU = this.get( texture ).texture;
  51804. if ( sourceGPU.format !== destinationGPU.format ) {
  51805. console.error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  51806. return;
  51807. }
  51808. let encoder;
  51809. if ( renderContextData.currentPass ) {
  51810. renderContextData.currentPass.end();
  51811. encoder = renderContextData.encoder;
  51812. } else {
  51813. encoder = this.device.createCommandEncoder( { label: 'copyFramebufferToTexture_' + texture.id } );
  51814. }
  51815. encoder.copyTextureToTexture(
  51816. {
  51817. texture: sourceGPU,
  51818. origin: [ rectangle.x, rectangle.y, 0 ],
  51819. },
  51820. {
  51821. texture: destinationGPU
  51822. },
  51823. [
  51824. rectangle.z,
  51825. rectangle.w
  51826. ]
  51827. );
  51828. if ( renderContextData.currentPass ) {
  51829. const { descriptor } = renderContextData;
  51830. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  51831. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  51832. }
  51833. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  51834. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  51835. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  51836. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  51837. if ( renderContext.viewport ) {
  51838. this.updateViewport( renderContext );
  51839. }
  51840. if ( renderContext.scissor ) {
  51841. const { x, y, width, height } = renderContext.scissorValue;
  51842. renderContextData.currentPass.setScissorRect( x, y, width, height );
  51843. }
  51844. } else {
  51845. this.device.queue.submit( [ encoder.finish() ] );
  51846. }
  51847. if ( texture.generateMipmaps ) {
  51848. this.textureUtils.generateMipmaps( texture );
  51849. }
  51850. }
  51851. }
  51852. /**
  51853. * A IES version of {@link SpotLight}. Can only be used with {@link WebGPURenderer}.
  51854. *
  51855. * @augments SpotLight
  51856. */
  51857. class IESSpotLight extends SpotLight {
  51858. /**
  51859. * Constructs a new IES spot light.
  51860. *
  51861. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  51862. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  51863. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  51864. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  51865. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  51866. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  51867. */
  51868. constructor( color, intensity, distance, angle, penumbra, decay ) {
  51869. super( color, intensity, distance, angle, penumbra, decay );
  51870. /**
  51871. * TODO
  51872. *
  51873. * @type {?Texture}
  51874. * @default null
  51875. */
  51876. this.iesMap = null;
  51877. }
  51878. copy( source, recursive ) {
  51879. super.copy( source, recursive );
  51880. this.iesMap = source.iesMap;
  51881. return this;
  51882. }
  51883. }
  51884. /**
  51885. * A projector light version of {@link SpotLight}. Can only be used with {@link WebGPURenderer}.
  51886. *
  51887. * @augments SpotLight
  51888. */
  51889. class ProjectorLight extends SpotLight {
  51890. /**
  51891. * Constructs a new projector light.
  51892. *
  51893. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  51894. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  51895. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  51896. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  51897. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  51898. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  51899. */
  51900. constructor( color, intensity, distance, angle, penumbra, decay ) {
  51901. super( color, intensity, distance, angle, penumbra, decay );
  51902. /**
  51903. * Aspect ratio of the light. Set to `null` to use the texture aspect ratio.
  51904. *
  51905. * @type {number}
  51906. * @default null
  51907. */
  51908. this.aspect = null;
  51909. }
  51910. copy( source, recursive ) {
  51911. super.copy( source, recursive );
  51912. this.aspect = source.aspect;
  51913. return this;
  51914. }
  51915. }
  51916. /**
  51917. * This version of a node library represents the standard version
  51918. * used in {@link WebGPURenderer}. It maps lights, tone mapping
  51919. * techniques and materials to node-based implementations.
  51920. *
  51921. * @private
  51922. * @augments NodeLibrary
  51923. */
  51924. class StandardNodeLibrary extends NodeLibrary {
  51925. /**
  51926. * Constructs a new standard node library.
  51927. */
  51928. constructor() {
  51929. super();
  51930. this.addMaterial( MeshPhongNodeMaterial, 'MeshPhongMaterial' );
  51931. this.addMaterial( MeshStandardNodeMaterial, 'MeshStandardMaterial' );
  51932. this.addMaterial( MeshPhysicalNodeMaterial, 'MeshPhysicalMaterial' );
  51933. this.addMaterial( MeshToonNodeMaterial, 'MeshToonMaterial' );
  51934. this.addMaterial( MeshBasicNodeMaterial, 'MeshBasicMaterial' );
  51935. this.addMaterial( MeshLambertNodeMaterial, 'MeshLambertMaterial' );
  51936. this.addMaterial( MeshNormalNodeMaterial, 'MeshNormalMaterial' );
  51937. this.addMaterial( MeshMatcapNodeMaterial, 'MeshMatcapMaterial' );
  51938. this.addMaterial( LineBasicNodeMaterial, 'LineBasicMaterial' );
  51939. this.addMaterial( LineDashedNodeMaterial, 'LineDashedMaterial' );
  51940. this.addMaterial( PointsNodeMaterial, 'PointsMaterial' );
  51941. this.addMaterial( SpriteNodeMaterial, 'SpriteMaterial' );
  51942. this.addMaterial( ShadowNodeMaterial, 'ShadowMaterial' );
  51943. this.addLight( PointLightNode, PointLight );
  51944. this.addLight( DirectionalLightNode, DirectionalLight );
  51945. this.addLight( RectAreaLightNode, RectAreaLight );
  51946. this.addLight( SpotLightNode, SpotLight );
  51947. this.addLight( AmbientLightNode, AmbientLight );
  51948. this.addLight( HemisphereLightNode, HemisphereLight );
  51949. this.addLight( LightProbeNode, LightProbe );
  51950. this.addLight( IESSpotLightNode, IESSpotLight );
  51951. this.addLight( ProjectorLightNode, ProjectorLight );
  51952. this.addToneMapping( linearToneMapping, LinearToneMapping );
  51953. this.addToneMapping( reinhardToneMapping, ReinhardToneMapping );
  51954. this.addToneMapping( cineonToneMapping, CineonToneMapping );
  51955. this.addToneMapping( acesFilmicToneMapping, ACESFilmicToneMapping );
  51956. this.addToneMapping( agxToneMapping, AgXToneMapping );
  51957. this.addToneMapping( neutralToneMapping, NeutralToneMapping );
  51958. }
  51959. }
  51960. /*
  51961. const debugHandler = {
  51962. get: function ( target, name ) {
  51963. // Add |update
  51964. if ( /^(create|destroy)/.test( name ) ) console.log( 'WebGPUBackend.' + name );
  51965. return target[ name ];
  51966. }
  51967. };
  51968. */
  51969. /**
  51970. * This renderer is the new alternative of `WebGLRenderer`. `WebGPURenderer` has the ability
  51971. * to target different backends. By default, the renderer tries to use a WebGPU backend if the
  51972. * browser supports WebGPU. If not, `WebGPURenderer` falls backs to a WebGL 2 backend.
  51973. *
  51974. * @augments Renderer
  51975. */
  51976. class WebGPURenderer extends Renderer {
  51977. /**
  51978. * WebGPURenderer options.
  51979. *
  51980. * @typedef {Object} WebGPURenderer~Options
  51981. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  51982. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  51983. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  51984. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  51985. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  51986. * @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.
  51987. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  51988. * @property {boolean} [multiview=false] - If set to `true`, the renderer will use multiview during WebXR rendering if supported.
  51989. * @property {number} [outputType=undefined] - Texture type for output to canvas. By default, device's preferred format is used; other formats may incur overhead.
  51990. * @property {number} [colorBufferType=HalfFloatType] - Defines the type of color buffers. The default `HalfFloatType` is recommend for best
  51991. * quality. To save memory and bandwidth, `UnsignedByteType` might be used. This will reduce rendering quality though.
  51992. */
  51993. /**
  51994. * Constructs a new WebGPU renderer.
  51995. *
  51996. * @param {WebGPURenderer~Options} [parameters] - The configuration parameter.
  51997. */
  51998. constructor( parameters = {} ) {
  51999. let BackendClass;
  52000. if ( parameters.forceWebGL ) {
  52001. BackendClass = WebGLBackend;
  52002. } else {
  52003. BackendClass = WebGPUBackend;
  52004. parameters.getFallback = () => {
  52005. console.warn( 'THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  52006. return new WebGLBackend( parameters );
  52007. };
  52008. }
  52009. const backend = new BackendClass( parameters );
  52010. //super( new Proxy( backend, debugHandler ) );
  52011. super( backend, parameters );
  52012. /**
  52013. * The generic default value is overwritten with the
  52014. * standard node library for type mapping.
  52015. *
  52016. * @type {StandardNodeLibrary}
  52017. */
  52018. this.library = new StandardNodeLibrary();
  52019. /**
  52020. * This flag can be used for type testing.
  52021. *
  52022. * @type {boolean}
  52023. * @readonly
  52024. * @default true
  52025. */
  52026. this.isWebGPURenderer = true;
  52027. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  52028. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  52029. }
  52030. }
  52031. }
  52032. /**
  52033. * A specialized group which enables applications access to the
  52034. * Render Bundle API of WebGPU. The group with all its descendant nodes
  52035. * are considered as one render bundle and processed as such by
  52036. * the renderer.
  52037. *
  52038. * This module is only fully supported by `WebGPURenderer` with a WebGPU backend.
  52039. * With a WebGL backend, the group can technically be rendered but without
  52040. * any performance improvements.
  52041. *
  52042. * @augments Group
  52043. */
  52044. class BundleGroup extends Group {
  52045. /**
  52046. * Constructs a new bundle group.
  52047. */
  52048. constructor() {
  52049. super();
  52050. /**
  52051. * This flag can be used for type testing.
  52052. *
  52053. * @type {boolean}
  52054. * @readonly
  52055. * @default true
  52056. */
  52057. this.isBundleGroup = true;
  52058. /**
  52059. * This property is only relevant for detecting types
  52060. * during serialization/deserialization. It should always
  52061. * match the class name.
  52062. *
  52063. * @type {string}
  52064. * @readonly
  52065. * @default 'BundleGroup'
  52066. */
  52067. this.type = 'BundleGroup';
  52068. /**
  52069. * Whether the bundle is static or not. When set to `true`, the structure
  52070. * is assumed to be static and does not change. E.g. no new objects are
  52071. * added to the group
  52072. *
  52073. * If a change is required, an update can still be forced by setting the
  52074. * `needsUpdate` flag to `true`.
  52075. *
  52076. * @type {boolean}
  52077. * @default true
  52078. */
  52079. this.static = true;
  52080. /**
  52081. * The bundle group's version.
  52082. *
  52083. * @type {number}
  52084. * @readonly
  52085. * @default 0
  52086. */
  52087. this.version = 0;
  52088. }
  52089. /**
  52090. * Set this property to `true` when the bundle group has changed.
  52091. *
  52092. * @type {boolean}
  52093. * @default false
  52094. * @param {boolean} value
  52095. */
  52096. set needsUpdate( value ) {
  52097. if ( value === true ) this.version ++;
  52098. }
  52099. }
  52100. /**
  52101. * This module is responsible to manage the post processing setups in apps.
  52102. * You usually create a single instance of this class and use it to define
  52103. * the output of your post processing effect chain.
  52104. * ```js
  52105. * const postProcessing = new PostProcessing( renderer );
  52106. *
  52107. * const scenePass = pass( scene, camera );
  52108. *
  52109. * postProcessing.outputNode = scenePass;
  52110. * ```
  52111. *
  52112. * Note: This module can only be used with `WebGPURenderer`.
  52113. */
  52114. class PostProcessing {
  52115. /**
  52116. * Constructs a new post processing management module.
  52117. *
  52118. * @param {Renderer} renderer - A reference to the renderer.
  52119. * @param {Node<vec4>} outputNode - An optional output node.
  52120. */
  52121. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  52122. /**
  52123. * A reference to the renderer.
  52124. *
  52125. * @type {Renderer}
  52126. */
  52127. this.renderer = renderer;
  52128. /**
  52129. * A node which defines the final output of the post
  52130. * processing. This is usually the last node in a chain
  52131. * of effect nodes.
  52132. *
  52133. * @type {Node<vec4>}
  52134. */
  52135. this.outputNode = outputNode;
  52136. /**
  52137. * Whether the default output tone mapping and color
  52138. * space transformation should be enabled or not.
  52139. *
  52140. * It is enabled by default by it must be disabled when
  52141. * effects must be executed after tone mapping and color
  52142. * space conversion. A typical example is FXAA which
  52143. * requires sRGB input.
  52144. *
  52145. * When set to `false`, the app must control the output
  52146. * transformation with `RenderOutputNode`.
  52147. *
  52148. * ```js
  52149. * const outputPass = renderOutput( scenePass );
  52150. * ```
  52151. *
  52152. * @type {boolean}
  52153. */
  52154. this.outputColorTransform = true;
  52155. /**
  52156. * Must be set to `true` when the output node changes.
  52157. *
  52158. * @type {Node<vec4>}
  52159. */
  52160. this.needsUpdate = true;
  52161. const material = new NodeMaterial();
  52162. material.name = 'PostProcessing';
  52163. /**
  52164. * The full screen quad that is used to render
  52165. * the effects.
  52166. *
  52167. * @private
  52168. * @type {QuadMesh}
  52169. */
  52170. this._quadMesh = new QuadMesh( material );
  52171. /**
  52172. * The context of the post processing stack.
  52173. *
  52174. * @private
  52175. * @type {?Object}
  52176. * @default null
  52177. */
  52178. this._context = null;
  52179. }
  52180. /**
  52181. * When `PostProcessing` is used to apply post processing effects,
  52182. * the application must use this version of `render()` inside
  52183. * its animation loop (not the one from the renderer).
  52184. */
  52185. render() {
  52186. const renderer = this.renderer;
  52187. this._update();
  52188. if ( this._context.onBeforePostProcessing !== null ) this._context.onBeforePostProcessing();
  52189. const toneMapping = renderer.toneMapping;
  52190. const outputColorSpace = renderer.outputColorSpace;
  52191. renderer.toneMapping = NoToneMapping;
  52192. renderer.outputColorSpace = LinearSRGBColorSpace;
  52193. //
  52194. const currentXR = renderer.xr.enabled;
  52195. renderer.xr.enabled = false;
  52196. this._quadMesh.render( renderer );
  52197. renderer.xr.enabled = currentXR;
  52198. //
  52199. renderer.toneMapping = toneMapping;
  52200. renderer.outputColorSpace = outputColorSpace;
  52201. if ( this._context.onAfterPostProcessing !== null ) this._context.onAfterPostProcessing();
  52202. }
  52203. /**
  52204. * Returns the current context of the post processing stack.
  52205. *
  52206. * @readonly
  52207. * @type {?Object}
  52208. */
  52209. get context() {
  52210. return this._context;
  52211. }
  52212. /**
  52213. * Frees internal resources.
  52214. */
  52215. dispose() {
  52216. this._quadMesh.material.dispose();
  52217. }
  52218. /**
  52219. * Updates the state of the module.
  52220. *
  52221. * @private
  52222. */
  52223. _update() {
  52224. if ( this.needsUpdate === true ) {
  52225. const renderer = this.renderer;
  52226. const toneMapping = renderer.toneMapping;
  52227. const outputColorSpace = renderer.outputColorSpace;
  52228. const context = {
  52229. postProcessing: this,
  52230. onBeforePostProcessing: null,
  52231. onAfterPostProcessing: null
  52232. };
  52233. let outputNode = this.outputNode;
  52234. if ( this.outputColorTransform === true ) {
  52235. outputNode = outputNode.context( context );
  52236. outputNode = renderOutput( outputNode, toneMapping, outputColorSpace );
  52237. } else {
  52238. context.toneMapping = toneMapping;
  52239. context.outputColorSpace = outputColorSpace;
  52240. outputNode = outputNode.context( context );
  52241. }
  52242. this._context = context;
  52243. this._quadMesh.material.fragmentNode = outputNode;
  52244. this._quadMesh.material.needsUpdate = true;
  52245. this.needsUpdate = false;
  52246. }
  52247. }
  52248. /**
  52249. * When `PostProcessing` is used to apply post processing effects,
  52250. * the application must use this version of `renderAsync()` inside
  52251. * its animation loop (not the one from the renderer).
  52252. *
  52253. * @async
  52254. * @return {Promise} A Promise that resolves when the render has been finished.
  52255. */
  52256. async renderAsync() {
  52257. this._update();
  52258. if ( this._context.onBeforePostProcessing !== null ) this._context.onBeforePostProcessing();
  52259. const renderer = this.renderer;
  52260. const toneMapping = renderer.toneMapping;
  52261. const outputColorSpace = renderer.outputColorSpace;
  52262. renderer.toneMapping = NoToneMapping;
  52263. renderer.outputColorSpace = LinearSRGBColorSpace;
  52264. //
  52265. const currentXR = renderer.xr.enabled;
  52266. renderer.xr.enabled = false;
  52267. await this._quadMesh.renderAsync( renderer );
  52268. renderer.xr.enabled = currentXR;
  52269. //
  52270. renderer.toneMapping = toneMapping;
  52271. renderer.outputColorSpace = outputColorSpace;
  52272. if ( this._context.onAfterPostProcessing !== null ) this._context.onAfterPostProcessing();
  52273. }
  52274. }
  52275. /**
  52276. * This special type of texture is intended for compute shaders.
  52277. * It can be used to compute the data of a texture with a compute shader.
  52278. *
  52279. * Note: This type of texture can only be used with `WebGPURenderer`
  52280. * and a WebGPU backend.
  52281. *
  52282. * @augments Texture
  52283. */
  52284. class StorageTexture extends Texture {
  52285. /**
  52286. * Constructs a new storage texture.
  52287. *
  52288. * @param {number} [width=1] - The storage texture's width.
  52289. * @param {number} [height=1] - The storage texture's height.
  52290. */
  52291. constructor( width = 1, height = 1 ) {
  52292. super();
  52293. /**
  52294. * The image object which just represents the texture's dimension.
  52295. *
  52296. * @type {{width: number, height: number}}
  52297. */
  52298. this.image = { width, height };
  52299. /**
  52300. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  52301. *
  52302. * @type {number}
  52303. */
  52304. this.magFilter = LinearFilter;
  52305. /**
  52306. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  52307. *
  52308. * @type {number}
  52309. */
  52310. this.minFilter = LinearFilter;
  52311. /**
  52312. * This flag can be used for type testing.
  52313. *
  52314. * @type {boolean}
  52315. * @readonly
  52316. * @default true
  52317. */
  52318. this.isStorageTexture = true;
  52319. }
  52320. }
  52321. /**
  52322. * This special type of texture is intended for compute shaders.
  52323. * It can be used to compute the data of a texture with a compute shader.
  52324. *
  52325. * Note: This type of texture can only be used with `WebGPURenderer`
  52326. * and a WebGPU backend.
  52327. *
  52328. * @augments Texture
  52329. */
  52330. class Storage3DTexture extends Texture {
  52331. /**
  52332. * Constructs a new storage texture.
  52333. *
  52334. * @param {number} [width=1] - The storage texture's width.
  52335. * @param {number} [height=1] - The storage texture's height.
  52336. * @param {number} [depth=1] - The storage texture's depth.
  52337. */
  52338. constructor( width = 1, height = 1, depth = 1 ) {
  52339. super();
  52340. //inherited from texture. Must be false for 3DTexture
  52341. this.isArrayTexture = false;
  52342. /**
  52343. * The image object which just represents the texture's dimension.
  52344. *
  52345. * @type {{width: number, height: number, depth: number}}
  52346. */
  52347. this.image = { width, height, depth };
  52348. /**
  52349. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  52350. *
  52351. * @type {number}
  52352. */
  52353. this.magFilter = LinearFilter;
  52354. /**
  52355. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  52356. *
  52357. * @type {number}
  52358. */
  52359. this.minFilter = LinearFilter;
  52360. /**
  52361. * This defines how the texture is wrapped in the depth direction and corresponds to
  52362. * *W* in UVW mapping.
  52363. *
  52364. * @type {number}
  52365. */
  52366. this.wrapR = ClampToEdgeWrapping;
  52367. /**
  52368. * This flag can be used for type testing.
  52369. *
  52370. * @type {boolean}
  52371. * @readonly
  52372. * @default true
  52373. */
  52374. this.isStorageTexture = true;
  52375. /**
  52376. * Indicates whether this texture is a 3D texture.
  52377. *
  52378. * @type {boolean}
  52379. *
  52380. */
  52381. this.is3DTexture = true;
  52382. }
  52383. }
  52384. /**
  52385. * This special type of texture is intended for compute shaders.
  52386. * It can be used to compute the data of a texture with a compute shader.
  52387. *
  52388. * Note: This type of texture can only be used with `WebGPURenderer`
  52389. * and a WebGPU backend.
  52390. *
  52391. * @augments Texture
  52392. */
  52393. class StorageArrayTexture extends Texture {
  52394. /**
  52395. * Constructs a new storage texture.
  52396. *
  52397. * @param {number} [width=1] - The storage texture's width.
  52398. * @param {number} [height=1] - The storage texture's height.
  52399. * @param {number} [depth=1] - The storage texture's depth.
  52400. */
  52401. constructor( width = 1, height = 1, depth = 1 ) {
  52402. super();
  52403. //inherited from texture
  52404. this.isArrayTexture = true;
  52405. /**
  52406. * The image object which just represents the texture's dimension.
  52407. *
  52408. * @type {{width: number, height: number, depth: number}}
  52409. */
  52410. this.image = { width, height, depth };
  52411. /**
  52412. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  52413. *
  52414. * @type {number}
  52415. */
  52416. this.magFilter = LinearFilter;
  52417. /**
  52418. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  52419. *
  52420. * @type {number}
  52421. */
  52422. this.minFilter = LinearFilter;
  52423. /**
  52424. * This flag can be used for type testing.
  52425. *
  52426. * @type {boolean}
  52427. * @readonly
  52428. * @default true
  52429. */
  52430. this.isStorageTexture = true;
  52431. }
  52432. }
  52433. /**
  52434. * This special type of buffer attribute is intended for compute shaders.
  52435. * It can be used to encode draw parameters for indirect draw calls.
  52436. *
  52437. * Note: This type of buffer attribute can only be used with `WebGPURenderer`
  52438. * and a WebGPU backend.
  52439. *
  52440. * @augments StorageBufferAttribute
  52441. */
  52442. class IndirectStorageBufferAttribute extends StorageBufferAttribute {
  52443. /**
  52444. * Constructs a new storage buffer attribute.
  52445. *
  52446. * @param {number|Uint32Array} count - The item count. It is also valid to pass a `Uint32Array` as an argument.
  52447. * The subsequent parameter is then obsolete.
  52448. * @param {number} itemSize - The item size.
  52449. */
  52450. constructor( count, itemSize ) {
  52451. super( count, itemSize, Uint32Array );
  52452. /**
  52453. * This flag can be used for type testing.
  52454. *
  52455. * @type {boolean}
  52456. * @readonly
  52457. * @default true
  52458. */
  52459. this.isIndirectStorageBufferAttribute = true;
  52460. }
  52461. }
  52462. /**
  52463. * A loader for loading node objects in the three.js JSON Object/Scene format.
  52464. *
  52465. * @augments Loader
  52466. */
  52467. class NodeLoader extends Loader {
  52468. /**
  52469. * Constructs a new node loader.
  52470. *
  52471. * @param {LoadingManager} [manager] - A reference to a loading manager.
  52472. */
  52473. constructor( manager ) {
  52474. super( manager );
  52475. /**
  52476. * Represents a dictionary of textures.
  52477. *
  52478. * @type {Object<string,Texture>}
  52479. */
  52480. this.textures = {};
  52481. /**
  52482. * Represents a dictionary of node types.
  52483. *
  52484. * @type {Object<string,Node.constructor>}
  52485. */
  52486. this.nodes = {};
  52487. }
  52488. /**
  52489. * Loads the node definitions from the given URL.
  52490. *
  52491. * @param {string} url - The path/URL of the file to be loaded.
  52492. * @param {Function} onLoad - Will be called when load completes.
  52493. * @param {Function} onProgress - Will be called while load progresses.
  52494. * @param {Function} onError - Will be called when errors are thrown during the loading process.
  52495. */
  52496. load( url, onLoad, onProgress, onError ) {
  52497. const loader = new FileLoader( this.manager );
  52498. loader.setPath( this.path );
  52499. loader.setRequestHeader( this.requestHeader );
  52500. loader.setWithCredentials( this.withCredentials );
  52501. loader.load( url, ( text ) => {
  52502. try {
  52503. onLoad( this.parse( JSON.parse( text ) ) );
  52504. } catch ( e ) {
  52505. if ( onError ) {
  52506. onError( e );
  52507. } else {
  52508. console.error( e );
  52509. }
  52510. this.manager.itemError( url );
  52511. }
  52512. }, onProgress, onError );
  52513. }
  52514. /**
  52515. * Parse the node dependencies for the loaded node.
  52516. *
  52517. * @param {Array<Object>} [json] - The JSON definition
  52518. * @return {Object<string,Node>} A dictionary with node dependencies.
  52519. */
  52520. parseNodes( json ) {
  52521. const nodes = {};
  52522. if ( json !== undefined ) {
  52523. for ( const nodeJSON of json ) {
  52524. const { uuid, type } = nodeJSON;
  52525. nodes[ uuid ] = this.createNodeFromType( type );
  52526. nodes[ uuid ].uuid = uuid;
  52527. }
  52528. const meta = { nodes, textures: this.textures };
  52529. for ( const nodeJSON of json ) {
  52530. nodeJSON.meta = meta;
  52531. const node = nodes[ nodeJSON.uuid ];
  52532. node.deserialize( nodeJSON );
  52533. delete nodeJSON.meta;
  52534. }
  52535. }
  52536. return nodes;
  52537. }
  52538. /**
  52539. * Parses the node from the given JSON.
  52540. *
  52541. * @param {Object} json - The JSON definition
  52542. * @param {string} json.type - The node type.
  52543. * @param {string} json.uuid - The node UUID.
  52544. * @param {Array<Object>} [json.nodes] - The node dependencies.
  52545. * @param {Object} [json.meta] - The meta data.
  52546. * @return {Node} The parsed node.
  52547. */
  52548. parse( json ) {
  52549. const node = this.createNodeFromType( json.type );
  52550. node.uuid = json.uuid;
  52551. const nodes = this.parseNodes( json.nodes );
  52552. const meta = { nodes, textures: this.textures };
  52553. json.meta = meta;
  52554. node.deserialize( json );
  52555. delete json.meta;
  52556. return node;
  52557. }
  52558. /**
  52559. * Defines the dictionary of textures.
  52560. *
  52561. * @param {Object<string,Texture>} value - The texture library defines as `<uuid,texture>`.
  52562. * @return {NodeLoader} A reference to this loader.
  52563. */
  52564. setTextures( value ) {
  52565. this.textures = value;
  52566. return this;
  52567. }
  52568. /**
  52569. * Defines the dictionary of node types.
  52570. *
  52571. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  52572. * @return {NodeLoader} A reference to this loader.
  52573. */
  52574. setNodes( value ) {
  52575. this.nodes = value;
  52576. return this;
  52577. }
  52578. /**
  52579. * Creates a node object from the given type.
  52580. *
  52581. * @param {string} type - The node type.
  52582. * @return {Node} The created node instance.
  52583. */
  52584. createNodeFromType( type ) {
  52585. if ( this.nodes[ type ] === undefined ) {
  52586. console.error( 'THREE.NodeLoader: Node type not found:', type );
  52587. return float();
  52588. }
  52589. return nodeObject( new this.nodes[ type ]() );
  52590. }
  52591. }
  52592. /**
  52593. * A special type of material loader for loading node materials.
  52594. *
  52595. * @augments MaterialLoader
  52596. */
  52597. class NodeMaterialLoader extends MaterialLoader {
  52598. /**
  52599. * Constructs a new node material loader.
  52600. *
  52601. * @param {LoadingManager} [manager] - A reference to a loading manager.
  52602. */
  52603. constructor( manager ) {
  52604. super( manager );
  52605. /**
  52606. * Represents a dictionary of node types.
  52607. *
  52608. * @type {Object<string,Node.constructor>}
  52609. */
  52610. this.nodes = {};
  52611. /**
  52612. * Represents a dictionary of node material types.
  52613. *
  52614. * @type {Object<string,NodeMaterial.constructor>}
  52615. */
  52616. this.nodeMaterials = {};
  52617. }
  52618. /**
  52619. * Parses the node material from the given JSON.
  52620. *
  52621. * @param {Object} json - The JSON definition
  52622. * @return {NodeMaterial}. The parsed material.
  52623. */
  52624. parse( json ) {
  52625. const material = super.parse( json );
  52626. const nodes = this.nodes;
  52627. const inputNodes = json.inputNodes;
  52628. for ( const property in inputNodes ) {
  52629. const uuid = inputNodes[ property ];
  52630. material[ property ] = nodes[ uuid ];
  52631. }
  52632. return material;
  52633. }
  52634. /**
  52635. * Defines the dictionary of node types.
  52636. *
  52637. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  52638. * @return {NodeLoader} A reference to this loader.
  52639. */
  52640. setNodes( value ) {
  52641. this.nodes = value;
  52642. return this;
  52643. }
  52644. /**
  52645. * Defines the dictionary of node material types.
  52646. *
  52647. * @param {Object<string,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  52648. * @return {NodeLoader} A reference to this loader.
  52649. */
  52650. setNodeMaterials( value ) {
  52651. this.nodeMaterials = value;
  52652. return this;
  52653. }
  52654. /**
  52655. * Creates a node material from the given type.
  52656. *
  52657. * @param {string} type - The node material type.
  52658. * @return {Node} The created node material instance.
  52659. */
  52660. createMaterialFromType( type ) {
  52661. const materialClass = this.nodeMaterials[ type ];
  52662. if ( materialClass !== undefined ) {
  52663. return new materialClass();
  52664. }
  52665. return super.createMaterialFromType( type );
  52666. }
  52667. }
  52668. /**
  52669. * A special type of object loader for loading 3D objects using
  52670. * node materials.
  52671. *
  52672. * @augments ObjectLoader
  52673. */
  52674. class NodeObjectLoader extends ObjectLoader {
  52675. /**
  52676. * Constructs a new node object loader.
  52677. *
  52678. * @param {LoadingManager} [manager] - A reference to a loading manager.
  52679. */
  52680. constructor( manager ) {
  52681. super( manager );
  52682. /**
  52683. * Represents a dictionary of node types.
  52684. *
  52685. * @type {Object<string,Node.constructor>}
  52686. */
  52687. this.nodes = {};
  52688. /**
  52689. * Represents a dictionary of node material types.
  52690. *
  52691. * @type {Object<string,NodeMaterial.constructor>}
  52692. */
  52693. this.nodeMaterials = {};
  52694. /**
  52695. * A reference to hold the `nodes` JSON property.
  52696. *
  52697. * @private
  52698. * @type {?Object[]}
  52699. */
  52700. this._nodesJSON = null;
  52701. }
  52702. /**
  52703. * Defines the dictionary of node types.
  52704. *
  52705. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  52706. * @return {NodeObjectLoader} A reference to this loader.
  52707. */
  52708. setNodes( value ) {
  52709. this.nodes = value;
  52710. return this;
  52711. }
  52712. /**
  52713. * Defines the dictionary of node material types.
  52714. *
  52715. * @param {Object<string,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  52716. * @return {NodeObjectLoader} A reference to this loader.
  52717. */
  52718. setNodeMaterials( value ) {
  52719. this.nodeMaterials = value;
  52720. return this;
  52721. }
  52722. /**
  52723. * Parses the node objects from the given JSON.
  52724. *
  52725. * @param {Object} json - The JSON definition
  52726. * @param {Function} onLoad - The onLoad callback function.
  52727. * @return {Object3D}. The parsed 3D object.
  52728. */
  52729. parse( json, onLoad ) {
  52730. this._nodesJSON = json.nodes;
  52731. const data = super.parse( json, onLoad );
  52732. this._nodesJSON = null; // dispose
  52733. return data;
  52734. }
  52735. /**
  52736. * Parses the node objects from the given JSON and textures.
  52737. *
  52738. * @param {Object[]} json - The JSON definition
  52739. * @param {Object<string,Texture>} textures - The texture library.
  52740. * @return {Object<string,Node>}. The parsed nodes.
  52741. */
  52742. parseNodes( json, textures ) {
  52743. if ( json !== undefined ) {
  52744. const loader = new NodeLoader();
  52745. loader.setNodes( this.nodes );
  52746. loader.setTextures( textures );
  52747. return loader.parseNodes( json );
  52748. }
  52749. return {};
  52750. }
  52751. /**
  52752. * Parses the node objects from the given JSON and textures.
  52753. *
  52754. * @param {Object} json - The JSON definition
  52755. * @param {Object<string,Texture>} textures - The texture library.
  52756. * @return {Object<string,NodeMaterial>}. The parsed materials.
  52757. */
  52758. parseMaterials( json, textures ) {
  52759. const materials = {};
  52760. if ( json !== undefined ) {
  52761. const nodes = this.parseNodes( this._nodesJSON, textures );
  52762. const loader = new NodeMaterialLoader();
  52763. loader.setTextures( textures );
  52764. loader.setNodes( nodes );
  52765. loader.setNodeMaterials( this.nodeMaterials );
  52766. for ( let i = 0, l = json.length; i < l; i ++ ) {
  52767. const data = json[ i ];
  52768. materials[ data.uuid ] = loader.parse( data );
  52769. }
  52770. }
  52771. return materials;
  52772. }
  52773. }
  52774. /**
  52775. * In earlier three.js versions, clipping was defined globally
  52776. * on the renderer or on material level. This special version of
  52777. * `THREE.Group` allows to encode the clipping state into the scene
  52778. * graph. Meaning if you create an instance of this group, all
  52779. * descendant 3D objects will be affected by the respective clipping
  52780. * planes.
  52781. *
  52782. * Note: `ClippingGroup` can only be used with `WebGPURenderer`.
  52783. *
  52784. * @augments Group
  52785. */
  52786. class ClippingGroup extends Group {
  52787. /**
  52788. * Constructs a new clipping group.
  52789. */
  52790. constructor() {
  52791. super();
  52792. /**
  52793. * This flag can be used for type testing.
  52794. *
  52795. * @type {boolean}
  52796. * @readonly
  52797. * @default true
  52798. */
  52799. this.isClippingGroup = true;
  52800. /**
  52801. * An array with clipping planes.
  52802. *
  52803. * @type {Array<Plane>}
  52804. */
  52805. this.clippingPlanes = [];
  52806. /**
  52807. * Whether clipping should be enabled or not.
  52808. *
  52809. * @type {boolean}
  52810. * @default true
  52811. */
  52812. this.enabled = true;
  52813. /**
  52814. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  52815. *
  52816. * @type {boolean}
  52817. * @default false
  52818. */
  52819. this.clipIntersection = false;
  52820. /**
  52821. * Whether shadows should be clipped or not.
  52822. *
  52823. * @type {boolean}
  52824. * @default false
  52825. */
  52826. this.clipShadows = false;
  52827. }
  52828. }
  52829. 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, 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, Material, MaterialLoader, MaterialNode, MaterialReferenceNode, MathUtils, Matrix2, Matrix3, Matrix4, MaxEquation, MaxMipLevelNode, MemberNode, Mesh, MeshBasicMaterial, MeshBasicNodeMaterial, MeshLambertMaterial, MeshLambertNodeMaterial, MeshMatcapMaterial, MeshMatcapNodeMaterial, MeshNormalMaterial, MeshNormalNodeMaterial, MeshPhongMaterial, MeshPhongNodeMaterial, MeshPhysicalMaterial, MeshPhysicalNodeMaterial, MeshSSSNodeMaterial, MeshStandardMaterial, MeshStandardNodeMaterial, MeshToonMaterial, MeshToonNodeMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, ModelNode, MorphNode, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeutralToneMapping, NeverCompare, NeverDepth, NeverStencilFunc, NoBlending, NoColorSpace, NoToneMapping, Node, NodeAccess, NodeAttribute, NodeBuilder, NodeCache, NodeCode, NodeFrame, NodeFunctionInput, NodeLoader, NodeMaterial, NodeMaterialLoader, NodeMaterialObserver, NodeObjectLoader, NodeShaderStage, NodeType, NodeUniform, NodeUpdateType, NodeUtils, NodeVar, NodeVarying, NormalBlending, NormalMapNode, NotEqualCompare, NotEqualDepth, NotEqualStencilFunc, Object3D, Object3DNode, ObjectLoader, ObjectSpaceNormalMap, OneFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OrthographicCamera, OutputStructNode, PCFShadowMap, PMREMGenerator, PMREMNode, ParameterNode, PassNode, PerspectiveCamera, PhongLightingModel, PhysicalLightingModel, Plane, PlaneGeometry, PointLight, PointLightNode, PointUVNode, PointsMaterial, PointsNodeMaterial, PostProcessing, PosterizeNode, ProjectorLight, ProjectorLightNode, PropertyNode, QuadMesh, Quaternion, RED_GREEN_RGTC2_Format, RED_RGTC1_Format, REVISION, RGBAFormat, RGBAIntegerFormat, RGBA_ASTC_10x10_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_BPTC_Format, RGBA_ETC2_EAC_Format, RGBA_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGBFormat, RGBIntegerFormat, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGFormat, RGIntegerFormat, RTTNode, RangeNode, RectAreaLight, RectAreaLightNode, RedFormat, RedIntegerFormat, ReferenceNode, ReflectorNode, ReinhardToneMapping, RemapNode, RenderOutputNode, RenderTarget, RendererReferenceNode, RendererUtils, RepeatWrapping, ReplaceStencilOp, ReverseSubtractEquation, RotateNode, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SRGBColorSpace, SRGBTransfer, Scene, SceneNode, ScreenNode, ScriptableNode, ScriptableValueNode, SetNode, ShadowBaseNode, ShadowMaterial, ShadowNode, ShadowNodeMaterial, ShortType, SkinningNode, Sphere, SphereGeometry, SplitNode, SpotLight, SpotLightNode, SpriteMaterial, SpriteNodeMaterial, SpriteSheetUVNode, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StackNode, StaticDrawUsage, Storage3DTexture, StorageArrayElementNode, StorageArrayTexture, StorageBufferAttribute, StorageBufferNode, StorageInstancedBufferAttribute, StorageTexture, StorageTextureNode, StructNode, StructTypeNode, SubBuildNode, SubtractEquation, SubtractiveBlending, TSL, TangentSpaceNormalMap, TempNode, Texture, Texture3DNode, TextureNode, TextureSizeNode, ToneMappingNode, ToonOutlinePassNode, 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号