three.webgpu.nodes.js 1.6 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802
  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, DynamicDrawUsage, InterleavedBufferAttribute, NoColorSpace, UnsignedIntType, IntType, BackSide, CubeReflectionMapping, CubeRefractionMapping, TangentSpaceNormalMap, ObjectSpaceNormalMap, InstancedInterleavedBuffer, InstancedBufferAttribute, DataArrayTexture, FloatType, FramebufferTexture, LinearMipmapLinearFilter, DepthTexture, Material, NormalBlending, LineBasicMaterial, LineDashedMaterial, NoBlending, MeshNormalMaterial, WebGLCubeRenderTarget, BoxGeometry, Mesh, Scene, LinearFilter, CubeCamera, CubeTexture, EquirectangularReflectionMapping, EquirectangularRefractionMapping, AddOperation, MixOperation, MultiplyOperation, MeshBasicMaterial, MeshLambertMaterial, MeshPhongMaterial, Texture, MeshStandardMaterial, MeshPhysicalMaterial, MeshToonMaterial, MeshMatcapMaterial, SpriteMaterial, PointsMaterial, ShadowMaterial, arrayNeedsUint32, Uint32BufferAttribute, Uint16BufferAttribute, DoubleSide, Camera, DepthStencilFormat, DepthFormat, UnsignedInt248Type, UnsignedByteType, RenderTarget, Plane, Object3D, HalfFloatType, LinearMipMapLinearFilter, OrthographicCamera, BufferGeometry, Float32BufferAttribute, BufferAttribute, UVMapping, Euler, LinearSRGBColorSpace, LessCompare, VSMShadowMap, RGFormat, BasicShadowMap, SphereGeometry, CubeUVReflectionMapping, PerspectiveCamera, RGBAFormat, LinearMipmapNearestFilter, NearestMipmapLinearFilter, Float16BufferAttribute, REVISION, ArrayCamera, WebXRController, RAD2DEG, SRGBColorSpace, PCFShadowMap, FrontSide, Frustum, DataTexture, RedIntegerFormat, RedFormat, RGIntegerFormat, RGBIntegerFormat, RGBFormat, RGBAIntegerFormat, UnsignedShortType, ByteType, ShortType, warnOnce, createCanvasElement, AddEquation, SubtractEquation, ReverseSubtractEquation, ZeroFactor, OneFactor, SrcColorFactor, SrcAlphaFactor, SrcAlphaSaturateFactor, DstColorFactor, DstAlphaFactor, OneMinusSrcColorFactor, OneMinusSrcAlphaFactor, OneMinusDstColorFactor, OneMinusDstAlphaFactor, CullFaceNone, CullFaceBack, CullFaceFront, CustomBlending, MultiplyBlending, SubtractiveBlending, AdditiveBlending, NotEqualDepth, GreaterDepth, GreaterEqualDepth, EqualDepth, LessEqualDepth, LessDepth, AlwaysDepth, NeverDepth, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedInt5999Type, AlphaFormat, LuminanceFormat, LuminanceAlphaFormat, 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, RepeatWrapping, ClampToEdgeWrapping, MirroredRepeatWrapping, NearestFilter, NearestMipmapNearestFilter, NeverCompare, AlwaysCompare, LessEqualCompare, EqualCompare, GreaterEqualCompare, GreaterCompare, NotEqualCompare, 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, CylinderGeometry, 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, KeyframeTrack, LOD, LatheGeometry, Layers, Light, Line, Line3, LineCurve, LineCurve3, LineLoop, LineSegments, LinearInterpolant, LinearMipMapNearestFilter, LinearTransfer, LoaderUtils, LoadingManager, LoopOnce, LoopPingPong, LoopRepeat, MOUSE, MeshDepthMaterial, MeshDistanceMaterial, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NormalAnimationBlendMode, NumberKeyframeTrack, OctahedronGeometry, OneMinusConstantAlphaFactor, OneMinusConstantColorFactor, PCFSoftShadowMap, Path, PlaneGeometry, PlaneHelper, PointLightHelper, Points, PolarGridHelper, PolyhedronGeometry, PositionalAudio, PropertyBinding, PropertyMixer, QuadraticBezierCurve, QuadraticBezierCurve3, Quaternion, QuaternionKeyframeTrack, QuaternionLinearInterpolant, RGBADepthPacking, RGBDepthPacking, RGB_BPTC_SIGNED_Format, RGB_BPTC_UNSIGNED_Format, RGDepthPacking, RawShaderMaterial, Ray, Raycaster, RenderTarget3D, RenderTargetArray, RingGeometry, ShaderMaterial, Shape, ShapeGeometry, ShapePath, ShapeUtils, Skeleton, SkeletonHelper, SkinnedMesh, Source, Sphere, Spherical, SphericalHarmonics3, SplineCurve, SpotLightHelper, Sprite, StaticCopyUsage, StaticReadUsage, StereoCamera, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, TOUCH, TetrahedronGeometry, TextureLoader, TextureUtils, TimestampQuery, TorusGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeGeometry, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform, UniformsGroup, VectorKeyframeTrack, VideoFrameTexture, VideoTexture, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGLRenderTarget, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroSlopeEnding } from './three.core.js';
  8. const refreshUniforms = [
  9. 'alphaMap',
  10. 'alphaTest',
  11. 'anisotropy',
  12. 'anisotropyMap',
  13. 'anisotropyRotation',
  14. 'aoMap',
  15. 'attenuationColor',
  16. 'attenuationDistance',
  17. 'bumpMap',
  18. 'clearcoat',
  19. 'clearcoatMap',
  20. 'clearcoatNormalMap',
  21. 'clearcoatNormalScale',
  22. 'clearcoatRoughness',
  23. 'color',
  24. 'dispersion',
  25. 'displacementMap',
  26. 'emissive',
  27. 'emissiveMap',
  28. 'envMap',
  29. 'gradientMap',
  30. 'ior',
  31. 'iridescence',
  32. 'iridescenceIOR',
  33. 'iridescenceMap',
  34. 'iridescenceThicknessMap',
  35. 'lightMap',
  36. 'map',
  37. 'matcap',
  38. 'metalness',
  39. 'metalnessMap',
  40. 'normalMap',
  41. 'normalScale',
  42. 'opacity',
  43. 'roughness',
  44. 'roughnessMap',
  45. 'sheen',
  46. 'sheenColor',
  47. 'sheenColorMap',
  48. 'sheenRoughnessMap',
  49. 'shininess',
  50. 'specular',
  51. 'specularColor',
  52. 'specularColorMap',
  53. 'specularIntensity',
  54. 'specularIntensityMap',
  55. 'specularMap',
  56. 'thickness',
  57. 'transmission',
  58. 'transmissionMap'
  59. ];
  60. /**
  61. * This class is used by {@link WebGPURenderer} as management component.
  62. * It's primary purpose is to determine whether render objects require a
  63. * refresh right before they are going to be rendered or not.
  64. */
  65. class NodeMaterialObserver {
  66. /**
  67. * Constructs a new node material observer.
  68. *
  69. * @param {NodeBuilder} builder - The node builder.
  70. */
  71. constructor( builder ) {
  72. /**
  73. * A node material can be used by more than one render object so the
  74. * monitor must maintain a list of render objects.
  75. *
  76. * @type {WeakMap<RenderObject,Object>}
  77. */
  78. this.renderObjects = new WeakMap();
  79. /**
  80. * Whether the material uses node objects or not.
  81. *
  82. * @type {Boolean}
  83. */
  84. this.hasNode = this.containsNode( builder );
  85. /**
  86. * Whether the node builder's 3D object is animated or not.
  87. *
  88. * @type {Boolean}
  89. */
  90. this.hasAnimation = builder.object.isSkinnedMesh === true;
  91. /**
  92. * A list of all possible material uniforms
  93. *
  94. * @type {Array<String>}
  95. */
  96. this.refreshUniforms = refreshUniforms;
  97. /**
  98. * Holds the current render ID from the node frame.
  99. *
  100. * @type {Number}
  101. * @default 0
  102. */
  103. this.renderId = 0;
  104. }
  105. /**
  106. * Returns `true` if the given render object is verified for the first time of this observer.
  107. *
  108. * @param {RenderObject} renderObject - The render object.
  109. * @return {Boolean} Whether the given render object is verified for the first time of this observer.
  110. */
  111. firstInitialization( renderObject ) {
  112. const hasInitialized = this.renderObjects.has( renderObject );
  113. if ( hasInitialized === false ) {
  114. this.getRenderObjectData( renderObject );
  115. return true;
  116. }
  117. return false;
  118. }
  119. /**
  120. * Returns monitoring data for the given render object.
  121. *
  122. * @param {RenderObject} renderObject - The render object.
  123. * @return {Object} The monitoring data.
  124. */
  125. getRenderObjectData( renderObject ) {
  126. let data = this.renderObjects.get( renderObject );
  127. if ( data === undefined ) {
  128. const { geometry, material, object } = renderObject;
  129. data = {
  130. material: this.getMaterialData( material ),
  131. geometry: {
  132. id: geometry.id,
  133. attributes: this.getAttributesData( geometry.attributes ),
  134. indexVersion: geometry.index ? geometry.index.version : null,
  135. drawRange: { start: geometry.drawRange.start, count: geometry.drawRange.count }
  136. },
  137. worldMatrix: object.matrixWorld.clone()
  138. };
  139. if ( object.center ) {
  140. data.center = object.center.clone();
  141. }
  142. if ( object.morphTargetInfluences ) {
  143. data.morphTargetInfluences = object.morphTargetInfluences.slice();
  144. }
  145. if ( renderObject.bundle !== null ) {
  146. data.version = renderObject.bundle.version;
  147. }
  148. if ( data.material.transmission > 0 ) {
  149. const { width, height } = renderObject.context;
  150. data.bufferWidth = width;
  151. data.bufferHeight = height;
  152. }
  153. this.renderObjects.set( renderObject, data );
  154. }
  155. return data;
  156. }
  157. /**
  158. * Returns an attribute data structure holding the attributes versions for
  159. * monitoring.
  160. *
  161. * @param {Object} attributes - The geometry attributes.
  162. * @return {Object} An object for monitoring the versions of attributes.
  163. */
  164. getAttributesData( attributes ) {
  165. const attributesData = {};
  166. for ( const name in attributes ) {
  167. const attribute = attributes[ name ];
  168. attributesData[ name ] = {
  169. version: attribute.version
  170. };
  171. }
  172. return attributesData;
  173. }
  174. /**
  175. * Returns `true` if the node builder's material uses
  176. * node properties.
  177. *
  178. * @param {NodeBuilder} builder - The current node builder.
  179. * @return {Boolean} Whether the node builder's material uses node properties or not.
  180. */
  181. containsNode( builder ) {
  182. const material = builder.material;
  183. for ( const property in material ) {
  184. if ( material[ property ] && material[ property ].isNode )
  185. return true;
  186. }
  187. if ( builder.renderer.nodes.modelViewMatrix !== null || builder.renderer.nodes.modelNormalViewMatrix !== null )
  188. return true;
  189. return false;
  190. }
  191. /**
  192. * Returns a material data structure holding the material property values for
  193. * monitoring.
  194. *
  195. * @param {Material} material - The material.
  196. * @return {Object} An object for monitoring material properties.
  197. */
  198. getMaterialData( material ) {
  199. const data = {};
  200. for ( const property of this.refreshUniforms ) {
  201. const value = material[ property ];
  202. if ( value === null || value === undefined ) continue;
  203. if ( typeof value === 'object' && value.clone !== undefined ) {
  204. if ( value.isTexture === true ) {
  205. data[ property ] = { id: value.id, version: value.version };
  206. } else {
  207. data[ property ] = value.clone();
  208. }
  209. } else {
  210. data[ property ] = value;
  211. }
  212. }
  213. return data;
  214. }
  215. /**
  216. * Returns `true` if the given render object has not changed its state.
  217. *
  218. * @param {RenderObject} renderObject - The render object.
  219. * @return {Boolean} Whether the given render object has changed its state or not.
  220. */
  221. equals( renderObject ) {
  222. const { object, material, geometry } = renderObject;
  223. const renderObjectData = this.getRenderObjectData( renderObject );
  224. // world matrix
  225. if ( renderObjectData.worldMatrix.equals( object.matrixWorld ) !== true ) {
  226. renderObjectData.worldMatrix.copy( object.matrixWorld );
  227. return false;
  228. }
  229. // material
  230. const materialData = renderObjectData.material;
  231. for ( const property in materialData ) {
  232. const value = materialData[ property ];
  233. const mtlValue = material[ property ];
  234. if ( value.equals !== undefined ) {
  235. if ( value.equals( mtlValue ) === false ) {
  236. value.copy( mtlValue );
  237. return false;
  238. }
  239. } else if ( mtlValue.isTexture === true ) {
  240. if ( value.id !== mtlValue.id || value.version !== mtlValue.version ) {
  241. value.id = mtlValue.id;
  242. value.version = mtlValue.version;
  243. return false;
  244. }
  245. } else if ( value !== mtlValue ) {
  246. materialData[ property ] = mtlValue;
  247. return false;
  248. }
  249. }
  250. if ( materialData.transmission > 0 ) {
  251. const { width, height } = renderObject.context;
  252. if ( renderObjectData.bufferWidth !== width || renderObjectData.bufferHeight !== height ) {
  253. renderObjectData.bufferWidth = width;
  254. renderObjectData.bufferHeight = height;
  255. return false;
  256. }
  257. }
  258. // geometry
  259. const storedGeometryData = renderObjectData.geometry;
  260. const attributes = geometry.attributes;
  261. const storedAttributes = storedGeometryData.attributes;
  262. const storedAttributeNames = Object.keys( storedAttributes );
  263. const currentAttributeNames = Object.keys( attributes );
  264. if ( storedGeometryData.id !== geometry.id ) {
  265. storedGeometryData.id = geometry.id;
  266. return false;
  267. }
  268. if ( storedAttributeNames.length !== currentAttributeNames.length ) {
  269. renderObjectData.geometry.attributes = this.getAttributesData( attributes );
  270. return false;
  271. }
  272. // compare each attribute
  273. for ( const name of storedAttributeNames ) {
  274. const storedAttributeData = storedAttributes[ name ];
  275. const attribute = attributes[ name ];
  276. if ( attribute === undefined ) {
  277. // attribute was removed
  278. delete storedAttributes[ name ];
  279. return false;
  280. }
  281. if ( storedAttributeData.version !== attribute.version ) {
  282. storedAttributeData.version = attribute.version;
  283. return false;
  284. }
  285. }
  286. // check index
  287. const index = geometry.index;
  288. const storedIndexVersion = storedGeometryData.indexVersion;
  289. const currentIndexVersion = index ? index.version : null;
  290. if ( storedIndexVersion !== currentIndexVersion ) {
  291. storedGeometryData.indexVersion = currentIndexVersion;
  292. return false;
  293. }
  294. // check drawRange
  295. if ( storedGeometryData.drawRange.start !== geometry.drawRange.start || storedGeometryData.drawRange.count !== geometry.drawRange.count ) {
  296. storedGeometryData.drawRange.start = geometry.drawRange.start;
  297. storedGeometryData.drawRange.count = geometry.drawRange.count;
  298. return false;
  299. }
  300. // morph targets
  301. if ( renderObjectData.morphTargetInfluences ) {
  302. let morphChanged = false;
  303. for ( let i = 0; i < renderObjectData.morphTargetInfluences.length; i ++ ) {
  304. if ( renderObjectData.morphTargetInfluences[ i ] !== object.morphTargetInfluences[ i ] ) {
  305. morphChanged = true;
  306. }
  307. }
  308. if ( morphChanged ) return true;
  309. }
  310. // center
  311. if ( renderObjectData.center ) {
  312. if ( renderObjectData.center.equals( object.center ) === false ) {
  313. renderObjectData.center.copy( object.center );
  314. return true;
  315. }
  316. }
  317. // bundle
  318. if ( renderObject.bundle !== null ) {
  319. renderObjectData.version = renderObject.bundle.version;
  320. }
  321. return true;
  322. }
  323. /**
  324. * Checks if the given render object requires a refresh.
  325. *
  326. * @param {RenderObject} renderObject - The render object.
  327. * @param {NodeFrame} nodeFrame - The current node frame.
  328. * @return {Boolean} Whether the given render object requires a refresh or not.
  329. */
  330. needsRefresh( renderObject, nodeFrame ) {
  331. if ( this.hasNode || this.hasAnimation || this.firstInitialization( renderObject ) )
  332. return true;
  333. const { renderId } = nodeFrame;
  334. if ( this.renderId !== renderId ) {
  335. this.renderId = renderId;
  336. return true;
  337. }
  338. const isStatic = renderObject.object.static === true;
  339. const isBundle = renderObject.bundle !== null && renderObject.bundle.static === true && this.getRenderObjectData( renderObject ).version === renderObject.bundle.version;
  340. if ( isStatic || isBundle )
  341. return false;
  342. const notEqual = this.equals( renderObject ) !== true;
  343. return notEqual;
  344. }
  345. }
  346. /** @module NodeUtils **/
  347. // cyrb53 (c) 2018 bryc (github.com/bryc). License: Public domain. Attribution appreciated.
  348. // A fast and simple 64-bit (or 53-bit) string hash function with decent collision resistance.
  349. // Largely inspired by MurmurHash2/3, but with a focus on speed/simplicity.
  350. // See https://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript/52171480#52171480
  351. // https://github.com/bryc/code/blob/master/jshash/experimental/cyrb53.js
  352. function cyrb53( value, seed = 0 ) {
  353. let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;
  354. if ( value instanceof Array ) {
  355. for ( let i = 0, val; i < value.length; i ++ ) {
  356. val = value[ i ];
  357. h1 = Math.imul( h1 ^ val, 2654435761 );
  358. h2 = Math.imul( h2 ^ val, 1597334677 );
  359. }
  360. } else {
  361. for ( let i = 0, ch; i < value.length; i ++ ) {
  362. ch = value.charCodeAt( i );
  363. h1 = Math.imul( h1 ^ ch, 2654435761 );
  364. h2 = Math.imul( h2 ^ ch, 1597334677 );
  365. }
  366. }
  367. h1 = Math.imul( h1 ^ ( h1 >>> 16 ), 2246822507 );
  368. h1 ^= Math.imul( h2 ^ ( h2 >>> 13 ), 3266489909 );
  369. h2 = Math.imul( h2 ^ ( h2 >>> 16 ), 2246822507 );
  370. h2 ^= Math.imul( h1 ^ ( h1 >>> 13 ), 3266489909 );
  371. return 4294967296 * ( 2097151 & h2 ) + ( h1 >>> 0 );
  372. }
  373. /**
  374. * Computes a hash for the given string.
  375. *
  376. * @method
  377. * @param {String} str - The string to be hashed.
  378. * @return {Number} The hash.
  379. */
  380. const hashString = ( str ) => cyrb53( str );
  381. /**
  382. * Computes a hash for the given array.
  383. *
  384. * @method
  385. * @param {Array<Number>} array - The array to be hashed.
  386. * @return {Number} The hash.
  387. */
  388. const hashArray = ( array ) => cyrb53( array );
  389. /**
  390. * Computes a hash for the given list of parameters.
  391. *
  392. * @method
  393. * @param {...Number} params - A list of parameters.
  394. * @return {Number} The hash.
  395. */
  396. const hash$1 = ( ...params ) => cyrb53( params );
  397. /**
  398. * Computes a cache key for the given node.
  399. *
  400. * @method
  401. * @param {Object} object - The object to be hashed.
  402. * @param {Boolean} [force=false] - Whether to force a cache key computation or not.
  403. * @return {Number} The hash.
  404. */
  405. function getCacheKey$1( object, force = false ) {
  406. const values = [];
  407. if ( object.isNode === true ) {
  408. values.push( object.id );
  409. object = object.getSelf();
  410. }
  411. for ( const { property, childNode } of getNodeChildren( object ) ) {
  412. values.push( cyrb53( property.slice( 0, -4 ) ), childNode.getCacheKey( force ) );
  413. }
  414. return cyrb53( values );
  415. }
  416. /**
  417. * This generator function can be used to iterate over the node children
  418. * of the given object.
  419. *
  420. * @generator
  421. * @param {Object} node - The object to be hashed.
  422. * @param {Boolean} [toJSON=false] - Whether to return JSON or not.
  423. * @yields {Object} A result node holding the property, index (if available) and the child node.
  424. */
  425. function* getNodeChildren( node, toJSON = false ) {
  426. for ( const property in node ) {
  427. // Ignore private properties.
  428. if ( property.startsWith( '_' ) === true ) continue;
  429. const object = node[ property ];
  430. if ( Array.isArray( object ) === true ) {
  431. for ( let i = 0; i < object.length; i ++ ) {
  432. const child = object[ i ];
  433. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  434. yield { property, index: i, childNode: child };
  435. }
  436. }
  437. } else if ( object && object.isNode === true ) {
  438. yield { property, childNode: object };
  439. } else if ( typeof object === 'object' ) {
  440. for ( const subProperty in object ) {
  441. const child = object[ subProperty ];
  442. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  443. yield { property, index: subProperty, childNode: child };
  444. }
  445. }
  446. }
  447. }
  448. }
  449. const typeFromLength = /*@__PURE__*/ new Map( [
  450. [ 1, 'float' ],
  451. [ 2, 'vec2' ],
  452. [ 3, 'vec3' ],
  453. [ 4, 'vec4' ],
  454. [ 9, 'mat3' ],
  455. [ 16, 'mat4' ]
  456. ] );
  457. const dataFromObject = /*@__PURE__*/ new WeakMap();
  458. /**
  459. * Returns the data type for the given the length.
  460. *
  461. * @method
  462. * @param {Number} length - The length.
  463. * @return {String} The data type.
  464. */
  465. function getTypeFromLength( length ) {
  466. return typeFromLength.get( length );
  467. }
  468. /**
  469. * Returns the typed array for the given data type.
  470. *
  471. * @method
  472. * @param {String} type - The data type.
  473. * @return {TypedArray} The typed array.
  474. */
  475. function getTypedArrayFromType( type ) {
  476. // Handle component type for vectors and matrices
  477. if ( /[iu]?vec\d/.test( type ) ) {
  478. // Handle int vectors
  479. if ( type.startsWith( 'ivec' ) ) return Int32Array;
  480. // Handle uint vectors
  481. if ( type.startsWith( 'uvec' ) ) return Uint32Array;
  482. // Default to float vectors
  483. return Float32Array;
  484. }
  485. // Handle matrices (always float)
  486. if ( /mat\d/.test( type ) ) return Float32Array;
  487. // Basic types
  488. if ( /float/.test( type ) ) return Float32Array;
  489. if ( /uint/.test( type ) ) return Uint32Array;
  490. if ( /int/.test( type ) ) return Int32Array;
  491. throw new Error( `THREE.NodeUtils: Unsupported type: ${type}` );
  492. }
  493. /**
  494. * Returns the length for the given data type.
  495. *
  496. * @method
  497. * @param {String} type - The data type.
  498. * @return {Number} The length.
  499. */
  500. function getLengthFromType( type ) {
  501. if ( /float|int|uint/.test( type ) ) return 1;
  502. if ( /vec2/.test( type ) ) return 2;
  503. if ( /vec3/.test( type ) ) return 3;
  504. if ( /vec4/.test( type ) ) return 4;
  505. if ( /mat2/.test( type ) ) return 4;
  506. if ( /mat3/.test( type ) ) return 9;
  507. if ( /mat4/.test( type ) ) return 16;
  508. console.error( 'THREE.TSL: Unsupported type:', type );
  509. }
  510. /**
  511. * Returns the data type for the given value.
  512. *
  513. * @method
  514. * @param {Any} value - The value.
  515. * @return {String?} The data type.
  516. */
  517. function getValueType( value ) {
  518. if ( value === undefined || value === null ) return null;
  519. const typeOf = typeof value;
  520. if ( value.isNode === true ) {
  521. return 'node';
  522. } else if ( typeOf === 'number' ) {
  523. return 'float';
  524. } else if ( typeOf === 'boolean' ) {
  525. return 'bool';
  526. } else if ( typeOf === 'string' ) {
  527. return 'string';
  528. } else if ( typeOf === 'function' ) {
  529. return 'shader';
  530. } else if ( value.isVector2 === true ) {
  531. return 'vec2';
  532. } else if ( value.isVector3 === true ) {
  533. return 'vec3';
  534. } else if ( value.isVector4 === true ) {
  535. return 'vec4';
  536. } else if ( value.isMatrix2 === true ) {
  537. return 'mat2';
  538. } else if ( value.isMatrix3 === true ) {
  539. return 'mat3';
  540. } else if ( value.isMatrix4 === true ) {
  541. return 'mat4';
  542. } else if ( value.isColor === true ) {
  543. return 'color';
  544. } else if ( value instanceof ArrayBuffer ) {
  545. return 'ArrayBuffer';
  546. }
  547. return null;
  548. }
  549. /**
  550. * Returns the value/object for the given data type and parameters.
  551. *
  552. * @method
  553. * @param {String} type - The given type.
  554. * @param {...Any} params - A parameter list.
  555. * @return {Any} The value/object.
  556. */
  557. function getValueFromType( type, ...params ) {
  558. const last4 = type ? type.slice( -4 ) : undefined;
  559. if ( params.length === 1 ) { // ensure same behaviour as in NodeBuilder.format()
  560. if ( last4 === 'vec2' ) params = [ params[ 0 ], params[ 0 ] ];
  561. else if ( last4 === 'vec3' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ] ];
  562. else if ( last4 === 'vec4' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ], params[ 0 ] ];
  563. }
  564. if ( type === 'color' ) {
  565. return new Color( ...params );
  566. } else if ( last4 === 'vec2' ) {
  567. return new Vector2( ...params );
  568. } else if ( last4 === 'vec3' ) {
  569. return new Vector3( ...params );
  570. } else if ( last4 === 'vec4' ) {
  571. return new Vector4( ...params );
  572. } else if ( last4 === 'mat2' ) {
  573. return new Matrix2( ...params );
  574. } else if ( last4 === 'mat3' ) {
  575. return new Matrix3( ...params );
  576. } else if ( last4 === 'mat4' ) {
  577. return new Matrix4( ...params );
  578. } else if ( type === 'bool' ) {
  579. return params[ 0 ] || false;
  580. } else if ( ( type === 'float' ) || ( type === 'int' ) || ( type === 'uint' ) ) {
  581. return params[ 0 ] || 0;
  582. } else if ( type === 'string' ) {
  583. return params[ 0 ] || '';
  584. } else if ( type === 'ArrayBuffer' ) {
  585. return base64ToArrayBuffer( params[ 0 ] );
  586. }
  587. return null;
  588. }
  589. /**
  590. * Gets the object data that can be shared between different rendering steps.
  591. *
  592. * @param {Object} object - The object to get the data for.
  593. * @return {Object} The object data.
  594. */
  595. function getDataFromObject( object ) {
  596. let data = dataFromObject.get( object );
  597. if ( data === undefined ) {
  598. data = {};
  599. dataFromObject.set( object, data );
  600. }
  601. return data;
  602. }
  603. /**
  604. * Converts the given array buffer to a Base64 string.
  605. *
  606. * @method
  607. * @param {ArrayBuffer} arrayBuffer - The array buffer.
  608. * @return {String} The Base64 string.
  609. */
  610. function arrayBufferToBase64( arrayBuffer ) {
  611. let chars = '';
  612. const array = new Uint8Array( arrayBuffer );
  613. for ( let i = 0; i < array.length; i ++ ) {
  614. chars += String.fromCharCode( array[ i ] );
  615. }
  616. return btoa( chars );
  617. }
  618. /**
  619. * Converts the given Base64 string to an array buffer.
  620. *
  621. * @method
  622. * @param {String} base64 - The Base64 string.
  623. * @return {ArrayBuffer} The array buffer.
  624. */
  625. function base64ToArrayBuffer( base64 ) {
  626. return Uint8Array.from( atob( base64 ), c => c.charCodeAt( 0 ) ).buffer;
  627. }
  628. var NodeUtils = /*#__PURE__*/Object.freeze({
  629. __proto__: null,
  630. arrayBufferToBase64: arrayBufferToBase64,
  631. base64ToArrayBuffer: base64ToArrayBuffer,
  632. getCacheKey: getCacheKey$1,
  633. getDataFromObject: getDataFromObject,
  634. getLengthFromType: getLengthFromType,
  635. getNodeChildren: getNodeChildren,
  636. getTypeFromLength: getTypeFromLength,
  637. getTypedArrayFromType: getTypedArrayFromType,
  638. getValueFromType: getValueFromType,
  639. getValueType: getValueType,
  640. hash: hash$1,
  641. hashArray: hashArray,
  642. hashString: hashString
  643. });
  644. /** @module NodeConstants **/
  645. /**
  646. * Possible shader stages.
  647. *
  648. * @property {string} VERTEX The vertex shader stage.
  649. * @property {string} FRAGMENT The fragment shader stage.
  650. */
  651. const NodeShaderStage = {
  652. VERTEX: 'vertex',
  653. FRAGMENT: 'fragment'
  654. };
  655. /**
  656. * Update types of a node.
  657. *
  658. * @property {string} NONE The update method is not executed.
  659. * @property {string} FRAME The update method is executed per frame.
  660. * @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.
  661. * @property {string} OBJECT The update method is executed per {@link Object3D} that uses the node for rendering.
  662. */
  663. const NodeUpdateType = {
  664. NONE: 'none',
  665. FRAME: 'frame',
  666. RENDER: 'render',
  667. OBJECT: 'object'
  668. };
  669. /**
  670. * Data types of a node.
  671. *
  672. * @property {string} BOOLEAN Boolean type.
  673. * @property {string} INTEGER Integer type.
  674. * @property {string} FLOAT Float type.
  675. * @property {string} VECTOR2 Two-dimensional vector type.
  676. * @property {string} VECTOR3 Three-dimensional vector type.
  677. * @property {string} VECTOR4 Four-dimensional vector type.
  678. * @property {string} MATRIX2 2x2 matrix type.
  679. * @property {string} MATRIX3 3x3 matrix type.
  680. * @property {string} MATRIX4 4x4 matrix type.
  681. */
  682. const NodeType = {
  683. BOOLEAN: 'bool',
  684. INTEGER: 'int',
  685. FLOAT: 'float',
  686. VECTOR2: 'vec2',
  687. VECTOR3: 'vec3',
  688. VECTOR4: 'vec4',
  689. MATRIX2: 'mat2',
  690. MATRIX3: 'mat3',
  691. MATRIX4: 'mat4'
  692. };
  693. /**
  694. * Access types of a node. These are relevant for compute and storage usage.
  695. *
  696. * @property {string} READ_ONLY Read-only access
  697. * @property {string} WRITE_ONLY Write-only access.
  698. * @property {string} READ_WRITE Read and write access.
  699. */
  700. const NodeAccess = {
  701. READ_ONLY: 'readOnly',
  702. WRITE_ONLY: 'writeOnly',
  703. READ_WRITE: 'readWrite',
  704. };
  705. const defaultShaderStages = [ 'fragment', 'vertex' ];
  706. const defaultBuildStages = [ 'setup', 'analyze', 'generate' ];
  707. const shaderStages = [ ...defaultShaderStages, 'compute' ];
  708. const vectorComponents = [ 'x', 'y', 'z', 'w' ];
  709. let _nodeId = 0;
  710. /**
  711. * Base class for all nodes.
  712. *
  713. * @augments EventDispatcher
  714. */
  715. class Node extends EventDispatcher {
  716. static get type() {
  717. return 'Node';
  718. }
  719. /**
  720. * Constructs a new node.
  721. *
  722. * @param {String?} nodeType - The node type.
  723. */
  724. constructor( nodeType = null ) {
  725. super();
  726. /**
  727. * The node type. This represents the result type of the node (e.g. `float` or `vec3`).
  728. *
  729. * @type {String?}
  730. * @default null
  731. */
  732. this.nodeType = nodeType;
  733. /**
  734. * The update type of the node's {@link Node#update} method. Possible values are listed in {@link NodeUpdateType}.
  735. *
  736. * @type {String}
  737. * @default 'none'
  738. */
  739. this.updateType = NodeUpdateType.NONE;
  740. /**
  741. * The update type of the node's {@link Node#updateBefore} method. Possible values are listed in {@link NodeUpdateType}.
  742. *
  743. * @type {String}
  744. * @default 'none'
  745. */
  746. this.updateBeforeType = NodeUpdateType.NONE;
  747. /**
  748. * The update type of the node's {@link Node#updateAfter} method. Possible values are listed in {@link NodeUpdateType}.
  749. *
  750. * @type {String}
  751. * @default 'none'
  752. */
  753. this.updateAfterType = NodeUpdateType.NONE;
  754. /**
  755. * The UUID of the node.
  756. *
  757. * @type {String}
  758. * @readonly
  759. */
  760. this.uuid = MathUtils.generateUUID();
  761. /**
  762. * The version of the node. The version automatically is increased when {@link Node#needsUpdate} is set to `true`.
  763. *
  764. * @type {Number}
  765. * @readonly
  766. * @default 0
  767. */
  768. this.version = 0;
  769. /**
  770. * Whether this node is global or not. This property is relevant for the internal
  771. * node caching system. All nodes which should be declared just once should
  772. * set this flag to `true` (a typical example is {@link AttributeNode}).
  773. *
  774. * @type {Boolean}
  775. * @default false
  776. */
  777. this.global = false;
  778. /**
  779. * This flag can be used for type testing.
  780. *
  781. * @type {Boolean}
  782. * @readonly
  783. * @default true
  784. */
  785. this.isNode = true;
  786. // private
  787. /**
  788. * The cache key of this node.
  789. *
  790. * @private
  791. * @type {Number?}
  792. * @default null
  793. */
  794. this._cacheKey = null;
  795. /**
  796. * The cache key 's version.
  797. *
  798. * @private
  799. * @type {Number}
  800. * @default 0
  801. */
  802. this._cacheKeyVersion = 0;
  803. Object.defineProperty( this, 'id', { value: _nodeId ++ } );
  804. }
  805. /**
  806. * Set this property to `true` when the node should be regenerated.
  807. *
  808. * @type {Boolean}
  809. * @default false
  810. * @param {boolean} value
  811. */
  812. set needsUpdate( value ) {
  813. if ( value === true ) {
  814. this.version ++;
  815. }
  816. }
  817. /**
  818. * The type of the class. The value is usually the constructor name.
  819. *
  820. * @type {String}
  821. * @readonly
  822. */
  823. get type() {
  824. return this.constructor.type;
  825. }
  826. /**
  827. * Convenient method for defining {@link Node#update}.
  828. *
  829. * @param {Function} callback - The update method.
  830. * @param {String} updateType - The update type.
  831. * @return {Node} A reference to this node.
  832. */
  833. onUpdate( callback, updateType ) {
  834. this.updateType = updateType;
  835. this.update = callback.bind( this.getSelf() );
  836. return this;
  837. }
  838. /**
  839. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  840. * this method automatically sets the update type to `FRAME`.
  841. *
  842. * @param {Function} callback - The update method.
  843. * @return {Node} A reference to this node.
  844. */
  845. onFrameUpdate( callback ) {
  846. return this.onUpdate( callback, NodeUpdateType.FRAME );
  847. }
  848. /**
  849. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  850. * this method automatically sets the update type to `RENDER`.
  851. *
  852. * @param {Function} callback - The update method.
  853. * @return {Node} A reference to this node.
  854. */
  855. onRenderUpdate( callback ) {
  856. return this.onUpdate( callback, NodeUpdateType.RENDER );
  857. }
  858. /**
  859. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  860. * this method automatically sets the update type to `OBJECT`.
  861. *
  862. * @param {Function} callback - The update method.
  863. * @return {Node} A reference to this node.
  864. */
  865. onObjectUpdate( callback ) {
  866. return this.onUpdate( callback, NodeUpdateType.OBJECT );
  867. }
  868. /**
  869. * Convenient method for defining {@link Node#updateReference}.
  870. *
  871. * @param {Function} callback - The update method.
  872. * @return {Node} A reference to this node.
  873. */
  874. onReference( callback ) {
  875. this.updateReference = callback.bind( this.getSelf() );
  876. return this;
  877. }
  878. /**
  879. * The `this` reference might point to a Proxy so this method can be used
  880. * to get the reference to the actual node instance.
  881. *
  882. * @return {Node} A reference to the node.
  883. */
  884. getSelf() {
  885. // Returns non-node object.
  886. return this.self || this;
  887. }
  888. /**
  889. * Nodes might refer to other objects like materials. This method allows to dynamically update the reference
  890. * to such objects based on a given state (e.g. the current node frame or builder).
  891. *
  892. * @param {Any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  893. * @return {Any} The updated reference.
  894. */
  895. updateReference( /*state*/ ) {
  896. return this;
  897. }
  898. /**
  899. * By default this method returns the value of the {@link Node#global} flag. This method
  900. * can be overwritten in derived classes if an analytical way is required to determine the
  901. * global status.
  902. *
  903. * @param {NodeBuilder} builder - The current node builder.
  904. * @return {Boolean} Whether this node is global or not.
  905. */
  906. isGlobal( /*builder*/ ) {
  907. return this.global;
  908. }
  909. /**
  910. * Generator function that can be used to iterate over the child nodes.
  911. *
  912. * @generator
  913. * @yields {Node} A child node.
  914. */
  915. * getChildren() {
  916. for ( const { childNode } of getNodeChildren( this ) ) {
  917. yield childNode;
  918. }
  919. }
  920. /**
  921. * Calling this method dispatches the `dispose` event. This event can be used
  922. * to register event listeners for clean up tasks.
  923. */
  924. dispose() {
  925. this.dispatchEvent( { type: 'dispose' } );
  926. }
  927. /**
  928. * Callback for {@link Node#traverse}.
  929. *
  930. * @callback traverseCallback
  931. * @param {Node} node - The current node.
  932. */
  933. /**
  934. * Can be used to traverse through the node's hierarchy.
  935. *
  936. * @param {traverseCallback} callback - A callback that is executed per node.
  937. */
  938. traverse( callback ) {
  939. callback( this );
  940. for ( const childNode of this.getChildren() ) {
  941. childNode.traverse( callback );
  942. }
  943. }
  944. /**
  945. * Returns the cache key for this node.
  946. *
  947. * @param {Boolean} [force=false] - When set to `true`, a recomputation of the cache key is forced.
  948. * @return {Number} The cache key of the node.
  949. */
  950. getCacheKey( force = false ) {
  951. force = force || this.version !== this._cacheKeyVersion;
  952. if ( force === true || this._cacheKey === null ) {
  953. this._cacheKey = hash$1( getCacheKey$1( this, force ), this.customCacheKey() );
  954. this._cacheKeyVersion = this.version;
  955. }
  956. return this._cacheKey;
  957. }
  958. /**
  959. * Generate a custom cache key for this node.
  960. *
  961. * @return {Number} The cache key of the node.
  962. */
  963. customCacheKey() {
  964. return 0;
  965. }
  966. /**
  967. * Returns the references to this node which is by default `this`.
  968. *
  969. * @return {Node} A reference to this node.
  970. */
  971. getScope() {
  972. return this;
  973. }
  974. /**
  975. * Returns the hash of the node which is used to identify the node. By default it's
  976. * the {@link Node#uuid} however derived node classes might have to overwrite this method
  977. * depending on their implementation.
  978. *
  979. * @param {NodeBuilder} builder - The current node builder.
  980. * @return {String} The hash.
  981. */
  982. getHash( /*builder*/ ) {
  983. return this.uuid;
  984. }
  985. /**
  986. * Returns the update type of {@link Node#update}.
  987. *
  988. * @return {NodeUpdateType} The update type.
  989. */
  990. getUpdateType() {
  991. return this.updateType;
  992. }
  993. /**
  994. * Returns the update type of {@link Node#updateBefore}.
  995. *
  996. * @return {NodeUpdateType} The update type.
  997. */
  998. getUpdateBeforeType() {
  999. return this.updateBeforeType;
  1000. }
  1001. /**
  1002. * Returns the update type of {@link Node#updateAfter}.
  1003. *
  1004. * @return {NodeUpdateType} The update type.
  1005. */
  1006. getUpdateAfterType() {
  1007. return this.updateAfterType;
  1008. }
  1009. /**
  1010. * Certain types are composed of multiple elements. For example a `vec3`
  1011. * is composed of three `float` values. This method returns the type of
  1012. * these elements.
  1013. *
  1014. * @param {NodeBuilder} builder - The current node builder.
  1015. * @return {String} The type of the node.
  1016. */
  1017. getElementType( builder ) {
  1018. const type = this.getNodeType( builder );
  1019. const elementType = builder.getElementType( type );
  1020. return elementType;
  1021. }
  1022. /**
  1023. * Returns the node's type.
  1024. *
  1025. * @param {NodeBuilder} builder - The current node builder.
  1026. * @return {String} The type of the node.
  1027. */
  1028. getNodeType( builder ) {
  1029. const nodeProperties = builder.getNodeProperties( this );
  1030. if ( nodeProperties.outputNode ) {
  1031. return nodeProperties.outputNode.getNodeType( builder );
  1032. }
  1033. return this.nodeType;
  1034. }
  1035. /**
  1036. * This method is used during the build process of a node and ensures
  1037. * equal nodes are not built multiple times but just once. For example if
  1038. * `attribute( 'uv' )` is used multiple times by the user, the build
  1039. * process makes sure to process just the first node.
  1040. *
  1041. * @param {NodeBuilder} builder - The current node builder.
  1042. * @return {Node} The shared node if possible. Otherwise `this` is returned.
  1043. */
  1044. getShared( builder ) {
  1045. const hash = this.getHash( builder );
  1046. const nodeFromHash = builder.getNodeFromHash( hash );
  1047. return nodeFromHash || this;
  1048. }
  1049. /**
  1050. * Represents the setup stage which is the first step of the build process, see {@link Node#build} method.
  1051. * This method is often overwritten in derived modules to prepare the node which is used as the output/result.
  1052. * The output node must be returned in the `return` statement.
  1053. *
  1054. * @param {NodeBuilder} builder - The current node builder.
  1055. * @return {Node?} The output node.
  1056. */
  1057. setup( builder ) {
  1058. const nodeProperties = builder.getNodeProperties( this );
  1059. let index = 0;
  1060. for ( const childNode of this.getChildren() ) {
  1061. nodeProperties[ 'node' + index ++ ] = childNode;
  1062. }
  1063. // return a outputNode if exists or null
  1064. return nodeProperties.outputNode || null;
  1065. }
  1066. /**
  1067. * Represents the analyze stage which is the second step of the build process, see {@link Node#build} method.
  1068. * This stage analyzes the node hierarchy and ensures descendent nodes are built.
  1069. *
  1070. * @param {NodeBuilder} builder - The current node builder.
  1071. */
  1072. analyze( builder ) {
  1073. const usageCount = builder.increaseUsage( this );
  1074. if ( usageCount === 1 ) {
  1075. // node flow children
  1076. const nodeProperties = builder.getNodeProperties( this );
  1077. for ( const childNode of Object.values( nodeProperties ) ) {
  1078. if ( childNode && childNode.isNode === true ) {
  1079. childNode.build( builder );
  1080. }
  1081. }
  1082. }
  1083. }
  1084. /**
  1085. * Represents the generate stage which is the third step of the build process, see {@link Node#build} method.
  1086. * This state builds the output node and returns the resulting shader string.
  1087. *
  1088. * @param {NodeBuilder} builder - The current node builder.
  1089. * @param {String?} output - Can be used to define the output type.
  1090. * @return {String?} The generated shader string.
  1091. */
  1092. generate( builder, output ) {
  1093. const { outputNode } = builder.getNodeProperties( this );
  1094. if ( outputNode && outputNode.isNode === true ) {
  1095. return outputNode.build( builder, output );
  1096. }
  1097. }
  1098. /**
  1099. * The method can be implemented to update the node's internal state before it is used to render an object.
  1100. * The {@link Node#updateBeforeType} property defines how often the update is executed.
  1101. *
  1102. * @abstract
  1103. * @param {NodeFrame} frame - A reference to the current node frame.
  1104. * @return {Boolean?} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1105. */
  1106. updateBefore( /*frame*/ ) {
  1107. console.warn( 'Abstract function.' );
  1108. }
  1109. /**
  1110. * The method can be implemented to update the node's internal state after it was used to render an object.
  1111. * The {@link Node#updateAfterType} property defines how often the update is executed.
  1112. *
  1113. * @abstract
  1114. * @param {NodeFrame} frame - A reference to the current node frame.
  1115. * @return {Boolean?} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1116. */
  1117. updateAfter( /*frame*/ ) {
  1118. console.warn( 'Abstract function.' );
  1119. }
  1120. /**
  1121. * The method can be implemented to update the node's internal state when it is used to render an object.
  1122. * The {@link Node#updateType} property defines how often the update is executed.
  1123. *
  1124. * @abstract
  1125. * @param {NodeFrame} frame - A reference to the current node frame.
  1126. * @return {Boolean?} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1127. */
  1128. update( /*frame*/ ) {
  1129. console.warn( 'Abstract function.' );
  1130. }
  1131. /**
  1132. * This method performs the build of a node. The behavior of this method as well as its return value depend
  1133. * on the current build stage (setup, analyze or generate).
  1134. *
  1135. * @param {NodeBuilder} builder - The current node builder.
  1136. * @param {String?} output - Can be used to define the output type.
  1137. * @return {String?} When this method is executed in the setup or analyze stage, `null` is returned. In the generate stage, the generated shader string.
  1138. */
  1139. build( builder, output = null ) {
  1140. const refNode = this.getShared( builder );
  1141. if ( this !== refNode ) {
  1142. return refNode.build( builder, output );
  1143. }
  1144. builder.addNode( this );
  1145. builder.addChain( this );
  1146. /* Build stages expected results:
  1147. - "setup" -> Node
  1148. - "analyze" -> null
  1149. - "generate" -> String
  1150. */
  1151. let result = null;
  1152. const buildStage = builder.getBuildStage();
  1153. if ( buildStage === 'setup' ) {
  1154. this.updateReference( builder );
  1155. const properties = builder.getNodeProperties( this );
  1156. if ( properties.initialized !== true ) {
  1157. //const stackNodesBeforeSetup = builder.stack.nodes.length;
  1158. properties.initialized = true;
  1159. const outputNode = this.setup( builder ); // return a node or null
  1160. const isNodeOutput = outputNode && outputNode.isNode === true;
  1161. /*if ( isNodeOutput && builder.stack.nodes.length !== stackNodesBeforeSetup ) {
  1162. // !! no outputNode !!
  1163. //outputNode = builder.stack;
  1164. }*/
  1165. for ( const childNode of Object.values( properties ) ) {
  1166. if ( childNode && childNode.isNode === true ) {
  1167. childNode.build( builder );
  1168. }
  1169. }
  1170. if ( isNodeOutput ) {
  1171. outputNode.build( builder );
  1172. }
  1173. properties.outputNode = outputNode;
  1174. }
  1175. } else if ( buildStage === 'analyze' ) {
  1176. this.analyze( builder );
  1177. } else if ( buildStage === 'generate' ) {
  1178. const isGenerateOnce = this.generate.length === 1;
  1179. if ( isGenerateOnce ) {
  1180. const type = this.getNodeType( builder );
  1181. const nodeData = builder.getDataFromNode( this );
  1182. result = nodeData.snippet;
  1183. if ( result === undefined ) {
  1184. result = this.generate( builder ) || '';
  1185. nodeData.snippet = result;
  1186. } else if ( nodeData.flowCodes !== undefined && builder.context.nodeBlock !== undefined ) {
  1187. builder.addFlowCodeHierarchy( this, builder.context.nodeBlock );
  1188. }
  1189. result = builder.format( result, type, output );
  1190. } else {
  1191. result = this.generate( builder, output ) || '';
  1192. }
  1193. }
  1194. builder.removeChain( this );
  1195. builder.addSequentialNode( this );
  1196. return result;
  1197. }
  1198. /**
  1199. * Returns the child nodes as a JSON object.
  1200. *
  1201. * @return {Array<Object>} An iterable list of serialized child objects as JSON.
  1202. */
  1203. getSerializeChildren() {
  1204. return getNodeChildren( this );
  1205. }
  1206. /**
  1207. * Serializes the node to JSON.
  1208. *
  1209. * @param {Object} json - The output JSON object.
  1210. */
  1211. serialize( json ) {
  1212. const nodeChildren = this.getSerializeChildren();
  1213. const inputNodes = {};
  1214. for ( const { property, index, childNode } of nodeChildren ) {
  1215. if ( index !== undefined ) {
  1216. if ( inputNodes[ property ] === undefined ) {
  1217. inputNodes[ property ] = Number.isInteger( index ) ? [] : {};
  1218. }
  1219. inputNodes[ property ][ index ] = childNode.toJSON( json.meta ).uuid;
  1220. } else {
  1221. inputNodes[ property ] = childNode.toJSON( json.meta ).uuid;
  1222. }
  1223. }
  1224. if ( Object.keys( inputNodes ).length > 0 ) {
  1225. json.inputNodes = inputNodes;
  1226. }
  1227. }
  1228. /**
  1229. * Deserializes the node from the given JSON.
  1230. *
  1231. * @param {Object} json - The JSON object.
  1232. */
  1233. deserialize( json ) {
  1234. if ( json.inputNodes !== undefined ) {
  1235. const nodes = json.meta.nodes;
  1236. for ( const property in json.inputNodes ) {
  1237. if ( Array.isArray( json.inputNodes[ property ] ) ) {
  1238. const inputArray = [];
  1239. for ( const uuid of json.inputNodes[ property ] ) {
  1240. inputArray.push( nodes[ uuid ] );
  1241. }
  1242. this[ property ] = inputArray;
  1243. } else if ( typeof json.inputNodes[ property ] === 'object' ) {
  1244. const inputObject = {};
  1245. for ( const subProperty in json.inputNodes[ property ] ) {
  1246. const uuid = json.inputNodes[ property ][ subProperty ];
  1247. inputObject[ subProperty ] = nodes[ uuid ];
  1248. }
  1249. this[ property ] = inputObject;
  1250. } else {
  1251. const uuid = json.inputNodes[ property ];
  1252. this[ property ] = nodes[ uuid ];
  1253. }
  1254. }
  1255. }
  1256. }
  1257. /**
  1258. * Serializes the node into the three.js JSON Object/Scene format.
  1259. *
  1260. * @param {Object?} meta - An optional JSON object that already holds serialized data from other scene objects.
  1261. * @return {Object} The serialized node.
  1262. */
  1263. toJSON( meta ) {
  1264. const { uuid, type } = this;
  1265. const isRoot = ( meta === undefined || typeof meta === 'string' );
  1266. if ( isRoot ) {
  1267. meta = {
  1268. textures: {},
  1269. images: {},
  1270. nodes: {}
  1271. };
  1272. }
  1273. // serialize
  1274. let data = meta.nodes[ uuid ];
  1275. if ( data === undefined ) {
  1276. data = {
  1277. uuid,
  1278. type,
  1279. meta,
  1280. metadata: {
  1281. version: 4.6,
  1282. type: 'Node',
  1283. generator: 'Node.toJSON'
  1284. }
  1285. };
  1286. if ( isRoot !== true ) meta.nodes[ data.uuid ] = data;
  1287. this.serialize( data );
  1288. delete data.meta;
  1289. }
  1290. // TODO: Copied from Object3D.toJSON
  1291. function extractFromCache( cache ) {
  1292. const values = [];
  1293. for ( const key in cache ) {
  1294. const data = cache[ key ];
  1295. delete data.metadata;
  1296. values.push( data );
  1297. }
  1298. return values;
  1299. }
  1300. if ( isRoot ) {
  1301. const textures = extractFromCache( meta.textures );
  1302. const images = extractFromCache( meta.images );
  1303. const nodes = extractFromCache( meta.nodes );
  1304. if ( textures.length > 0 ) data.textures = textures;
  1305. if ( images.length > 0 ) data.images = images;
  1306. if ( nodes.length > 0 ) data.nodes = nodes;
  1307. }
  1308. return data;
  1309. }
  1310. }
  1311. /**
  1312. * Base class for representing element access on an array-like
  1313. * node data structures.
  1314. *
  1315. * @augments Node
  1316. */
  1317. class ArrayElementNode extends Node { // @TODO: If extending from TempNode it breaks webgpu_compute
  1318. static get type() {
  1319. return 'ArrayElementNode';
  1320. }
  1321. /**
  1322. * Constructs an array element node.
  1323. *
  1324. * @param {Node} node - The array-like node.
  1325. * @param {Node} indexNode - The index node that defines the element access.
  1326. */
  1327. constructor( node, indexNode ) {
  1328. super();
  1329. /**
  1330. * The array-like node.
  1331. *
  1332. * @type {Node}
  1333. */
  1334. this.node = node;
  1335. /**
  1336. * The index node that defines the element access.
  1337. *
  1338. * @type {Node}
  1339. */
  1340. this.indexNode = indexNode;
  1341. /**
  1342. * This flag can be used for type testing.
  1343. *
  1344. * @type {Boolean}
  1345. * @readonly
  1346. * @default true
  1347. */
  1348. this.isArrayElementNode = true;
  1349. }
  1350. /**
  1351. * This method is overwritten since the node type is inferred from the array-like node.
  1352. *
  1353. * @param {NodeBuilder} builder - The current node builder.
  1354. * @return {String} The node type.
  1355. */
  1356. getNodeType( builder ) {
  1357. return this.node.getElementType( builder );
  1358. }
  1359. generate( builder ) {
  1360. const nodeSnippet = this.node.build( builder );
  1361. const indexSnippet = this.indexNode.build( builder, 'uint' );
  1362. return `${ nodeSnippet }[ ${ indexSnippet } ]`;
  1363. }
  1364. }
  1365. /**
  1366. * This module is part of the TSL core and usually not used in app level code.
  1367. * It represents a convert operation during the shader generation process
  1368. * meaning it converts the data type of a node to a target data type.
  1369. *
  1370. * @augments Node
  1371. */
  1372. class ConvertNode extends Node {
  1373. static get type() {
  1374. return 'ConvertNode';
  1375. }
  1376. /**
  1377. * Constructs a new convert node.
  1378. *
  1379. * @param {Node} node - The node which type should be converted.
  1380. * @param {String} convertTo - The target node type. Multiple types can be defined by separating them with a `|` sign.
  1381. */
  1382. constructor( node, convertTo ) {
  1383. super();
  1384. /**
  1385. * The node which type should be converted.
  1386. *
  1387. * @type {Node}
  1388. */
  1389. this.node = node;
  1390. /**
  1391. * The target node type. Multiple types can be defined by separating them with a `|` sign.
  1392. *
  1393. * @type {String}
  1394. */
  1395. this.convertTo = convertTo;
  1396. }
  1397. /**
  1398. * This method is overwritten since the implementation tries to infer the best
  1399. * matching type from the {@link ConvertNode#convertTo} property.
  1400. *
  1401. * @param {NodeBuilder} builder - The current node builder.
  1402. * @return {String} The node type.
  1403. */
  1404. getNodeType( builder ) {
  1405. const requestType = this.node.getNodeType( builder );
  1406. let convertTo = null;
  1407. for ( const overloadingType of this.convertTo.split( '|' ) ) {
  1408. if ( convertTo === null || builder.getTypeLength( requestType ) === builder.getTypeLength( overloadingType ) ) {
  1409. convertTo = overloadingType;
  1410. }
  1411. }
  1412. return convertTo;
  1413. }
  1414. serialize( data ) {
  1415. super.serialize( data );
  1416. data.convertTo = this.convertTo;
  1417. }
  1418. deserialize( data ) {
  1419. super.deserialize( data );
  1420. this.convertTo = data.convertTo;
  1421. }
  1422. generate( builder, output ) {
  1423. const node = this.node;
  1424. const type = this.getNodeType( builder );
  1425. const snippet = node.build( builder, type );
  1426. return builder.format( snippet, type, output );
  1427. }
  1428. }
  1429. /**
  1430. * This module uses cache management to create temporary variables
  1431. * if the node is used more than once to prevent duplicate calculations.
  1432. *
  1433. * The class acts as a base class for many other nodes types.
  1434. *
  1435. * @augments Node
  1436. */
  1437. class TempNode extends Node {
  1438. static get type() {
  1439. return 'TempNode';
  1440. }
  1441. /**
  1442. * Constructs a temp node.
  1443. *
  1444. * @param {String?} nodeType - The node type.
  1445. */
  1446. constructor( nodeType = null ) {
  1447. super( nodeType );
  1448. /**
  1449. * This flag can be used for type testing.
  1450. *
  1451. * @type {Boolean}
  1452. * @readonly
  1453. * @default true
  1454. */
  1455. this.isTempNode = true;
  1456. }
  1457. /**
  1458. * Whether this node is used more than once in context of other nodes.
  1459. *
  1460. * @param {NodeBuilder} builder - The node builder.
  1461. * @return {Boolean} A flag that indicates if there is more than one dependency to other nodes.
  1462. */
  1463. hasDependencies( builder ) {
  1464. return builder.getDataFromNode( this ).usageCount > 1;
  1465. }
  1466. build( builder, output ) {
  1467. const buildStage = builder.getBuildStage();
  1468. if ( buildStage === 'generate' ) {
  1469. const type = builder.getVectorType( this.getNodeType( builder, output ) );
  1470. const nodeData = builder.getDataFromNode( this );
  1471. if ( nodeData.propertyName !== undefined ) {
  1472. return builder.format( nodeData.propertyName, type, output );
  1473. } else if ( type !== 'void' && output !== 'void' && this.hasDependencies( builder ) ) {
  1474. const snippet = super.build( builder, type );
  1475. const nodeVar = builder.getVarFromNode( this, null, type );
  1476. const propertyName = builder.getPropertyName( nodeVar );
  1477. builder.addLineFlowCode( `${ propertyName } = ${ snippet }`, this );
  1478. nodeData.snippet = snippet;
  1479. nodeData.propertyName = propertyName;
  1480. return builder.format( nodeData.propertyName, type, output );
  1481. }
  1482. }
  1483. return super.build( builder, output );
  1484. }
  1485. }
  1486. /**
  1487. * This module is part of the TSL core and usually not used in app level code.
  1488. * It represents a join operation during the shader generation process.
  1489. * For example in can compose/join two single floats into a `vec2` type.
  1490. *
  1491. * @augments TempNode
  1492. */
  1493. class JoinNode extends TempNode {
  1494. static get type() {
  1495. return 'JoinNode';
  1496. }
  1497. /**
  1498. * Constructs a new join node.
  1499. *
  1500. * @param {Array<Node>} nodes - An array of nodes that should be joined.
  1501. * @param {String?} [nodeType=null] - The node type.
  1502. */
  1503. constructor( nodes = [], nodeType = null ) {
  1504. super( nodeType );
  1505. /**
  1506. * An array of nodes that should be joined.
  1507. *
  1508. * @type {Array<Node>}
  1509. */
  1510. this.nodes = nodes;
  1511. }
  1512. /**
  1513. * This method is overwritten since the node type must be inferred from the
  1514. * joined data length if not explicitly defined.
  1515. *
  1516. * @param {NodeBuilder} builder - The current node builder.
  1517. * @return {String} The node type.
  1518. */
  1519. getNodeType( builder ) {
  1520. if ( this.nodeType !== null ) {
  1521. return builder.getVectorType( this.nodeType );
  1522. }
  1523. return builder.getTypeFromLength( this.nodes.reduce( ( count, cur ) => count + builder.getTypeLength( cur.getNodeType( builder ) ), 0 ) );
  1524. }
  1525. generate( builder, output ) {
  1526. const type = this.getNodeType( builder );
  1527. const nodes = this.nodes;
  1528. const primitiveType = builder.getComponentType( type );
  1529. const snippetValues = [];
  1530. for ( const input of nodes ) {
  1531. let inputSnippet = input.build( builder );
  1532. const inputPrimitiveType = builder.getComponentType( input.getNodeType( builder ) );
  1533. if ( inputPrimitiveType !== primitiveType ) {
  1534. inputSnippet = builder.format( inputSnippet, inputPrimitiveType, primitiveType );
  1535. }
  1536. snippetValues.push( inputSnippet );
  1537. }
  1538. const snippet = `${ builder.getType( type ) }( ${ snippetValues.join( ', ' ) } )`;
  1539. return builder.format( snippet, type, output );
  1540. }
  1541. }
  1542. const _stringVectorComponents = vectorComponents.join( '' );
  1543. /**
  1544. * This module is part of the TSL core and usually not used in app level code.
  1545. * `SplitNode` represents a property access operation which means it is
  1546. * used to implement any `.xyzw`, `.rgba` and `stpq` usage on node objects.
  1547. * For example:
  1548. * ```js
  1549. * const redValue = color.r;
  1550. * ```
  1551. *
  1552. * @augments Node
  1553. */
  1554. class SplitNode extends Node {
  1555. static get type() {
  1556. return 'SplitNode';
  1557. }
  1558. /**
  1559. * Constructs a new split node.
  1560. *
  1561. * @param {Node} node - The node that should be accessed.
  1562. * @param {String} [components='x'] - The components that should be accessed.
  1563. */
  1564. constructor( node, components = 'x' ) {
  1565. super();
  1566. /**
  1567. * The node that should be accessed.
  1568. *
  1569. * @type {Node}
  1570. */
  1571. this.node = node;
  1572. /**
  1573. * The components that should be accessed.
  1574. *
  1575. * @type {string}
  1576. */
  1577. this.components = components;
  1578. /**
  1579. * This flag can be used for type testing.
  1580. *
  1581. * @type {Boolean}
  1582. * @readonly
  1583. * @default true
  1584. */
  1585. this.isSplitNode = true;
  1586. }
  1587. /**
  1588. * Returns the vector length which is computed based on the requested components.
  1589. *
  1590. * @return {Number} The vector length.
  1591. */
  1592. getVectorLength() {
  1593. let vectorLength = this.components.length;
  1594. for ( const c of this.components ) {
  1595. vectorLength = Math.max( vectorComponents.indexOf( c ) + 1, vectorLength );
  1596. }
  1597. return vectorLength;
  1598. }
  1599. /**
  1600. * Returns the component type of the node's type.
  1601. *
  1602. * @param {NodeBuilder} builder - The current node builder.
  1603. * @return {String} The component type.
  1604. */
  1605. getComponentType( builder ) {
  1606. return builder.getComponentType( this.node.getNodeType( builder ) );
  1607. }
  1608. /**
  1609. * This method is overwritten since the node type is inferred from requested components.
  1610. *
  1611. * @param {NodeBuilder} builder - The current node builder.
  1612. * @return {String} The node type.
  1613. */
  1614. getNodeType( builder ) {
  1615. return builder.getTypeFromLength( this.components.length, this.getComponentType( builder ) );
  1616. }
  1617. generate( builder, output ) {
  1618. const node = this.node;
  1619. const nodeTypeLength = builder.getTypeLength( node.getNodeType( builder ) );
  1620. let snippet = null;
  1621. if ( nodeTypeLength > 1 ) {
  1622. let type = null;
  1623. const componentsLength = this.getVectorLength();
  1624. if ( componentsLength >= nodeTypeLength ) {
  1625. // needed expand the input node
  1626. type = builder.getTypeFromLength( this.getVectorLength(), this.getComponentType( builder ) );
  1627. }
  1628. const nodeSnippet = node.build( builder, type );
  1629. if ( this.components.length === nodeTypeLength && this.components === _stringVectorComponents.slice( 0, this.components.length ) ) {
  1630. // unnecessary swizzle
  1631. snippet = builder.format( nodeSnippet, type, output );
  1632. } else {
  1633. snippet = builder.format( `${nodeSnippet}.${this.components}`, this.getNodeType( builder ), output );
  1634. }
  1635. } else {
  1636. // ignore .components if .node returns float/integer
  1637. snippet = node.build( builder, output );
  1638. }
  1639. return snippet;
  1640. }
  1641. serialize( data ) {
  1642. super.serialize( data );
  1643. data.components = this.components;
  1644. }
  1645. deserialize( data ) {
  1646. super.deserialize( data );
  1647. this.components = data.components;
  1648. }
  1649. }
  1650. /**
  1651. * This module is part of the TSL core and usually not used in app level code.
  1652. * `SetNode` represents a set operation which means it is used to implement any
  1653. * `setXYZW()`, `setRGBA()` and `setSTPQ()` method invocations on node objects.
  1654. * For example:
  1655. * ```js
  1656. * materialLine.colorNode = color( 0, 0, 0 ).setR( float( 1 ) );
  1657. * ```
  1658. *
  1659. * @augments TempNode
  1660. */
  1661. class SetNode extends TempNode {
  1662. static get type() {
  1663. return 'SetNode';
  1664. }
  1665. /**
  1666. * Constructs a new set node.
  1667. *
  1668. * @param {Node} sourceNode - The node that should be updated.
  1669. * @param {String} components - The components that should be updated.
  1670. * @param {Node} targetNode - The value node.
  1671. */
  1672. constructor( sourceNode, components, targetNode ) {
  1673. super();
  1674. /**
  1675. * The node that should be updated.
  1676. *
  1677. * @type {Node}
  1678. */
  1679. this.sourceNode = sourceNode;
  1680. /**
  1681. * The components that should be updated.
  1682. *
  1683. * @type {String}
  1684. */
  1685. this.components = components;
  1686. /**
  1687. * The value node.
  1688. *
  1689. * @type {Node}
  1690. */
  1691. this.targetNode = targetNode;
  1692. }
  1693. /**
  1694. * This method is overwritten since the node type is inferred from {@link SetNode#sourceNode}.
  1695. *
  1696. * @param {NodeBuilder} builder - The current node builder.
  1697. * @return {String} The node type.
  1698. */
  1699. getNodeType( builder ) {
  1700. return this.sourceNode.getNodeType( builder );
  1701. }
  1702. generate( builder ) {
  1703. const { sourceNode, components, targetNode } = this;
  1704. const sourceType = this.getNodeType( builder );
  1705. const componentType = builder.getComponentType( targetNode.getNodeType( builder ) );
  1706. const targetType = builder.getTypeFromLength( components.length, componentType );
  1707. const targetSnippet = targetNode.build( builder, targetType );
  1708. const sourceSnippet = sourceNode.build( builder, sourceType );
  1709. const length = builder.getTypeLength( sourceType );
  1710. const snippetValues = [];
  1711. for ( let i = 0; i < length; i ++ ) {
  1712. const component = vectorComponents[ i ];
  1713. if ( component === components[ 0 ] ) {
  1714. snippetValues.push( targetSnippet );
  1715. i += components.length - 1;
  1716. } else {
  1717. snippetValues.push( sourceSnippet + '.' + component );
  1718. }
  1719. }
  1720. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  1721. }
  1722. }
  1723. /**
  1724. * This module is part of the TSL core and usually not used in app level code.
  1725. * It represents a flip operation during the shader generation process
  1726. * meaning it flips normalized values with the following formula:
  1727. * ```
  1728. * x = 1 - x;
  1729. * ```
  1730. * `FlipNode` is internally used to implement any `flipXYZW()`, `flipRGBA()` and
  1731. * `flipSTPQ()` method invocations on node objects. For example:
  1732. * ```js
  1733. * uvNode = uvNode.flipY();
  1734. * ```
  1735. *
  1736. * @augments TempNode
  1737. */
  1738. class FlipNode extends TempNode {
  1739. static get type() {
  1740. return 'FlipNode';
  1741. }
  1742. /**
  1743. * Constructs a new flip node.
  1744. *
  1745. * @param {Node} sourceNode - The node which component(s) should be flipped.
  1746. * @param {String} components - The components that should be flipped e.g. `'x'` or `'xy'`.
  1747. */
  1748. constructor( sourceNode, components ) {
  1749. super();
  1750. /**
  1751. * The node which component(s) should be flipped.
  1752. *
  1753. * @type {Node}
  1754. */
  1755. this.sourceNode = sourceNode;
  1756. /**
  1757. * The components that should be flipped e.g. `'x'` or `'xy'`.
  1758. *
  1759. * @type {String}
  1760. */
  1761. this.components = components;
  1762. }
  1763. /**
  1764. * This method is overwritten since the node type is inferred from the source node.
  1765. *
  1766. * @param {NodeBuilder} builder - The current node builder.
  1767. * @return {String} The node type.
  1768. */
  1769. getNodeType( builder ) {
  1770. return this.sourceNode.getNodeType( builder );
  1771. }
  1772. generate( builder ) {
  1773. const { components, sourceNode } = this;
  1774. const sourceType = this.getNodeType( builder );
  1775. const sourceSnippet = sourceNode.build( builder );
  1776. const sourceCache = builder.getVarFromNode( this );
  1777. const sourceProperty = builder.getPropertyName( sourceCache );
  1778. builder.addLineFlowCode( sourceProperty + ' = ' + sourceSnippet, this );
  1779. const length = builder.getTypeLength( sourceType );
  1780. const snippetValues = [];
  1781. let componentIndex = 0;
  1782. for ( let i = 0; i < length; i ++ ) {
  1783. const component = vectorComponents[ i ];
  1784. if ( component === components[ componentIndex ] ) {
  1785. snippetValues.push( '1.0 - ' + ( sourceProperty + '.' + component ) );
  1786. componentIndex ++;
  1787. } else {
  1788. snippetValues.push( sourceProperty + '.' + component );
  1789. }
  1790. }
  1791. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  1792. }
  1793. }
  1794. /**
  1795. * Base class for representing data input nodes.
  1796. *
  1797. * @augments Node
  1798. */
  1799. class InputNode extends Node {
  1800. static get type() {
  1801. return 'InputNode';
  1802. }
  1803. /**
  1804. * Constructs a new input node.
  1805. *
  1806. * @param {Any} value - The value of this node. This can be a any JS primitive, functions, array buffers or even three.js objects (vector, matrices, colors).
  1807. * @param {String?} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  1808. */
  1809. constructor( value, nodeType = null ) {
  1810. super( nodeType );
  1811. /**
  1812. * This flag can be used for type testing.
  1813. *
  1814. * @type {Boolean}
  1815. * @readonly
  1816. * @default true
  1817. */
  1818. this.isInputNode = true;
  1819. /**
  1820. * The value of this node. This can be a any JS primitive, functions, array buffers or even three.js objects (vector, matrices, colors).
  1821. *
  1822. * @type {Any}
  1823. */
  1824. this.value = value;
  1825. /**
  1826. * The precision of the value in the shader.
  1827. *
  1828. * @type {('low'|'medium'|'high')?}
  1829. * @default null
  1830. */
  1831. this.precision = null;
  1832. }
  1833. getNodeType( /*builder*/ ) {
  1834. if ( this.nodeType === null ) {
  1835. return getValueType( this.value );
  1836. }
  1837. return this.nodeType;
  1838. }
  1839. /**
  1840. * Returns the input type of the node which is by default the node type. Derived modules
  1841. * might overwrite this method and use a fixed type or compute one analytically.
  1842. *
  1843. * A typical example for different input and node types are textures. The input type of a
  1844. * normal RGBA texture is `texture` whereas its node type is `vec4`.
  1845. *
  1846. * @param {NodeBuilder} builder - The current node builder.
  1847. * @return {String} The input type.
  1848. */
  1849. getInputType( builder ) {
  1850. return this.getNodeType( builder );
  1851. }
  1852. /**
  1853. * Sets the precision to the given value. The method can be
  1854. * overwritten in derived classes if the final precision must be computed
  1855. * analytically.
  1856. *
  1857. * @param {('low'|'medium'|'high')} precision - The precision of the input value in the shader.
  1858. * @return {InputNode} A reference to this node.
  1859. */
  1860. setPrecision( precision ) {
  1861. this.precision = precision;
  1862. return this;
  1863. }
  1864. serialize( data ) {
  1865. super.serialize( data );
  1866. data.value = this.value;
  1867. if ( this.value && this.value.toArray ) data.value = this.value.toArray();
  1868. data.valueType = getValueType( this.value );
  1869. data.nodeType = this.nodeType;
  1870. if ( data.valueType === 'ArrayBuffer' ) data.value = arrayBufferToBase64( data.value );
  1871. data.precision = this.precision;
  1872. }
  1873. deserialize( data ) {
  1874. super.deserialize( data );
  1875. this.nodeType = data.nodeType;
  1876. this.value = Array.isArray( data.value ) ? getValueFromType( data.valueType, ...data.value ) : data.value;
  1877. this.precision = data.precision || null;
  1878. if ( this.value && this.value.fromArray ) this.value = this.value.fromArray( data.value );
  1879. }
  1880. generate( /*builder, output*/ ) {
  1881. console.warn( 'Abstract function.' );
  1882. }
  1883. }
  1884. const _regNum = /float|u?int/;
  1885. /**
  1886. * Class for representing a constant value in the shader.
  1887. *
  1888. * @augments InputNode
  1889. */
  1890. class ConstNode extends InputNode {
  1891. static get type() {
  1892. return 'ConstNode';
  1893. }
  1894. /**
  1895. * Constructs a new input node.
  1896. *
  1897. * @param {Any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color).
  1898. * @param {String?} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  1899. */
  1900. constructor( value, nodeType = null ) {
  1901. super( value, nodeType );
  1902. /**
  1903. * This flag can be used for type testing.
  1904. *
  1905. * @type {Boolean}
  1906. * @readonly
  1907. * @default true
  1908. */
  1909. this.isConstNode = true;
  1910. }
  1911. /**
  1912. * Generates the shader string of the value with the current node builder.
  1913. *
  1914. * @param {NodeBuilder} builder - The current node builder.
  1915. * @return {String} The generated value as a shader string.
  1916. */
  1917. generateConst( builder ) {
  1918. return builder.generateConst( this.getNodeType( builder ), this.value );
  1919. }
  1920. generate( builder, output ) {
  1921. const type = this.getNodeType( builder );
  1922. if ( _regNum.test( type ) && _regNum.test( output ) ) {
  1923. return builder.generateConst( output, this.value );
  1924. }
  1925. return builder.format( this.generateConst( builder ), type, output );
  1926. }
  1927. }
  1928. /** @module TSLCore **/
  1929. let currentStack = null;
  1930. const NodeElements = new Map();
  1931. function addMethodChaining( name, nodeElement ) {
  1932. if ( NodeElements.has( name ) ) {
  1933. console.warn( `Redefinition of method chaining ${ name }` );
  1934. return;
  1935. }
  1936. if ( typeof nodeElement !== 'function' ) throw new Error( `Node element ${ name } is not a function` );
  1937. NodeElements.set( name, nodeElement );
  1938. }
  1939. const parseSwizzle = ( props ) => props.replace( /r|s/g, 'x' ).replace( /g|t/g, 'y' ).replace( /b|p/g, 'z' ).replace( /a|q/g, 'w' );
  1940. const parseSwizzleAndSort = ( props ) => parseSwizzle( props ).split( '' ).sort().join( '' );
  1941. const shaderNodeHandler = {
  1942. setup( NodeClosure, params ) {
  1943. const inputs = params.shift();
  1944. return NodeClosure( nodeObjects( inputs ), ...params );
  1945. },
  1946. get( node, prop, nodeObj ) {
  1947. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  1948. if ( node.isStackNode !== true && prop === 'assign' ) {
  1949. return ( ...params ) => {
  1950. currentStack.assign( nodeObj, ...params );
  1951. return nodeObj;
  1952. };
  1953. } else if ( NodeElements.has( prop ) ) {
  1954. const nodeElement = NodeElements.get( prop );
  1955. return node.isStackNode ? ( ...params ) => nodeObj.add( nodeElement( ...params ) ) : ( ...params ) => nodeElement( nodeObj, ...params );
  1956. } else if ( prop === 'self' ) {
  1957. return node;
  1958. } else if ( prop.endsWith( 'Assign' ) && NodeElements.has( prop.slice( 0, prop.length - 'Assign'.length ) ) ) {
  1959. const nodeElement = NodeElements.get( prop.slice( 0, prop.length - 'Assign'.length ) );
  1960. return node.isStackNode ? ( ...params ) => nodeObj.assign( params[ 0 ], nodeElement( ...params ) ) : ( ...params ) => nodeObj.assign( nodeElement( nodeObj, ...params ) );
  1961. } else if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true ) {
  1962. // accessing properties ( swizzle )
  1963. prop = parseSwizzle( prop );
  1964. return nodeObject( new SplitNode( nodeObj, prop ) );
  1965. } else if ( /^set[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  1966. // set properties ( swizzle ) and sort to xyzw sequence
  1967. prop = parseSwizzleAndSort( prop.slice( 3 ).toLowerCase() );
  1968. return ( value ) => nodeObject( new SetNode( node, prop, value ) );
  1969. } else if ( /^flip[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  1970. // set properties ( swizzle ) and sort to xyzw sequence
  1971. prop = parseSwizzleAndSort( prop.slice( 4 ).toLowerCase() );
  1972. return () => nodeObject( new FlipNode( nodeObject( node ), prop ) );
  1973. } else if ( prop === 'width' || prop === 'height' || prop === 'depth' ) {
  1974. // accessing property
  1975. if ( prop === 'width' ) prop = 'x';
  1976. else if ( prop === 'height' ) prop = 'y';
  1977. else if ( prop === 'depth' ) prop = 'z';
  1978. return nodeObject( new SplitNode( node, prop ) );
  1979. } else if ( /^\d+$/.test( prop ) === true ) {
  1980. // accessing array
  1981. return nodeObject( new ArrayElementNode( nodeObj, new ConstNode( Number( prop ), 'uint' ) ) );
  1982. }
  1983. }
  1984. return Reflect.get( node, prop, nodeObj );
  1985. },
  1986. set( node, prop, value, nodeObj ) {
  1987. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  1988. // setting properties
  1989. if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true || prop === 'width' || prop === 'height' || prop === 'depth' || /^\d+$/.test( prop ) === true ) {
  1990. nodeObj[ prop ].assign( value );
  1991. return true;
  1992. }
  1993. }
  1994. return Reflect.set( node, prop, value, nodeObj );
  1995. }
  1996. };
  1997. const nodeObjectsCacheMap = new WeakMap();
  1998. const nodeBuilderFunctionsCacheMap = new WeakMap();
  1999. const ShaderNodeObject = function ( obj, altType = null ) {
  2000. const type = getValueType( obj );
  2001. if ( type === 'node' ) {
  2002. let nodeObject = nodeObjectsCacheMap.get( obj );
  2003. if ( nodeObject === undefined ) {
  2004. nodeObject = new Proxy( obj, shaderNodeHandler );
  2005. nodeObjectsCacheMap.set( obj, nodeObject );
  2006. nodeObjectsCacheMap.set( nodeObject, nodeObject );
  2007. }
  2008. return nodeObject;
  2009. } else if ( ( altType === null && ( type === 'float' || type === 'boolean' ) ) || ( type && type !== 'shader' && type !== 'string' ) ) {
  2010. return nodeObject( getConstNode( obj, altType ) );
  2011. } else if ( type === 'shader' ) {
  2012. return Fn( obj );
  2013. }
  2014. return obj;
  2015. };
  2016. const ShaderNodeObjects = function ( objects, altType = null ) {
  2017. for ( const name in objects ) {
  2018. objects[ name ] = nodeObject( objects[ name ], altType );
  2019. }
  2020. return objects;
  2021. };
  2022. const ShaderNodeArray = function ( array, altType = null ) {
  2023. const len = array.length;
  2024. for ( let i = 0; i < len; i ++ ) {
  2025. array[ i ] = nodeObject( array[ i ], altType );
  2026. }
  2027. return array;
  2028. };
  2029. const ShaderNodeProxy = function ( NodeClass, scope = null, factor = null, settings = null ) {
  2030. const assignNode = ( node ) => nodeObject( settings !== null ? Object.assign( node, settings ) : node );
  2031. if ( scope === null ) {
  2032. return ( ...params ) => {
  2033. return assignNode( new NodeClass( ...nodeArray( params ) ) );
  2034. };
  2035. } else if ( factor !== null ) {
  2036. factor = nodeObject( factor );
  2037. return ( ...params ) => {
  2038. return assignNode( new NodeClass( scope, ...nodeArray( params ), factor ) );
  2039. };
  2040. } else {
  2041. return ( ...params ) => {
  2042. return assignNode( new NodeClass( scope, ...nodeArray( params ) ) );
  2043. };
  2044. }
  2045. };
  2046. const ShaderNodeImmutable = function ( NodeClass, ...params ) {
  2047. return nodeObject( new NodeClass( ...nodeArray( params ) ) );
  2048. };
  2049. class ShaderCallNodeInternal extends Node {
  2050. constructor( shaderNode, inputNodes ) {
  2051. super();
  2052. this.shaderNode = shaderNode;
  2053. this.inputNodes = inputNodes;
  2054. }
  2055. getNodeType( builder ) {
  2056. return this.shaderNode.nodeType || this.getOutputNode( builder ).getNodeType( builder );
  2057. }
  2058. call( builder ) {
  2059. const { shaderNode, inputNodes } = this;
  2060. const properties = builder.getNodeProperties( shaderNode );
  2061. if ( properties.onceOutput ) return properties.onceOutput;
  2062. //
  2063. let result = null;
  2064. if ( shaderNode.layout ) {
  2065. let functionNodesCacheMap = nodeBuilderFunctionsCacheMap.get( builder.constructor );
  2066. if ( functionNodesCacheMap === undefined ) {
  2067. functionNodesCacheMap = new WeakMap();
  2068. nodeBuilderFunctionsCacheMap.set( builder.constructor, functionNodesCacheMap );
  2069. }
  2070. let functionNode = functionNodesCacheMap.get( shaderNode );
  2071. if ( functionNode === undefined ) {
  2072. functionNode = nodeObject( builder.buildFunctionNode( shaderNode ) );
  2073. functionNodesCacheMap.set( shaderNode, functionNode );
  2074. }
  2075. if ( builder.currentFunctionNode !== null ) {
  2076. builder.currentFunctionNode.includes.push( functionNode );
  2077. }
  2078. result = nodeObject( functionNode.call( inputNodes ) );
  2079. } else {
  2080. const jsFunc = shaderNode.jsFunc;
  2081. const outputNode = inputNodes !== null || jsFunc.length > 1 ? jsFunc( inputNodes || [], builder ) : jsFunc( builder );
  2082. result = nodeObject( outputNode );
  2083. }
  2084. if ( shaderNode.once ) {
  2085. properties.onceOutput = result;
  2086. }
  2087. return result;
  2088. }
  2089. getOutputNode( builder ) {
  2090. const properties = builder.getNodeProperties( this );
  2091. if ( properties.outputNode === null ) {
  2092. properties.outputNode = this.setupOutput( builder );
  2093. }
  2094. return properties.outputNode;
  2095. }
  2096. setup( builder ) {
  2097. return this.getOutputNode( builder );
  2098. }
  2099. setupOutput( builder ) {
  2100. builder.addStack();
  2101. builder.stack.outputNode = this.call( builder );
  2102. return builder.removeStack();
  2103. }
  2104. generate( builder, output ) {
  2105. const outputNode = this.getOutputNode( builder );
  2106. return outputNode.build( builder, output );
  2107. }
  2108. }
  2109. class ShaderNodeInternal extends Node {
  2110. constructor( jsFunc, nodeType ) {
  2111. super( nodeType );
  2112. this.jsFunc = jsFunc;
  2113. this.layout = null;
  2114. this.global = true;
  2115. this.once = false;
  2116. }
  2117. setLayout( layout ) {
  2118. this.layout = layout;
  2119. return this;
  2120. }
  2121. call( inputs = null ) {
  2122. nodeObjects( inputs );
  2123. return nodeObject( new ShaderCallNodeInternal( this, inputs ) );
  2124. }
  2125. setup() {
  2126. return this.call();
  2127. }
  2128. }
  2129. const bools = [ false, true ];
  2130. const uints = [ 0, 1, 2, 3 ];
  2131. const ints = [ -1, -2 ];
  2132. 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 ];
  2133. const boolsCacheMap = new Map();
  2134. for ( const bool of bools ) boolsCacheMap.set( bool, new ConstNode( bool ) );
  2135. const uintsCacheMap = new Map();
  2136. for ( const uint of uints ) uintsCacheMap.set( uint, new ConstNode( uint, 'uint' ) );
  2137. const intsCacheMap = new Map( [ ...uintsCacheMap ].map( el => new ConstNode( el.value, 'int' ) ) );
  2138. for ( const int of ints ) intsCacheMap.set( int, new ConstNode( int, 'int' ) );
  2139. const floatsCacheMap = new Map( [ ...intsCacheMap ].map( el => new ConstNode( el.value ) ) );
  2140. for ( const float of floats ) floatsCacheMap.set( float, new ConstNode( float ) );
  2141. for ( const float of floats ) floatsCacheMap.set( - float, new ConstNode( - float ) );
  2142. const cacheMaps = { bool: boolsCacheMap, uint: uintsCacheMap, ints: intsCacheMap, float: floatsCacheMap };
  2143. const constNodesCacheMap = new Map( [ ...boolsCacheMap, ...floatsCacheMap ] );
  2144. const getConstNode = ( value, type ) => {
  2145. if ( constNodesCacheMap.has( value ) ) {
  2146. return constNodesCacheMap.get( value );
  2147. } else if ( value.isNode === true ) {
  2148. return value;
  2149. } else {
  2150. return new ConstNode( value, type );
  2151. }
  2152. };
  2153. const safeGetNodeType = ( node ) => {
  2154. try {
  2155. return node.getNodeType();
  2156. } catch ( _ ) {
  2157. return undefined;
  2158. }
  2159. };
  2160. const ConvertType = function ( type, cacheMap = null ) {
  2161. return ( ...params ) => {
  2162. if ( params.length === 0 || ( ! [ 'bool', 'float', 'int', 'uint' ].includes( type ) && params.every( param => typeof param !== 'object' ) ) ) {
  2163. params = [ getValueFromType( type, ...params ) ];
  2164. }
  2165. if ( params.length === 1 && cacheMap !== null && cacheMap.has( params[ 0 ] ) ) {
  2166. return nodeObject( cacheMap.get( params[ 0 ] ) );
  2167. }
  2168. if ( params.length === 1 ) {
  2169. const node = getConstNode( params[ 0 ], type );
  2170. if ( safeGetNodeType( node ) === type ) return nodeObject( node );
  2171. return nodeObject( new ConvertNode( node, type ) );
  2172. }
  2173. const nodes = params.map( param => getConstNode( param ) );
  2174. return nodeObject( new JoinNode( nodes, type ) );
  2175. };
  2176. };
  2177. // exports
  2178. const defined = ( v ) => typeof v === 'object' && v !== null ? v.value : v; // TODO: remove boolean conversion and defined function
  2179. // utils
  2180. const getConstNodeType = ( value ) => ( value !== undefined && value !== null ) ? ( value.nodeType || value.convertTo || ( typeof value === 'string' ? value : null ) ) : null;
  2181. // shader node base
  2182. function ShaderNode( jsFunc, nodeType ) {
  2183. return new Proxy( new ShaderNodeInternal( jsFunc, nodeType ), shaderNodeHandler );
  2184. }
  2185. const nodeObject = ( val, altType = null ) => /* new */ ShaderNodeObject( val, altType );
  2186. const nodeObjects = ( val, altType = null ) => new ShaderNodeObjects( val, altType );
  2187. const nodeArray = ( val, altType = null ) => new ShaderNodeArray( val, altType );
  2188. const nodeProxy = ( ...params ) => new ShaderNodeProxy( ...params );
  2189. const nodeImmutable = ( ...params ) => new ShaderNodeImmutable( ...params );
  2190. const Fn = ( jsFunc, nodeType ) => {
  2191. const shaderNode = new ShaderNode( jsFunc, nodeType );
  2192. const fn = ( ...params ) => {
  2193. let inputs;
  2194. nodeObjects( params );
  2195. if ( params[ 0 ] && params[ 0 ].isNode ) {
  2196. inputs = [ ...params ];
  2197. } else {
  2198. inputs = params[ 0 ];
  2199. }
  2200. return shaderNode.call( inputs );
  2201. };
  2202. fn.shaderNode = shaderNode;
  2203. fn.setLayout = ( layout ) => {
  2204. shaderNode.setLayout( layout );
  2205. return fn;
  2206. };
  2207. fn.once = () => {
  2208. shaderNode.once = true;
  2209. return fn;
  2210. };
  2211. return fn;
  2212. };
  2213. /**
  2214. * @function
  2215. * @deprecated since r168. Use {@link Fn} instead.
  2216. *
  2217. * @param {...any} params
  2218. * @returns {Function}
  2219. */
  2220. const tslFn = ( ...params ) => { // @deprecated, r168
  2221. console.warn( 'TSL.ShaderNode: tslFn() has been renamed to Fn().' );
  2222. return Fn( ...params );
  2223. };
  2224. //
  2225. addMethodChaining( 'toGlobal', ( node ) => {
  2226. node.global = true;
  2227. return node;
  2228. } );
  2229. //
  2230. const setCurrentStack = ( stack ) => {
  2231. currentStack = stack;
  2232. };
  2233. const getCurrentStack = () => currentStack;
  2234. const If = ( ...params ) => currentStack.If( ...params );
  2235. function append( node ) {
  2236. if ( currentStack ) currentStack.add( node );
  2237. return node;
  2238. }
  2239. addMethodChaining( 'append', append );
  2240. // types
  2241. const color = new ConvertType( 'color' );
  2242. const float = new ConvertType( 'float', cacheMaps.float );
  2243. const int = new ConvertType( 'int', cacheMaps.ints );
  2244. const uint = new ConvertType( 'uint', cacheMaps.uint );
  2245. const bool = new ConvertType( 'bool', cacheMaps.bool );
  2246. const vec2 = new ConvertType( 'vec2' );
  2247. const ivec2 = new ConvertType( 'ivec2' );
  2248. const uvec2 = new ConvertType( 'uvec2' );
  2249. const bvec2 = new ConvertType( 'bvec2' );
  2250. const vec3 = new ConvertType( 'vec3' );
  2251. const ivec3 = new ConvertType( 'ivec3' );
  2252. const uvec3 = new ConvertType( 'uvec3' );
  2253. const bvec3 = new ConvertType( 'bvec3' );
  2254. const vec4 = new ConvertType( 'vec4' );
  2255. const ivec4 = new ConvertType( 'ivec4' );
  2256. const uvec4 = new ConvertType( 'uvec4' );
  2257. const bvec4 = new ConvertType( 'bvec4' );
  2258. const mat2 = new ConvertType( 'mat2' );
  2259. const mat3 = new ConvertType( 'mat3' );
  2260. const mat4 = new ConvertType( 'mat4' );
  2261. const string = ( value = '' ) => nodeObject( new ConstNode( value, 'string' ) );
  2262. const arrayBuffer = ( value ) => nodeObject( new ConstNode( value, 'ArrayBuffer' ) );
  2263. addMethodChaining( 'toColor', color );
  2264. addMethodChaining( 'toFloat', float );
  2265. addMethodChaining( 'toInt', int );
  2266. addMethodChaining( 'toUint', uint );
  2267. addMethodChaining( 'toBool', bool );
  2268. addMethodChaining( 'toVec2', vec2 );
  2269. addMethodChaining( 'toIVec2', ivec2 );
  2270. addMethodChaining( 'toUVec2', uvec2 );
  2271. addMethodChaining( 'toBVec2', bvec2 );
  2272. addMethodChaining( 'toVec3', vec3 );
  2273. addMethodChaining( 'toIVec3', ivec3 );
  2274. addMethodChaining( 'toUVec3', uvec3 );
  2275. addMethodChaining( 'toBVec3', bvec3 );
  2276. addMethodChaining( 'toVec4', vec4 );
  2277. addMethodChaining( 'toIVec4', ivec4 );
  2278. addMethodChaining( 'toUVec4', uvec4 );
  2279. addMethodChaining( 'toBVec4', bvec4 );
  2280. addMethodChaining( 'toMat2', mat2 );
  2281. addMethodChaining( 'toMat3', mat3 );
  2282. addMethodChaining( 'toMat4', mat4 );
  2283. // basic nodes
  2284. const element = /*@__PURE__*/ nodeProxy( ArrayElementNode );
  2285. const convert = ( node, types ) => nodeObject( new ConvertNode( nodeObject( node ), types ) );
  2286. const split = ( node, channels ) => nodeObject( new SplitNode( nodeObject( node ), channels ) );
  2287. addMethodChaining( 'element', element );
  2288. addMethodChaining( 'convert', convert );
  2289. /** @module ArrayNode **/
  2290. /**
  2291. * ArrayNode represents a collection of nodes, typically created using the {@link module:TSL~array} function.
  2292. * ```js
  2293. * const colors = array( [
  2294. * vec3( 1, 0, 0 ),
  2295. * vec3( 0, 1, 0 ),
  2296. * vec3( 0, 0, 1 )
  2297. * ] );
  2298. *
  2299. * const redColor = tintColors.element( 0 );
  2300. *
  2301. * @augments Node
  2302. */
  2303. class ArrayNode extends TempNode {
  2304. static get type() {
  2305. return 'ArrayNode';
  2306. }
  2307. /**
  2308. * Constructs a new array node.
  2309. *
  2310. * @param {String} [nodeType] - The data type of the elements.
  2311. * @param {Number} [count] - Size of the array.
  2312. * @param {Array<Node>?} [values=null] - Array default values.
  2313. */
  2314. constructor( nodeType, count, values = null ) {
  2315. super( nodeType );
  2316. /**
  2317. * Array size.
  2318. *
  2319. * @type {Array<Node>}
  2320. */
  2321. this.count = count;
  2322. /**
  2323. * Array default values.
  2324. *
  2325. * @type {Array<Node>}
  2326. */
  2327. this.values = values;
  2328. /**
  2329. * This flag can be used for type testing.
  2330. *
  2331. * @type {Boolean}
  2332. * @readonly
  2333. * @default true
  2334. */
  2335. this.isArrayNode = true;
  2336. }
  2337. getNodeType( builder ) {
  2338. if ( this.nodeType === null ) {
  2339. this.nodeType = this.values[ 0 ].getNodeType( builder );
  2340. }
  2341. return this.nodeType;
  2342. }
  2343. getElementType( builder ) {
  2344. return this.getNodeType( builder );
  2345. }
  2346. generate( builder ) {
  2347. const type = this.getNodeType( builder );
  2348. return builder.generateArray( type, this.count, this.values );
  2349. }
  2350. }
  2351. /**
  2352. * TSL function for creating an array node.
  2353. *
  2354. * @function
  2355. * @param {String|Array<Node>} nodeTypeOrValues - A string representing the element type (e.g., 'vec3')
  2356. * or an array containing the default values (e.g., [ vec3() ]).
  2357. * @param {Number?} [count] - Size of the array.
  2358. * @returns {ArrayNode}
  2359. */
  2360. const array = ( ...params ) => {
  2361. let node;
  2362. if ( params.length === 1 ) {
  2363. const values = params[ 0 ];
  2364. node = new ArrayNode( null, values.length, values );
  2365. } else {
  2366. const nodeType = params[ 0 ];
  2367. const count = params[ 1 ];
  2368. node = new ArrayNode( nodeType, count );
  2369. }
  2370. return nodeObject( node );
  2371. };
  2372. addMethodChaining( 'toArray', ( node, count ) => array( Array( count ).fill( node ) ) );
  2373. /** @module UniformGroupNode **/
  2374. /**
  2375. * This node can be used to group single instances of {@link UniformNode}
  2376. * and manage them as a uniform buffer.
  2377. *
  2378. * In most cases, the predefined nodes `objectGroup`, `renderGroup` and `frameGroup`
  2379. * will be used when defining the {@link UniformNode#groupNode} property.
  2380. *
  2381. * - `objectGroup`: Uniform buffer per object.
  2382. * - `renderGroup`: Shared uniform buffer, updated once per render call.
  2383. * - `frameGroup`: Shared uniform buffer, updated once per frame.
  2384. *
  2385. * @augments Node
  2386. */
  2387. class UniformGroupNode extends Node {
  2388. static get type() {
  2389. return 'UniformGroupNode';
  2390. }
  2391. /**
  2392. * Constructs a new uniform group node.
  2393. *
  2394. * @param {String} name - The name of the uniform group node.
  2395. * @param {Boolean} [shared=false] - Whether this uniform group node is shared or not.
  2396. * @param {Number} [order=1] - Influences the internal sorting.
  2397. */
  2398. constructor( name, shared = false, order = 1 ) {
  2399. super( 'string' );
  2400. /**
  2401. * The name of the uniform group node.
  2402. *
  2403. * @type {String}
  2404. */
  2405. this.name = name;
  2406. /**
  2407. * Whether this uniform group node is shared or not.
  2408. *
  2409. * @type {Boolean}
  2410. * @default false
  2411. */
  2412. this.shared = shared;
  2413. /**
  2414. * Influences the internal sorting.
  2415. * TODO: Add details when this property should be changed.
  2416. *
  2417. * @type {Number}
  2418. * @default 1
  2419. */
  2420. this.order = order;
  2421. /**
  2422. * This flag can be used for type testing.
  2423. *
  2424. * @type {Boolean}
  2425. * @readonly
  2426. * @default true
  2427. */
  2428. this.isUniformGroup = true;
  2429. }
  2430. serialize( data ) {
  2431. super.serialize( data );
  2432. data.name = this.name;
  2433. data.version = this.version;
  2434. data.shared = this.shared;
  2435. }
  2436. deserialize( data ) {
  2437. super.deserialize( data );
  2438. this.name = data.name;
  2439. this.version = data.version;
  2440. this.shared = data.shared;
  2441. }
  2442. }
  2443. /**
  2444. * TSL function for creating a uniform group node with the given name.
  2445. *
  2446. * @function
  2447. * @param {String} name - The name of the uniform group node.
  2448. * @returns {UniformGroupNode}
  2449. */
  2450. const uniformGroup = ( name ) => new UniformGroupNode( name );
  2451. /**
  2452. * TSL function for creating a shared uniform group node with the given name and order.
  2453. *
  2454. * @function
  2455. * @param {String} name - The name of the uniform group node.
  2456. * @param {Number} [order=0] - Influences the internal sorting.
  2457. * @returns {UniformGroupNode}
  2458. */
  2459. const sharedUniformGroup = ( name, order = 0 ) => new UniformGroupNode( name, true, order );
  2460. /**
  2461. * TSL object that represents a shared uniform group node which is updated once per frame.
  2462. *
  2463. * @type {UniformGroupNode}
  2464. */
  2465. const frameGroup = /*@__PURE__*/ sharedUniformGroup( 'frame' );
  2466. /**
  2467. * TSL object that represents a shared uniform group node which is updated once per render.
  2468. *
  2469. * @type {UniformGroupNode}
  2470. */
  2471. const renderGroup = /*@__PURE__*/ sharedUniformGroup( 'render' );
  2472. /**
  2473. * TSL object that represents a uniform group node which is updated once per object.
  2474. *
  2475. * @type {UniformGroupNode}
  2476. */
  2477. const objectGroup = /*@__PURE__*/ uniformGroup( 'object' );
  2478. /** @module UniformNode **/
  2479. /**
  2480. * Class for representing a uniform.
  2481. *
  2482. * @augments InputNode
  2483. */
  2484. class UniformNode extends InputNode {
  2485. static get type() {
  2486. return 'UniformNode';
  2487. }
  2488. /**
  2489. * Constructs a new uniform node.
  2490. *
  2491. * @param {Any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  2492. * @param {String?} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2493. */
  2494. constructor( value, nodeType = null ) {
  2495. super( value, nodeType );
  2496. /**
  2497. * This flag can be used for type testing.
  2498. *
  2499. * @type {Boolean}
  2500. * @readonly
  2501. * @default true
  2502. */
  2503. this.isUniformNode = true;
  2504. /**
  2505. * The name or label of the uniform.
  2506. *
  2507. * @type {String}
  2508. * @default ''
  2509. */
  2510. this.name = '';
  2511. /**
  2512. * The uniform group of this uniform. By default, uniforms are
  2513. * managed per object but they might belong to a shared group
  2514. * which is updated per frame or render call.
  2515. *
  2516. * @type {UniformGroupNode}
  2517. */
  2518. this.groupNode = objectGroup;
  2519. }
  2520. /**
  2521. * Sets the {@link UniformNode#name} property.
  2522. *
  2523. * @param {String} name - The name of the uniform.
  2524. * @return {UniformNode} A reference to this node.
  2525. */
  2526. label( name ) {
  2527. this.name = name;
  2528. return this;
  2529. }
  2530. /**
  2531. * Sets the {@link UniformNode#groupNode} property.
  2532. *
  2533. * @param {UniformGroupNode} group - The uniform group.
  2534. * @return {UniformNode} A reference to this node.
  2535. */
  2536. setGroup( group ) {
  2537. this.groupNode = group;
  2538. return this;
  2539. }
  2540. /**
  2541. * Returns the {@link UniformNode#groupNode}.
  2542. *
  2543. * @return {UniformGroupNode} The uniform group.
  2544. */
  2545. getGroup() {
  2546. return this.groupNode;
  2547. }
  2548. /**
  2549. * By default, this method returns the result of {@link Node#getHash} but derived
  2550. * classes might overwrite this method with a different implementation.
  2551. *
  2552. * @param {NodeBuilder} builder - The current node builder.
  2553. * @return {String} The uniform hash.
  2554. */
  2555. getUniformHash( builder ) {
  2556. return this.getHash( builder );
  2557. }
  2558. onUpdate( callback, updateType ) {
  2559. const self = this.getSelf();
  2560. callback = callback.bind( self );
  2561. return super.onUpdate( ( frame ) => {
  2562. const value = callback( frame, self );
  2563. if ( value !== undefined ) {
  2564. this.value = value;
  2565. }
  2566. }, updateType );
  2567. }
  2568. generate( builder, output ) {
  2569. const type = this.getNodeType( builder );
  2570. const hash = this.getUniformHash( builder );
  2571. let sharedNode = builder.getNodeFromHash( hash );
  2572. if ( sharedNode === undefined ) {
  2573. builder.setHashNode( this, hash );
  2574. sharedNode = this;
  2575. }
  2576. const sharedNodeType = sharedNode.getInputType( builder );
  2577. const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, this.name || builder.context.label );
  2578. const propertyName = builder.getPropertyName( nodeUniform );
  2579. if ( builder.context.label !== undefined ) delete builder.context.label;
  2580. return builder.format( propertyName, type, output );
  2581. }
  2582. }
  2583. /**
  2584. * TSL function for creating a uniform node.
  2585. *
  2586. * @function
  2587. * @param {Any} arg1 - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  2588. * @param {String?} arg2 - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2589. * @returns {UniformNode}
  2590. */
  2591. const uniform = ( arg1, arg2 ) => {
  2592. const nodeType = getConstNodeType( arg2 || arg1 );
  2593. // @TODO: get ConstNode from .traverse() in the future
  2594. const value = ( arg1 && arg1.isNode === true ) ? ( arg1.node && arg1.node.value ) || arg1.value : arg1;
  2595. return nodeObject( new UniformNode( value, nodeType ) );
  2596. };
  2597. /** @module PropertyNode **/
  2598. /**
  2599. * This class represents a shader property. It can be used
  2600. * to explicitly define a property and assign a value to it.
  2601. *
  2602. * ```js
  2603. * const threshold = property( 'float', 'threshold' ).assign( THRESHOLD );
  2604. *```
  2605. * `PropertyNode` is used by the engine to predefined common material properties
  2606. * for TSL code.
  2607. *
  2608. * @augments Node
  2609. */
  2610. class PropertyNode extends Node {
  2611. static get type() {
  2612. return 'PropertyNode';
  2613. }
  2614. /**
  2615. * Constructs a new property node.
  2616. *
  2617. * @param {String} nodeType - The type of the node.
  2618. * @param {String?} [name=null] - The name of the property in the shader.
  2619. * @param {Boolean} [varying=false] - Whether this property is a varying or not.
  2620. */
  2621. constructor( nodeType, name = null, varying = false ) {
  2622. super( nodeType );
  2623. /**
  2624. * The name of the property in the shader. If no name is defined,
  2625. * the node system auto-generates one.
  2626. *
  2627. * @type {String?}
  2628. * @default null
  2629. */
  2630. this.name = name;
  2631. /**
  2632. * Whether this property is a varying or not.
  2633. *
  2634. * @type {Boolean}
  2635. * @default false
  2636. */
  2637. this.varying = varying;
  2638. /**
  2639. * This flag can be used for type testing.
  2640. *
  2641. * @type {Boolean}
  2642. * @readonly
  2643. * @default true
  2644. */
  2645. this.isPropertyNode = true;
  2646. }
  2647. getHash( builder ) {
  2648. return this.name || super.getHash( builder );
  2649. }
  2650. /**
  2651. * The method is overwritten so it always returns `true`.
  2652. *
  2653. * @param {NodeBuilder} builder - The current node builder.
  2654. * @return {Boolean} Whether this node is global or not.
  2655. */
  2656. isGlobal( /*builder*/ ) {
  2657. return true;
  2658. }
  2659. generate( builder ) {
  2660. let nodeVar;
  2661. if ( this.varying === true ) {
  2662. nodeVar = builder.getVaryingFromNode( this, this.name );
  2663. nodeVar.needsInterpolation = true;
  2664. } else {
  2665. nodeVar = builder.getVarFromNode( this, this.name );
  2666. }
  2667. return builder.getPropertyName( nodeVar );
  2668. }
  2669. }
  2670. /**
  2671. * TSL function for creating a property node.
  2672. *
  2673. * @function
  2674. * @param {String} type - The type of the node.
  2675. * @param {String?} [name=null] - The name of the property in the shader.
  2676. * @returns {PropertyNode}
  2677. */
  2678. const property = ( type, name ) => nodeObject( new PropertyNode( type, name ) );
  2679. /**
  2680. * TSL function for creating a varying property node.
  2681. *
  2682. * @function
  2683. * @param {String} type - The type of the node.
  2684. * @param {String?} [name=null] - The name of the varying in the shader.
  2685. * @returns {PropertyNode}
  2686. */
  2687. const varyingProperty = ( type, name ) => nodeObject( new PropertyNode( type, name, true ) );
  2688. /**
  2689. * TSL object that represents the shader variable `DiffuseColor`.
  2690. *
  2691. * @type {PropertyNode<vec4>}
  2692. */
  2693. const diffuseColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'DiffuseColor' );
  2694. /**
  2695. * TSL object that represents the shader variable `EmissiveColor`.
  2696. *
  2697. * @type {PropertyNode<vec3>}
  2698. */
  2699. const emissive = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'EmissiveColor' );
  2700. /**
  2701. * TSL object that represents the shader variable `Roughness`.
  2702. *
  2703. * @type {PropertyNode<float>}
  2704. */
  2705. const roughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Roughness' );
  2706. /**
  2707. * TSL object that represents the shader variable `Metalness`.
  2708. *
  2709. * @type {PropertyNode<float>}
  2710. */
  2711. const metalness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Metalness' );
  2712. /**
  2713. * TSL object that represents the shader variable `Clearcoat`.
  2714. *
  2715. * @type {PropertyNode<float>}
  2716. */
  2717. const clearcoat = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Clearcoat' );
  2718. /**
  2719. * TSL object that represents the shader variable `ClearcoatRoughness`.
  2720. *
  2721. * @type {PropertyNode<float>}
  2722. */
  2723. const clearcoatRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'ClearcoatRoughness' );
  2724. /**
  2725. * TSL object that represents the shader variable `Sheen`.
  2726. *
  2727. * @type {PropertyNode<vec3>}
  2728. */
  2729. const sheen = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'Sheen' );
  2730. /**
  2731. * TSL object that represents the shader variable `SheenRoughness`.
  2732. *
  2733. * @type {PropertyNode<float>}
  2734. */
  2735. const sheenRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SheenRoughness' );
  2736. /**
  2737. * TSL object that represents the shader variable `Iridescence`.
  2738. *
  2739. * @type {PropertyNode<float>}
  2740. */
  2741. const iridescence = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Iridescence' );
  2742. /**
  2743. * TSL object that represents the shader variable `IridescenceIOR`.
  2744. *
  2745. * @type {PropertyNode<float>}
  2746. */
  2747. const iridescenceIOR = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceIOR' );
  2748. /**
  2749. * TSL object that represents the shader variable `IridescenceThickness`.
  2750. *
  2751. * @type {PropertyNode<float>}
  2752. */
  2753. const iridescenceThickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceThickness' );
  2754. /**
  2755. * TSL object that represents the shader variable `AlphaT`.
  2756. *
  2757. * @type {PropertyNode<float>}
  2758. */
  2759. const alphaT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AlphaT' );
  2760. /**
  2761. * TSL object that represents the shader variable `Anisotropy`.
  2762. *
  2763. * @type {PropertyNode<float>}
  2764. */
  2765. const anisotropy = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Anisotropy' );
  2766. /**
  2767. * TSL object that represents the shader variable `AnisotropyT`.
  2768. *
  2769. * @type {PropertyNode<vec3>}
  2770. */
  2771. const anisotropyT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyT' );
  2772. /**
  2773. * TSL object that represents the shader variable `AnisotropyB`.
  2774. *
  2775. * @type {PropertyNode<vec3>}
  2776. */
  2777. const anisotropyB = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyB' );
  2778. /**
  2779. * TSL object that represents the shader variable `SpecularColor`.
  2780. *
  2781. * @type {PropertyNode<color>}
  2782. */
  2783. const specularColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'SpecularColor' );
  2784. /**
  2785. * TSL object that represents the shader variable `SpecularF90`.
  2786. *
  2787. * @type {PropertyNode<float>}
  2788. */
  2789. const specularF90 = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SpecularF90' );
  2790. /**
  2791. * TSL object that represents the shader variable `Shininess`.
  2792. *
  2793. * @type {PropertyNode<float>}
  2794. */
  2795. const shininess = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Shininess' );
  2796. /**
  2797. * TSL object that represents the shader variable `Output`.
  2798. *
  2799. * @type {PropertyNode<vec4>}
  2800. */
  2801. const output = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'Output' );
  2802. /**
  2803. * TSL object that represents the shader variable `dashSize`.
  2804. *
  2805. * @type {PropertyNode<float>}
  2806. */
  2807. const dashSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'dashSize' );
  2808. /**
  2809. * TSL object that represents the shader variable `gapSize`.
  2810. *
  2811. * @type {PropertyNode<float>}
  2812. */
  2813. const gapSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'gapSize' );
  2814. /**
  2815. * TSL object that represents the shader variable `pointWidth`.
  2816. *
  2817. * @type {PropertyNode<float>}
  2818. */
  2819. const pointWidth = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'pointWidth' );
  2820. /**
  2821. * TSL object that represents the shader variable `IOR`.
  2822. *
  2823. * @type {PropertyNode<float>}
  2824. */
  2825. const ior = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IOR' );
  2826. /**
  2827. * TSL object that represents the shader variable `Transmission`.
  2828. *
  2829. * @type {PropertyNode<float>}
  2830. */
  2831. const transmission = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Transmission' );
  2832. /**
  2833. * TSL object that represents the shader variable `Thickness`.
  2834. *
  2835. * @type {PropertyNode<float>}
  2836. */
  2837. const thickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Thickness' );
  2838. /**
  2839. * TSL object that represents the shader variable `AttenuationDistance`.
  2840. *
  2841. * @type {PropertyNode<float>}
  2842. */
  2843. const attenuationDistance = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AttenuationDistance' );
  2844. /**
  2845. * TSL object that represents the shader variable `AttenuationColor`.
  2846. *
  2847. * @type {PropertyNode<color>}
  2848. */
  2849. const attenuationColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'AttenuationColor' );
  2850. /**
  2851. * TSL object that represents the shader variable `Dispersion`.
  2852. *
  2853. * @type {PropertyNode<float>}
  2854. */
  2855. const dispersion = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Dispersion' );
  2856. /** @module AssignNode **/
  2857. /**
  2858. * These node represents an assign operation. Meaning a node is assigned
  2859. * to another node.
  2860. *
  2861. * @augments TempNode
  2862. */
  2863. class AssignNode extends TempNode {
  2864. static get type() {
  2865. return 'AssignNode';
  2866. }
  2867. /**
  2868. * Constructs a new assign node.
  2869. *
  2870. * @param {Node} targetNode - The target node.
  2871. * @param {Node} sourceNode - The source type.
  2872. */
  2873. constructor( targetNode, sourceNode ) {
  2874. super();
  2875. /**
  2876. * The target node.
  2877. *
  2878. * @type {Node}
  2879. */
  2880. this.targetNode = targetNode;
  2881. /**
  2882. * The source node.
  2883. *
  2884. * @type {Node}
  2885. */
  2886. this.sourceNode = sourceNode;
  2887. }
  2888. /**
  2889. * Whether this node is used more than once in context of other nodes. This method
  2890. * is overwritten since it always returns `false` (assigns are unique).
  2891. *
  2892. * @return {Boolean} A flag that indicates if there is more than one dependency to other nodes. Always `false`.
  2893. */
  2894. hasDependencies() {
  2895. return false;
  2896. }
  2897. getNodeType( builder, output ) {
  2898. return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void';
  2899. }
  2900. /**
  2901. * Whether a split is required when assigning source to target. This can happen when the component length of
  2902. * target and source data type does not match.
  2903. *
  2904. * @param {NodeBuilder} builder - The current node builder.
  2905. * @return {Boolean} Whether a split is required when assigning source to target.
  2906. */
  2907. needsSplitAssign( builder ) {
  2908. const { targetNode } = this;
  2909. if ( builder.isAvailable( 'swizzleAssign' ) === false && targetNode.isSplitNode && targetNode.components.length > 1 ) {
  2910. const targetLength = builder.getTypeLength( targetNode.node.getNodeType( builder ) );
  2911. const assignDifferentVector = vectorComponents.join( '' ).slice( 0, targetLength ) !== targetNode.components;
  2912. return assignDifferentVector;
  2913. }
  2914. return false;
  2915. }
  2916. generate( builder, output ) {
  2917. const { targetNode, sourceNode } = this;
  2918. const needsSplitAssign = this.needsSplitAssign( builder );
  2919. const targetType = targetNode.getNodeType( builder );
  2920. const target = targetNode.context( { assign: true } ).build( builder );
  2921. const source = sourceNode.build( builder, targetType );
  2922. const sourceType = sourceNode.getNodeType( builder );
  2923. const nodeData = builder.getDataFromNode( this );
  2924. //
  2925. let snippet;
  2926. if ( nodeData.initialized === true ) {
  2927. if ( output !== 'void' ) {
  2928. snippet = target;
  2929. }
  2930. } else if ( needsSplitAssign ) {
  2931. const sourceVar = builder.getVarFromNode( this, null, targetType );
  2932. const sourceProperty = builder.getPropertyName( sourceVar );
  2933. builder.addLineFlowCode( `${ sourceProperty } = ${ source }`, this );
  2934. const targetRoot = targetNode.node.context( { assign: true } ).build( builder );
  2935. for ( let i = 0; i < targetNode.components.length; i ++ ) {
  2936. const component = targetNode.components[ i ];
  2937. builder.addLineFlowCode( `${ targetRoot }.${ component } = ${ sourceProperty }[ ${ i } ]`, this );
  2938. }
  2939. if ( output !== 'void' ) {
  2940. snippet = target;
  2941. }
  2942. } else {
  2943. snippet = `${ target } = ${ source }`;
  2944. if ( output === 'void' || sourceType === 'void' ) {
  2945. builder.addLineFlowCode( snippet, this );
  2946. if ( output !== 'void' ) {
  2947. snippet = target;
  2948. }
  2949. }
  2950. }
  2951. nodeData.initialized = true;
  2952. return builder.format( snippet, targetType, output );
  2953. }
  2954. }
  2955. /**
  2956. * TSL function for creating an assign node.
  2957. *
  2958. * @function
  2959. * @param {Node} targetNode - The target node.
  2960. * @param {Node} sourceNode - The source type.
  2961. * @returns {AssignNode}
  2962. */
  2963. const assign = /*@__PURE__*/ nodeProxy( AssignNode );
  2964. addMethodChaining( 'assign', assign );
  2965. /**
  2966. * This module represents the call of a {@link FunctionNode}. Developers are usually not confronted
  2967. * with this module since they use the predefined TSL syntax `wgslFn` and `glslFn` which encapsulate
  2968. * this logic.
  2969. *
  2970. * @augments TempNode
  2971. */
  2972. class FunctionCallNode extends TempNode {
  2973. static get type() {
  2974. return 'FunctionCallNode';
  2975. }
  2976. /**
  2977. * Constructs a new function call node.
  2978. *
  2979. * @param {FunctionNode?} functionNode - The function node.
  2980. * @param {Object<String, Node>} [parameters={}] - The parameters for the function call.
  2981. */
  2982. constructor( functionNode = null, parameters = {} ) {
  2983. super();
  2984. /**
  2985. * The function node.
  2986. *
  2987. * @type {FunctionNode}
  2988. * @default null
  2989. */
  2990. this.functionNode = functionNode;
  2991. /**
  2992. * The parameters of the function call.
  2993. *
  2994. * @type {Object<String, Node>}
  2995. * @default {}
  2996. */
  2997. this.parameters = parameters;
  2998. }
  2999. /**
  3000. * Sets the parameters of the function call node.
  3001. *
  3002. * @param {Object<String, Node>} parameters - The parameters to set.
  3003. * @return {FunctionCallNode} A reference to this node.
  3004. */
  3005. setParameters( parameters ) {
  3006. this.parameters = parameters;
  3007. return this;
  3008. }
  3009. /**
  3010. * Returns the parameters of the function call node.
  3011. *
  3012. * @return {Object<String, Node>} The parameters of this node.
  3013. */
  3014. getParameters() {
  3015. return this.parameters;
  3016. }
  3017. getNodeType( builder ) {
  3018. return this.functionNode.getNodeType( builder );
  3019. }
  3020. generate( builder ) {
  3021. const params = [];
  3022. const functionNode = this.functionNode;
  3023. const inputs = functionNode.getInputs( builder );
  3024. const parameters = this.parameters;
  3025. const generateInput = ( node, inputNode ) => {
  3026. const type = inputNode.type;
  3027. const pointer = type === 'pointer';
  3028. let output;
  3029. if ( pointer ) output = '&' + node.build( builder );
  3030. else output = node.build( builder, type );
  3031. return output;
  3032. };
  3033. if ( Array.isArray( parameters ) ) {
  3034. for ( let i = 0; i < parameters.length; i ++ ) {
  3035. params.push( generateInput( parameters[ i ], inputs[ i ] ) );
  3036. }
  3037. } else {
  3038. for ( const inputNode of inputs ) {
  3039. const node = parameters[ inputNode.name ];
  3040. if ( node !== undefined ) {
  3041. params.push( generateInput( node, inputNode ) );
  3042. } else {
  3043. throw new Error( `FunctionCallNode: Input '${inputNode.name}' not found in FunctionNode.` );
  3044. }
  3045. }
  3046. }
  3047. const functionName = functionNode.build( builder, 'property' );
  3048. return `${functionName}( ${params.join( ', ' )} )`;
  3049. }
  3050. }
  3051. const call = ( func, ...params ) => {
  3052. params = params.length > 1 || ( params[ 0 ] && params[ 0 ].isNode === true ) ? nodeArray( params ) : nodeObjects( params[ 0 ] );
  3053. return nodeObject( new FunctionCallNode( nodeObject( func ), params ) );
  3054. };
  3055. addMethodChaining( 'call', call );
  3056. /** @module OperatorNode **/
  3057. /**
  3058. * This node represents basic mathematical and logical operations like addition,
  3059. * subtraction or comparisons (e.g. `equal()`).
  3060. *
  3061. * @augments TempNode
  3062. */
  3063. class OperatorNode extends TempNode {
  3064. static get type() {
  3065. return 'OperatorNode';
  3066. }
  3067. /**
  3068. * Constructs a new operator node.
  3069. *
  3070. * @param {String} op - The operator.
  3071. * @param {Node} aNode - The first input.
  3072. * @param {Node} bNode - The second input.
  3073. * @param {...Node} params - Additional input parameters.
  3074. */
  3075. constructor( op, aNode, bNode, ...params ) {
  3076. super();
  3077. if ( params.length > 0 ) {
  3078. let finalOp = new OperatorNode( op, aNode, bNode );
  3079. for ( let i = 0; i < params.length - 1; i ++ ) {
  3080. finalOp = new OperatorNode( op, finalOp, params[ i ] );
  3081. }
  3082. aNode = finalOp;
  3083. bNode = params[ params.length - 1 ];
  3084. }
  3085. /**
  3086. * The operator.
  3087. *
  3088. * @type {String}
  3089. */
  3090. this.op = op;
  3091. /**
  3092. * The first input.
  3093. *
  3094. * @type {Node}
  3095. */
  3096. this.aNode = aNode;
  3097. /**
  3098. * The second input.
  3099. *
  3100. * @type {Node}
  3101. */
  3102. this.bNode = bNode;
  3103. /**
  3104. * This flag can be used for type testing.
  3105. *
  3106. * @type {Boolean}
  3107. * @readonly
  3108. * @default true
  3109. */
  3110. this.isOperatorNode = true;
  3111. }
  3112. /**
  3113. * This method is overwritten since the node type is inferred from the operator
  3114. * and the input node types.
  3115. *
  3116. * @param {NodeBuilder} builder - The current node builder.
  3117. * @param {String} output - The current output string.
  3118. * @return {String} The node type.
  3119. */
  3120. getNodeType( builder, output ) {
  3121. const op = this.op;
  3122. const aNode = this.aNode;
  3123. const bNode = this.bNode;
  3124. const typeA = aNode.getNodeType( builder );
  3125. const typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  3126. if ( typeA === 'void' || typeB === 'void' ) {
  3127. return 'void';
  3128. } else if ( op === '%' ) {
  3129. return typeA;
  3130. } else if ( op === '~' || op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) {
  3131. return builder.getIntegerType( typeA );
  3132. } else if ( op === '!' || op === '==' || op === '&&' || op === '||' || op === '^^' ) {
  3133. return 'bool';
  3134. } else if ( op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  3135. const typeLength = output ? builder.getTypeLength( output ) : Math.max( builder.getTypeLength( typeA ), builder.getTypeLength( typeB ) );
  3136. return typeLength > 1 ? `bvec${ typeLength }` : 'bool';
  3137. } else {
  3138. // Handle matrix operations
  3139. if ( builder.isMatrix( typeA ) ) {
  3140. if ( typeB === 'float' ) {
  3141. return typeA; // matrix * scalar = matrix
  3142. } else if ( builder.isVector( typeB ) ) {
  3143. return builder.getVectorFromMatrix( typeA ); // matrix * vector
  3144. } else if ( builder.isMatrix( typeB ) ) {
  3145. return typeA; // matrix * matrix
  3146. }
  3147. } else if ( builder.isMatrix( typeB ) ) {
  3148. if ( typeA === 'float' ) {
  3149. return typeB; // scalar * matrix = matrix
  3150. } else if ( builder.isVector( typeA ) ) {
  3151. return builder.getVectorFromMatrix( typeB ); // vector * matrix
  3152. }
  3153. }
  3154. // Handle non-matrix cases
  3155. if ( builder.getTypeLength( typeB ) > builder.getTypeLength( typeA ) ) {
  3156. // anytype x anytype: use the greater length vector
  3157. return typeB;
  3158. }
  3159. return typeA;
  3160. }
  3161. }
  3162. generate( builder, output ) {
  3163. const op = this.op;
  3164. const aNode = this.aNode;
  3165. const bNode = this.bNode;
  3166. const type = this.getNodeType( builder, output );
  3167. let typeA = null;
  3168. let typeB = null;
  3169. if ( type !== 'void' ) {
  3170. typeA = aNode.getNodeType( builder );
  3171. typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  3172. if ( op === '<' || op === '>' || op === '<=' || op === '>=' || op === '==' ) {
  3173. if ( builder.isVector( typeA ) ) {
  3174. typeB = typeA;
  3175. } else if ( typeA !== typeB ) {
  3176. typeA = typeB = 'float';
  3177. }
  3178. } else if ( op === '>>' || op === '<<' ) {
  3179. typeA = type;
  3180. typeB = builder.changeComponentType( typeB, 'uint' );
  3181. } else if ( builder.isMatrix( typeA ) ) {
  3182. if ( typeB === 'float' ) {
  3183. // Keep matrix type for typeA, but ensure typeB stays float
  3184. typeB = 'float';
  3185. } else if ( builder.isVector( typeB ) ) {
  3186. // matrix x vector
  3187. typeB = builder.getVectorFromMatrix( typeA );
  3188. } else if ( builder.isMatrix( typeB ) ) ; else {
  3189. typeA = typeB = type;
  3190. }
  3191. } else if ( builder.isMatrix( typeB ) ) {
  3192. if ( typeA === 'float' ) {
  3193. // Keep matrix type for typeB, but ensure typeA stays float
  3194. typeA = 'float';
  3195. } else if ( builder.isVector( typeA ) ) {
  3196. // vector x matrix
  3197. typeA = builder.getVectorFromMatrix( typeB );
  3198. } else {
  3199. typeA = typeB = type;
  3200. }
  3201. } else {
  3202. // anytype x anytype
  3203. typeA = typeB = type;
  3204. }
  3205. } else {
  3206. typeA = typeB = type;
  3207. }
  3208. const a = aNode.build( builder, typeA );
  3209. const b = typeof bNode !== 'undefined' ? bNode.build( builder, typeB ) : null;
  3210. const outputLength = builder.getTypeLength( output );
  3211. const fnOpSnippet = builder.getFunctionOperator( op );
  3212. if ( output !== 'void' ) {
  3213. if ( op === '<' && outputLength > 1 ) {
  3214. if ( builder.useComparisonMethod ) {
  3215. return builder.format( `${ builder.getMethod( 'lessThan', output ) }( ${ a }, ${ b } )`, type, output );
  3216. } else {
  3217. return builder.format( `( ${ a } < ${ b } )`, type, output );
  3218. }
  3219. } else if ( op === '<=' && outputLength > 1 ) {
  3220. if ( builder.useComparisonMethod ) {
  3221. return builder.format( `${ builder.getMethod( 'lessThanEqual', output ) }( ${ a }, ${ b } )`, type, output );
  3222. } else {
  3223. return builder.format( `( ${ a } <= ${ b } )`, type, output );
  3224. }
  3225. } else if ( op === '>' && outputLength > 1 ) {
  3226. if ( builder.useComparisonMethod ) {
  3227. return builder.format( `${ builder.getMethod( 'greaterThan', output ) }( ${ a }, ${ b } )`, type, output );
  3228. } else {
  3229. return builder.format( `( ${ a } > ${ b } )`, type, output );
  3230. }
  3231. } else if ( op === '>=' && outputLength > 1 ) {
  3232. if ( builder.useComparisonMethod ) {
  3233. return builder.format( `${ builder.getMethod( 'greaterThanEqual', output ) }( ${ a }, ${ b } )`, type, output );
  3234. } else {
  3235. return builder.format( `( ${ a } >= ${ b } )`, type, output );
  3236. }
  3237. } else if ( op === '!' || op === '~' ) {
  3238. return builder.format( `(${op}${a})`, typeA, output );
  3239. } else if ( fnOpSnippet ) {
  3240. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  3241. } else {
  3242. // Handle matrix operations
  3243. if ( builder.isMatrix( typeA ) && typeB === 'float' ) {
  3244. return builder.format( `( ${ b } ${ op } ${ a } )`, type, output );
  3245. } else if ( typeA === 'float' && builder.isMatrix( typeB ) ) {
  3246. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  3247. } else {
  3248. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  3249. }
  3250. }
  3251. } else if ( typeA !== 'void' ) {
  3252. if ( fnOpSnippet ) {
  3253. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  3254. } else {
  3255. if ( builder.isMatrix( typeA ) && typeB === 'float' ) {
  3256. return builder.format( `${ b } ${ op } ${ a }`, type, output );
  3257. } else {
  3258. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  3259. }
  3260. }
  3261. }
  3262. }
  3263. serialize( data ) {
  3264. super.serialize( data );
  3265. data.op = this.op;
  3266. }
  3267. deserialize( data ) {
  3268. super.deserialize( data );
  3269. this.op = data.op;
  3270. }
  3271. }
  3272. /**
  3273. * Returns the addition of two or more value.
  3274. *
  3275. * @function
  3276. * @param {Node} aNode - The first input.
  3277. * @param {Node} bNode - The second input.
  3278. * @param {...Node} params - Additional input parameters.
  3279. * @returns {OperatorNode}
  3280. */
  3281. const add = /*@__PURE__*/ nodeProxy( OperatorNode, '+' );
  3282. /**
  3283. * Returns the subtraction of two or more value.
  3284. *
  3285. * @function
  3286. * @param {Node} aNode - The first input.
  3287. * @param {Node} bNode - The second input.
  3288. * @param {...Node} params - Additional input parameters.
  3289. * @returns {OperatorNode}
  3290. */
  3291. const sub = /*@__PURE__*/ nodeProxy( OperatorNode, '-' );
  3292. /**
  3293. * Returns the multiplication of two or more value.
  3294. *
  3295. * @function
  3296. * @param {Node} aNode - The first input.
  3297. * @param {Node} bNode - The second input.
  3298. * @param {...Node} params - Additional input parameters.
  3299. * @returns {OperatorNode}
  3300. */
  3301. const mul = /*@__PURE__*/ nodeProxy( OperatorNode, '*' );
  3302. /**
  3303. * Returns the division of two or more value.
  3304. *
  3305. * @function
  3306. * @param {Node} aNode - The first input.
  3307. * @param {Node} bNode - The second input.
  3308. * @param {...Node} params - Additional input parameters.
  3309. * @returns {OperatorNode}
  3310. */
  3311. const div = /*@__PURE__*/ nodeProxy( OperatorNode, '/' );
  3312. /**
  3313. * Computes the remainder of dividing the first node by the second, for integer values.
  3314. *
  3315. * @function
  3316. * @param {Node} aNode - The first input.
  3317. * @param {Node} bNode - The second input.
  3318. * @returns {OperatorNode}
  3319. */
  3320. const modInt = /*@__PURE__*/ nodeProxy( OperatorNode, '%' );
  3321. /**
  3322. * Checks if two nodes are equal.
  3323. *
  3324. * @function
  3325. * @param {Node} aNode - The first input.
  3326. * @param {Node} bNode - The second input.
  3327. * @returns {OperatorNode}
  3328. */
  3329. const equal = /*@__PURE__*/ nodeProxy( OperatorNode, '==' );
  3330. /**
  3331. * Checks if two nodes are not equal.
  3332. *
  3333. * @function
  3334. * @param {Node} aNode - The first input.
  3335. * @param {Node} bNode - The second input.
  3336. * @returns {OperatorNode}
  3337. */
  3338. const notEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '!=' );
  3339. /**
  3340. * Checks if the first node is less than the second.
  3341. *
  3342. * @function
  3343. * @param {Node} aNode - The first input.
  3344. * @param {Node} bNode - The second input.
  3345. * @returns {OperatorNode}
  3346. */
  3347. const lessThan = /*@__PURE__*/ nodeProxy( OperatorNode, '<' );
  3348. /**
  3349. * Checks if the first node is greater than the second.
  3350. *
  3351. * @function
  3352. * @param {Node} aNode - The first input.
  3353. * @param {Node} bNode - The second input.
  3354. * @returns {OperatorNode}
  3355. */
  3356. const greaterThan = /*@__PURE__*/ nodeProxy( OperatorNode, '>' );
  3357. /**
  3358. * Checks if the first node is less than or equal to the second.
  3359. *
  3360. * @function
  3361. * @param {Node} aNode - The first input.
  3362. * @param {Node} bNode - The second input.
  3363. * @returns {OperatorNode}
  3364. */
  3365. const lessThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '<=' );
  3366. /**
  3367. * Checks if the first node is greater than or equal to the second.
  3368. *
  3369. * @function
  3370. * @param {Node} aNode - The first input.
  3371. * @param {Node} bNode - The second input.
  3372. * @returns {OperatorNode}
  3373. */
  3374. const greaterThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '>=' );
  3375. /**
  3376. * Performs logical AND on two nodes.
  3377. *
  3378. * @function
  3379. * @param {Node} aNode - The first input.
  3380. * @param {Node} bNode - The second input.
  3381. * @returns {OperatorNode}
  3382. */
  3383. const and = /*@__PURE__*/ nodeProxy( OperatorNode, '&&' );
  3384. /**
  3385. * Performs logical OR on two nodes.
  3386. *
  3387. * @function
  3388. * @param {Node} aNode - The first input.
  3389. * @param {Node} bNode - The second input.
  3390. * @returns {OperatorNode}
  3391. */
  3392. const or = /*@__PURE__*/ nodeProxy( OperatorNode, '||' );
  3393. /**
  3394. * Performs logical NOT on a node.
  3395. *
  3396. * @function
  3397. * @param {Node} aNode - The first input.
  3398. * @param {Node} bNode - The second input.
  3399. * @returns {OperatorNode}
  3400. */
  3401. const not = /*@__PURE__*/ nodeProxy( OperatorNode, '!' );
  3402. /**
  3403. * Performs logical XOR on two nodes.
  3404. *
  3405. * @function
  3406. * @param {Node} aNode - The first input.
  3407. * @param {Node} bNode - The second input.
  3408. * @returns {OperatorNode}
  3409. */
  3410. const xor = /*@__PURE__*/ nodeProxy( OperatorNode, '^^' );
  3411. /**
  3412. * Performs bitwise AND on two nodes.
  3413. *
  3414. * @function
  3415. * @param {Node} aNode - The first input.
  3416. * @param {Node} bNode - The second input.
  3417. * @returns {OperatorNode}
  3418. */
  3419. const bitAnd = /*@__PURE__*/ nodeProxy( OperatorNode, '&' );
  3420. /**
  3421. * Performs bitwise NOT on a node.
  3422. *
  3423. * @function
  3424. * @param {Node} aNode - The first input.
  3425. * @param {Node} bNode - The second input.
  3426. * @returns {OperatorNode}
  3427. */
  3428. const bitNot = /*@__PURE__*/ nodeProxy( OperatorNode, '~' );
  3429. /**
  3430. * Performs bitwise OR on two nodes.
  3431. *
  3432. * @function
  3433. * @param {Node} aNode - The first input.
  3434. * @param {Node} bNode - The second input.
  3435. * @returns {OperatorNode}
  3436. */
  3437. const bitOr = /*@__PURE__*/ nodeProxy( OperatorNode, '|' );
  3438. /**
  3439. * Performs bitwise XOR on two nodes.
  3440. *
  3441. * @function
  3442. * @param {Node} aNode - The first input.
  3443. * @param {Node} bNode - The second input.
  3444. * @returns {OperatorNode}
  3445. */
  3446. const bitXor = /*@__PURE__*/ nodeProxy( OperatorNode, '^' );
  3447. /**
  3448. * Shifts a node to the left.
  3449. *
  3450. * @function
  3451. * @param {Node} aNode - The node to shift.
  3452. * @param {Node} bNode - The value to shift.
  3453. * @returns {OperatorNode}
  3454. */
  3455. const shiftLeft = /*@__PURE__*/ nodeProxy( OperatorNode, '<<' );
  3456. /**
  3457. * Shifts a node to the right.
  3458. *
  3459. * @function
  3460. * @param {Node} aNode - The node to shift.
  3461. * @param {Node} bNode - The value to shift.
  3462. * @returns {OperatorNode}
  3463. */
  3464. const shiftRight = /*@__PURE__*/ nodeProxy( OperatorNode, '>>' );
  3465. addMethodChaining( 'add', add );
  3466. addMethodChaining( 'sub', sub );
  3467. addMethodChaining( 'mul', mul );
  3468. addMethodChaining( 'div', div );
  3469. addMethodChaining( 'modInt', modInt );
  3470. addMethodChaining( 'equal', equal );
  3471. addMethodChaining( 'notEqual', notEqual );
  3472. addMethodChaining( 'lessThan', lessThan );
  3473. addMethodChaining( 'greaterThan', greaterThan );
  3474. addMethodChaining( 'lessThanEqual', lessThanEqual );
  3475. addMethodChaining( 'greaterThanEqual', greaterThanEqual );
  3476. addMethodChaining( 'and', and );
  3477. addMethodChaining( 'or', or );
  3478. addMethodChaining( 'not', not );
  3479. addMethodChaining( 'xor', xor );
  3480. addMethodChaining( 'bitAnd', bitAnd );
  3481. addMethodChaining( 'bitNot', bitNot );
  3482. addMethodChaining( 'bitOr', bitOr );
  3483. addMethodChaining( 'bitXor', bitXor );
  3484. addMethodChaining( 'shiftLeft', shiftLeft );
  3485. addMethodChaining( 'shiftRight', shiftRight );
  3486. /**
  3487. * @function
  3488. * @deprecated since r168. Use {@link modInt} instead.
  3489. *
  3490. * @param {...any} params
  3491. * @returns {Function}
  3492. */
  3493. const remainder = ( ...params ) => { // @deprecated, r168
  3494. console.warn( 'TSL.OperatorNode: .remainder() has been renamed to .modInt().' );
  3495. return modInt( ...params );
  3496. };
  3497. addMethodChaining( 'remainder', remainder );
  3498. /** @module MathNode **/
  3499. /**
  3500. * This node represents a variety of mathematical methods available in shaders.
  3501. * They are divided into three categories:
  3502. *
  3503. * - Methods with one input like `sin`, `cos` or `normalize`.
  3504. * - Methods with two inputs like `dot`, `cross` or `pow`.
  3505. * - Methods with three inputs like `mix`, `clamp` or `smoothstep`.
  3506. *
  3507. * @augments TempNode
  3508. */
  3509. class MathNode extends TempNode {
  3510. static get type() {
  3511. return 'MathNode';
  3512. }
  3513. /**
  3514. * Constructs a new math node.
  3515. *
  3516. * @param {String} method - The method name.
  3517. * @param {Node} aNode - The first input.
  3518. * @param {Node?} [bNode=null] - The second input.
  3519. * @param {Node?} [cNode=null] - The third input.
  3520. */
  3521. constructor( method, aNode, bNode = null, cNode = null ) {
  3522. super();
  3523. /**
  3524. * The method name.
  3525. *
  3526. * @type {String}
  3527. */
  3528. this.method = method;
  3529. /**
  3530. * The first input.
  3531. *
  3532. * @type {Node}
  3533. */
  3534. this.aNode = aNode;
  3535. /**
  3536. * The second input.
  3537. *
  3538. * @type {Node?}
  3539. * @default null
  3540. */
  3541. this.bNode = bNode;
  3542. /**
  3543. * The third input.
  3544. *
  3545. * @type {Node?}
  3546. * @default null
  3547. */
  3548. this.cNode = cNode;
  3549. /**
  3550. * This flag can be used for type testing.
  3551. *
  3552. * @type {Boolean}
  3553. * @readonly
  3554. * @default true
  3555. */
  3556. this.isMathNode = true;
  3557. }
  3558. /**
  3559. * The input type is inferred from the node types of the input nodes.
  3560. *
  3561. * @param {NodeBuilder} builder - The current node builder.
  3562. * @return {String} The input type.
  3563. */
  3564. getInputType( builder ) {
  3565. const aType = this.aNode.getNodeType( builder );
  3566. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  3567. const cType = this.cNode ? this.cNode.getNodeType( builder ) : null;
  3568. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  3569. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  3570. const cLen = builder.isMatrix( cType ) ? 0 : builder.getTypeLength( cType );
  3571. if ( aLen > bLen && aLen > cLen ) {
  3572. return aType;
  3573. } else if ( bLen > cLen ) {
  3574. return bType;
  3575. } else if ( cLen > aLen ) {
  3576. return cType;
  3577. }
  3578. return aType;
  3579. }
  3580. /**
  3581. * The selected method as well as the input type determine the node type of this node.
  3582. *
  3583. * @param {NodeBuilder} builder - The current node builder.
  3584. * @return {String} The node type.
  3585. */
  3586. getNodeType( builder ) {
  3587. const method = this.method;
  3588. if ( method === MathNode.LENGTH || method === MathNode.DISTANCE || method === MathNode.DOT ) {
  3589. return 'float';
  3590. } else if ( method === MathNode.CROSS ) {
  3591. return 'vec3';
  3592. } else if ( method === MathNode.ALL ) {
  3593. return 'bool';
  3594. } else if ( method === MathNode.EQUALS ) {
  3595. return builder.changeComponentType( this.aNode.getNodeType( builder ), 'bool' );
  3596. } else if ( method === MathNode.MOD ) {
  3597. return this.aNode.getNodeType( builder );
  3598. } else {
  3599. return this.getInputType( builder );
  3600. }
  3601. }
  3602. generate( builder, output ) {
  3603. let method = this.method;
  3604. const type = this.getNodeType( builder );
  3605. const inputType = this.getInputType( builder );
  3606. const a = this.aNode;
  3607. const b = this.bNode;
  3608. const c = this.cNode;
  3609. const coordinateSystem = builder.renderer.coordinateSystem;
  3610. if ( method === MathNode.TRANSFORM_DIRECTION ) {
  3611. // dir can be either a direction vector or a normal vector
  3612. // upper-left 3x3 of matrix is assumed to be orthogonal
  3613. let tA = a;
  3614. let tB = b;
  3615. if ( builder.isMatrix( tA.getNodeType( builder ) ) ) {
  3616. tB = vec4( vec3( tB ), 0.0 );
  3617. } else {
  3618. tA = vec4( vec3( tA ), 0.0 );
  3619. }
  3620. const mulNode = mul( tA, tB ).xyz;
  3621. return normalize( mulNode ).build( builder, output );
  3622. } else if ( method === MathNode.NEGATE ) {
  3623. return builder.format( '( - ' + a.build( builder, inputType ) + ' )', type, output );
  3624. } else if ( method === MathNode.ONE_MINUS ) {
  3625. return sub( 1.0, a ).build( builder, output );
  3626. } else if ( method === MathNode.RECIPROCAL ) {
  3627. return div( 1.0, a ).build( builder, output );
  3628. } else if ( method === MathNode.DIFFERENCE ) {
  3629. return abs( sub( a, b ) ).build( builder, output );
  3630. } else {
  3631. const params = [];
  3632. if ( method === MathNode.CROSS || method === MathNode.MOD ) {
  3633. params.push(
  3634. a.build( builder, type ),
  3635. b.build( builder, type )
  3636. );
  3637. } else if ( coordinateSystem === WebGLCoordinateSystem && method === MathNode.STEP ) {
  3638. params.push(
  3639. a.build( builder, builder.getTypeLength( a.getNodeType( builder ) ) === 1 ? 'float' : inputType ),
  3640. b.build( builder, inputType )
  3641. );
  3642. } else if ( ( coordinateSystem === WebGLCoordinateSystem && ( method === MathNode.MIN || method === MathNode.MAX ) ) || method === MathNode.MOD ) {
  3643. params.push(
  3644. a.build( builder, inputType ),
  3645. b.build( builder, builder.getTypeLength( b.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  3646. );
  3647. } else if ( method === MathNode.REFRACT ) {
  3648. params.push(
  3649. a.build( builder, inputType ),
  3650. b.build( builder, inputType ),
  3651. c.build( builder, 'float' )
  3652. );
  3653. } else if ( method === MathNode.MIX ) {
  3654. params.push(
  3655. a.build( builder, inputType ),
  3656. b.build( builder, inputType ),
  3657. c.build( builder, builder.getTypeLength( c.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  3658. );
  3659. } else {
  3660. if ( coordinateSystem === WebGPUCoordinateSystem && method === MathNode.ATAN && b !== null ) {
  3661. method = 'atan2';
  3662. }
  3663. params.push( a.build( builder, inputType ) );
  3664. if ( b !== null ) params.push( b.build( builder, inputType ) );
  3665. if ( c !== null ) params.push( c.build( builder, inputType ) );
  3666. }
  3667. return builder.format( `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`, type, output );
  3668. }
  3669. }
  3670. serialize( data ) {
  3671. super.serialize( data );
  3672. data.method = this.method;
  3673. }
  3674. deserialize( data ) {
  3675. super.deserialize( data );
  3676. this.method = data.method;
  3677. }
  3678. }
  3679. // 1 input
  3680. MathNode.ALL = 'all';
  3681. MathNode.ANY = 'any';
  3682. MathNode.RADIANS = 'radians';
  3683. MathNode.DEGREES = 'degrees';
  3684. MathNode.EXP = 'exp';
  3685. MathNode.EXP2 = 'exp2';
  3686. MathNode.LOG = 'log';
  3687. MathNode.LOG2 = 'log2';
  3688. MathNode.SQRT = 'sqrt';
  3689. MathNode.INVERSE_SQRT = 'inversesqrt';
  3690. MathNode.FLOOR = 'floor';
  3691. MathNode.CEIL = 'ceil';
  3692. MathNode.NORMALIZE = 'normalize';
  3693. MathNode.FRACT = 'fract';
  3694. MathNode.SIN = 'sin';
  3695. MathNode.COS = 'cos';
  3696. MathNode.TAN = 'tan';
  3697. MathNode.ASIN = 'asin';
  3698. MathNode.ACOS = 'acos';
  3699. MathNode.ATAN = 'atan';
  3700. MathNode.ABS = 'abs';
  3701. MathNode.SIGN = 'sign';
  3702. MathNode.LENGTH = 'length';
  3703. MathNode.NEGATE = 'negate';
  3704. MathNode.ONE_MINUS = 'oneMinus';
  3705. MathNode.DFDX = 'dFdx';
  3706. MathNode.DFDY = 'dFdy';
  3707. MathNode.ROUND = 'round';
  3708. MathNode.RECIPROCAL = 'reciprocal';
  3709. MathNode.TRUNC = 'trunc';
  3710. MathNode.FWIDTH = 'fwidth';
  3711. MathNode.TRANSPOSE = 'transpose';
  3712. // 2 inputs
  3713. MathNode.BITCAST = 'bitcast';
  3714. MathNode.EQUALS = 'equals';
  3715. MathNode.MIN = 'min';
  3716. MathNode.MAX = 'max';
  3717. MathNode.MOD = 'mod';
  3718. MathNode.STEP = 'step';
  3719. MathNode.REFLECT = 'reflect';
  3720. MathNode.DISTANCE = 'distance';
  3721. MathNode.DIFFERENCE = 'difference';
  3722. MathNode.DOT = 'dot';
  3723. MathNode.CROSS = 'cross';
  3724. MathNode.POW = 'pow';
  3725. MathNode.TRANSFORM_DIRECTION = 'transformDirection';
  3726. // 3 inputs
  3727. MathNode.MIX = 'mix';
  3728. MathNode.CLAMP = 'clamp';
  3729. MathNode.REFRACT = 'refract';
  3730. MathNode.SMOOTHSTEP = 'smoothstep';
  3731. MathNode.FACEFORWARD = 'faceforward';
  3732. // 1 inputs
  3733. /**
  3734. * A small value used to handle floating-point precision errors.
  3735. *
  3736. * @type {Node<float>}
  3737. */
  3738. const EPSILON = /*@__PURE__*/ float( 1e-6 );
  3739. /**
  3740. * Represents infinity.
  3741. *
  3742. * @type {Node<float>}
  3743. */
  3744. const INFINITY = /*@__PURE__*/ float( 1e6 );
  3745. /**
  3746. * Represents PI.
  3747. *
  3748. * @type {Node<float>}
  3749. */
  3750. const PI = /*@__PURE__*/ float( Math.PI );
  3751. /**
  3752. * Represents PI * 2.
  3753. *
  3754. * @type {Node<float>}
  3755. */
  3756. const PI2 = /*@__PURE__*/ float( Math.PI * 2 );
  3757. /**
  3758. * Returns `true` if all components of `x` are `true`.
  3759. *
  3760. * @function
  3761. * @param {Node | Number} x - The parameter.
  3762. * @returns {Node<bool>}
  3763. */
  3764. const all = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ALL );
  3765. /**
  3766. * Returns `true` if any components of `x` are `true`.
  3767. *
  3768. * @function
  3769. * @param {Node | Number} x - The parameter.
  3770. * @returns {Node<bool>}
  3771. */
  3772. const any = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ANY );
  3773. /**
  3774. * Converts a quantity in degrees to radians.
  3775. *
  3776. * @function
  3777. * @param {Node | Number} x - The input in degrees.
  3778. * @returns {Node}
  3779. */
  3780. const radians = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RADIANS );
  3781. /**
  3782. * Convert a quantity in radians to degrees.
  3783. *
  3784. * @function
  3785. * @param {Node | Number} x - The input in radians.
  3786. * @returns {Node}
  3787. */
  3788. const degrees = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DEGREES );
  3789. /**
  3790. * Returns the natural exponentiation of the parameter.
  3791. *
  3792. * @function
  3793. * @param {Node | Number} x - The parameter.
  3794. * @returns {Node}
  3795. */
  3796. const exp = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP );
  3797. /**
  3798. * Returns 2 raised to the power of the parameter.
  3799. *
  3800. * @function
  3801. * @param {Node | Number} x - The parameter.
  3802. * @returns {Node}
  3803. */
  3804. const exp2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP2 );
  3805. /**
  3806. * Returns the natural logarithm of the parameter.
  3807. *
  3808. * @function
  3809. * @param {Node | Number} x - The parameter.
  3810. * @returns {Node}
  3811. */
  3812. const log = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG );
  3813. /**
  3814. * Returns the base 2 logarithm of the parameter.
  3815. *
  3816. * @function
  3817. * @param {Node | Number} x - The parameter.
  3818. * @returns {Node}
  3819. */
  3820. const log2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG2 );
  3821. /**
  3822. * Returns the square root of the parameter.
  3823. *
  3824. * @function
  3825. * @param {Node | Number} x - The parameter.
  3826. * @returns {Node}
  3827. */
  3828. const sqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SQRT );
  3829. /**
  3830. * Returns the inverse of the square root of the parameter.
  3831. *
  3832. * @function
  3833. * @param {Node | Number} x - The parameter.
  3834. * @returns {Node}
  3835. */
  3836. const inverseSqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.INVERSE_SQRT );
  3837. /**
  3838. * Finds the nearest integer less than or equal to the parameter.
  3839. *
  3840. * @function
  3841. * @param {Node | Number} x - The parameter.
  3842. * @returns {Node}
  3843. */
  3844. const floor = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FLOOR );
  3845. /**
  3846. * Finds the nearest integer that is greater than or equal to the parameter.
  3847. *
  3848. * @function
  3849. * @param {Node | Number} x - The parameter.
  3850. * @returns {Node}
  3851. */
  3852. const ceil = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CEIL );
  3853. /**
  3854. * Calculates the unit vector in the same direction as the original vector.
  3855. *
  3856. * @function
  3857. * @param {Node} x - The input vector.
  3858. * @returns {Node}
  3859. */
  3860. const normalize = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NORMALIZE );
  3861. /**
  3862. * Computes the fractional part of the parameter.
  3863. *
  3864. * @function
  3865. * @param {Node | Number} x - The parameter.
  3866. * @returns {Node}
  3867. */
  3868. const fract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FRACT );
  3869. /**
  3870. * Returns the sine of the parameter.
  3871. *
  3872. * @function
  3873. * @param {Node | Number} x - The parameter.
  3874. * @returns {Node}
  3875. */
  3876. const sin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIN );
  3877. /**
  3878. * Returns the cosine of the parameter.
  3879. *
  3880. * @function
  3881. * @param {Node | Number} x - The parameter.
  3882. * @returns {Node}
  3883. */
  3884. const cos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.COS );
  3885. /**
  3886. * Returns the tangent of the parameter.
  3887. *
  3888. * @function
  3889. * @param {Node | Number} x - The parameter.
  3890. * @returns {Node}
  3891. */
  3892. const tan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TAN );
  3893. /**
  3894. * Returns the arcsine of the parameter.
  3895. *
  3896. * @function
  3897. * @param {Node | Number} x - The parameter.
  3898. * @returns {Node}
  3899. */
  3900. const asin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ASIN );
  3901. /**
  3902. * Returns the arccosine of the parameter.
  3903. *
  3904. * @function
  3905. * @param {Node | Number} x - The parameter.
  3906. * @returns {Node}
  3907. */
  3908. const acos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ACOS );
  3909. /**
  3910. * Returns the arc-tangent of the parameter.
  3911. * If two parameters are provided, the result is `atan2(y/x)`.
  3912. *
  3913. * @function
  3914. * @param {Node | Number} y - The y parameter.
  3915. * @param {(Node | Number)?} x - The x parameter.
  3916. * @returns {Node}
  3917. */
  3918. const atan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ATAN );
  3919. /**
  3920. * Returns the absolute value of the parameter.
  3921. *
  3922. * @function
  3923. * @param {Node | Number} x - The parameter.
  3924. * @returns {Node}
  3925. */
  3926. const abs = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ABS );
  3927. /**
  3928. * Extracts the sign of the parameter.
  3929. *
  3930. * @function
  3931. * @param {Node | Number} x - The parameter.
  3932. * @returns {Node}
  3933. */
  3934. const sign = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIGN );
  3935. /**
  3936. * Calculates the length of a vector.
  3937. *
  3938. * @function
  3939. * @param {Node} x - The parameter.
  3940. * @returns {Node<float>}
  3941. */
  3942. const length = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LENGTH );
  3943. /**
  3944. * Negates the value of the parameter (-x).
  3945. *
  3946. * @function
  3947. * @param {Node | Number} x - The parameter.
  3948. * @returns {Node}
  3949. */
  3950. const negate = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NEGATE );
  3951. /**
  3952. * Return `1` minus the parameter.
  3953. *
  3954. * @function
  3955. * @param {Node | Number} x - The parameter.
  3956. * @returns {Node}
  3957. */
  3958. const oneMinus = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ONE_MINUS );
  3959. /**
  3960. * Returns the partial derivative of the parameter with respect to x.
  3961. *
  3962. * @function
  3963. * @param {Node | Number} x - The parameter.
  3964. * @returns {Node}
  3965. */
  3966. const dFdx = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDX );
  3967. /**
  3968. * Returns the partial derivative of the parameter with respect to y.
  3969. *
  3970. * @function
  3971. * @param {Node | Number} x - The parameter.
  3972. * @returns {Node}
  3973. */
  3974. const dFdy = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDY );
  3975. /**
  3976. * Rounds the parameter to the nearest integer.
  3977. *
  3978. * @function
  3979. * @param {Node | Number} x - The parameter.
  3980. * @returns {Node}
  3981. */
  3982. const round = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ROUND );
  3983. /**
  3984. * Returns the reciprocal of the parameter `(1/x)`.
  3985. *
  3986. * @function
  3987. * @param {Node | Number} x - The parameter.
  3988. * @returns {Node}
  3989. */
  3990. const reciprocal = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RECIPROCAL );
  3991. /**
  3992. * Truncates the parameter, removing the fractional part.
  3993. *
  3994. * @function
  3995. * @param {Node | Number} x - The parameter.
  3996. * @returns {Node}
  3997. */
  3998. const trunc = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRUNC );
  3999. /**
  4000. * Returns the sum of the absolute derivatives in x and y.
  4001. *
  4002. * @function
  4003. * @param {Node | Number} x - The parameter.
  4004. * @returns {Node}
  4005. */
  4006. const fwidth = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FWIDTH );
  4007. /**
  4008. * Returns the transpose of a matrix.
  4009. *
  4010. * @function
  4011. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  4012. * @returns {Node}
  4013. */
  4014. const transpose = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSPOSE );
  4015. // 2 inputs
  4016. /**
  4017. * Reinterpret the bit representation of a value in one type as a value in another type.
  4018. *
  4019. * @function
  4020. * @param {Node | Number} x - The parameter.
  4021. * @param {String} y - The new type.
  4022. * @returns {Node}
  4023. */
  4024. const bitcast = /*@__PURE__*/ nodeProxy( MathNode, MathNode.BITCAST );
  4025. /**
  4026. * Returns `true` if `x` equals `y`.
  4027. *
  4028. * @function
  4029. * @param {Node | Number} x - The first parameter.
  4030. * @param {Node | Number} y - The second parameter.
  4031. * @returns {Node<bool>}
  4032. */
  4033. const equals = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EQUALS );
  4034. /**
  4035. * Returns the lesser of two values.
  4036. *
  4037. * @function
  4038. * @param {Node | Number} x - The y parameter.
  4039. * @param {Node | Number} y - The x parameter.
  4040. * @returns {Node}
  4041. */
  4042. const min$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIN );
  4043. /**
  4044. * Returns the greater of two values.
  4045. *
  4046. * @function
  4047. * @param {Node | Number} x - The y parameter.
  4048. * @param {Node | Number} y - The x parameter.
  4049. * @returns {Node}
  4050. */
  4051. const max$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MAX );
  4052. /**
  4053. * Computes the remainder of dividing the first node by the second one.
  4054. *
  4055. * @function
  4056. * @param {Node | Number} x - The y parameter.
  4057. * @param {Node | Number} y - The x parameter.
  4058. * @returns {Node}
  4059. */
  4060. const mod = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MOD );
  4061. /**
  4062. * Generate a step function by comparing two values.
  4063. *
  4064. * @function
  4065. * @param {Node | Number} x - The y parameter.
  4066. * @param {Node | Number} y - The x parameter.
  4067. * @returns {Node}
  4068. */
  4069. const step = /*@__PURE__*/ nodeProxy( MathNode, MathNode.STEP );
  4070. /**
  4071. * Calculates the reflection direction for an incident vector.
  4072. *
  4073. * @function
  4074. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  4075. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  4076. * @returns {Node<vec2|vec3|vec4>}
  4077. */
  4078. const reflect = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFLECT );
  4079. /**
  4080. * Calculates the distance between two points.
  4081. *
  4082. * @function
  4083. * @param {Node<vec2|vec3|vec4>} x - The first point.
  4084. * @param {Node<vec2|vec3|vec4>} y - The second point.
  4085. * @returns {Node<float>}
  4086. */
  4087. const distance = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DISTANCE );
  4088. /**
  4089. * Calculates the absolute difference between two values.
  4090. *
  4091. * @function
  4092. * @param {Node | Number} x - The first parameter.
  4093. * @param {Node | Number} y - The second parameter.
  4094. * @returns {Node}
  4095. */
  4096. const difference = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DIFFERENCE );
  4097. /**
  4098. * Calculates the dot product of two vectors.
  4099. *
  4100. * @function
  4101. * @param {Node<vec2|vec3|vec4>} x - The first vector.
  4102. * @param {Node<vec2|vec3|vec4>} y - The second vector.
  4103. * @returns {Node<float>}
  4104. */
  4105. const dot = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DOT );
  4106. /**
  4107. * Calculates the cross product of two vectors.
  4108. *
  4109. * @function
  4110. * @param {Node<vec2|vec3|vec4>} x - The first vector.
  4111. * @param {Node<vec2|vec3|vec4>} y - The second vector.
  4112. * @returns {Node<vec2|vec3|vec4>}
  4113. */
  4114. const cross = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CROSS );
  4115. /**
  4116. * Return the value of the first parameter raised to the power of the second one.
  4117. *
  4118. * @function
  4119. * @param {Node | Number} x - The first parameter.
  4120. * @param {Node | Number} y - The second parameter.
  4121. * @returns {Node}
  4122. */
  4123. const pow = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW );
  4124. /**
  4125. * Returns the square of the parameter.
  4126. *
  4127. * @function
  4128. * @param {Node | Number} x - The first parameter.
  4129. * @returns {Node}
  4130. */
  4131. const pow2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 2 );
  4132. /**
  4133. * Returns the cube of the parameter.
  4134. *
  4135. * @function
  4136. * @param {Node | Number} x - The first parameter.
  4137. * @returns {Node}
  4138. */
  4139. const pow3 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 3 );
  4140. /**
  4141. * Returns the fourth power of the parameter.
  4142. *
  4143. * @function
  4144. * @param {Node | Number} x - The first parameter.
  4145. * @returns {Node}
  4146. */
  4147. const pow4 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 4 );
  4148. /**
  4149. * Transforms the direction of a vector by a matrix and then normalizes the result.
  4150. *
  4151. * @function
  4152. * @param {Node<vec2|vec3|vec4>} direction - The direction vector.
  4153. * @param {Node<mat2|mat3|mat4>} matrix - The transformation matrix.
  4154. * @returns {Node}
  4155. */
  4156. const transformDirection = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSFORM_DIRECTION );
  4157. /**
  4158. * Returns the cube root of a number.
  4159. *
  4160. * @function
  4161. * @param {Node | Number} a - The first parameter.
  4162. * @returns {Node}
  4163. */
  4164. const cbrt = ( a ) => mul( sign( a ), pow( abs( a ), 1.0 / 3.0 ) );
  4165. /**
  4166. * Calculate the squared length of a vector.
  4167. *
  4168. * @function
  4169. * @param {Node<vec2|vec3|vec4>} a - The vector.
  4170. * @returns {Node<float>}
  4171. */
  4172. const lengthSq = ( a ) => dot( a, a );
  4173. /**
  4174. * Linearly interpolates between two values.
  4175. *
  4176. * @function
  4177. * @param {Node | Number} a - The first parameter.
  4178. * @param {Node | Number} b - The second parameter.
  4179. * @param {Node | Number} t - The interpolation value.
  4180. * @returns {Node}
  4181. */
  4182. const mix = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIX );
  4183. /**
  4184. * Constrains a value to lie between two further values.
  4185. *
  4186. * @function
  4187. * @param {Node | Number} value - The value to constrain.
  4188. * @param {Node | Number} [low=0] - The lower bound.
  4189. * @param {Node | Number} [high=1] - The upper bound.
  4190. * @returns {Node}
  4191. */
  4192. const clamp = ( value, low = 0, high = 1 ) => nodeObject( new MathNode( MathNode.CLAMP, nodeObject( value ), nodeObject( low ), nodeObject( high ) ) );
  4193. /**
  4194. * Constrains a value between `0` and `1`.
  4195. *
  4196. * @function
  4197. * @param {Node | Number} value - The value to constrain.
  4198. * @returns {Node}
  4199. */
  4200. const saturate = ( value ) => clamp( value );
  4201. /**
  4202. * Calculates the refraction direction for an incident vector.
  4203. *
  4204. * @function
  4205. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  4206. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  4207. * @param {Node<float>} eta - The the ratio of indices of refraction.
  4208. * @returns {Node<vec2|vec3|vec4>}
  4209. */
  4210. const refract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFRACT );
  4211. /**
  4212. * Performs a Hermite interpolation between two values.
  4213. *
  4214. * @function
  4215. * @param {Node | Number} low - The value of the lower edge of the Hermite function.
  4216. * @param {Node | Number} high - The value of the upper edge of the Hermite function.
  4217. * @param {Node | Number} x - The source value for interpolation.
  4218. * @returns {Node}
  4219. */
  4220. const smoothstep = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SMOOTHSTEP );
  4221. /**
  4222. * Returns a vector pointing in the same direction as another.
  4223. *
  4224. * @function
  4225. * @param {Node<vec2|vec3|vec4>} N - The vector to orient.
  4226. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  4227. * @param {Node<vec2|vec3|vec4>} Nref - The reference vector.
  4228. * @returns {Node<vec2|vec3|vec4>}
  4229. */
  4230. const faceForward = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FACEFORWARD );
  4231. /**
  4232. * Returns a random value for the given uv.
  4233. *
  4234. * @function
  4235. * @param {Node<vec2>} uv - The uv node.
  4236. * @returns {Node<float>}
  4237. */
  4238. const rand = /*@__PURE__*/ Fn( ( [ uv ] ) => {
  4239. const a = 12.9898, b = 78.233, c = 43758.5453;
  4240. const dt = dot( uv.xy, vec2( a, b ) ), sn = mod( dt, PI );
  4241. return fract( sin( sn ).mul( c ) );
  4242. } );
  4243. /**
  4244. * Alias for `mix()` with a different parameter order.
  4245. *
  4246. * @function
  4247. * @param {Node | Number} t - The interpolation value.
  4248. * @param {Node | Number} e1 - The first parameter.
  4249. * @param {Node | Number} e2 - The second parameter.
  4250. * @returns {Node}
  4251. */
  4252. const mixElement = ( t, e1, e2 ) => mix( e1, e2, t );
  4253. /**
  4254. * Alias for `smoothstep()` with a different parameter order.
  4255. *
  4256. * @function
  4257. * @param {Node | Number} x - The source value for interpolation.
  4258. * @param {Node | Number} low - The value of the lower edge of the Hermite function.
  4259. * @param {Node | Number} high - The value of the upper edge of the Hermite function.
  4260. * @returns {Node}
  4261. */
  4262. const smoothstepElement = ( x, low, high ) => smoothstep( low, high, x );
  4263. /**
  4264. * Returns the arc-tangent of the quotient of its parameters.
  4265. *
  4266. * @function
  4267. * @deprecated since r172. Use {@link atan} instead.
  4268. *
  4269. * @param {Node | Number} y - The y parameter.
  4270. * @param {Node | Number} x - The x parameter.
  4271. * @returns {Node}
  4272. */
  4273. const atan2 = ( y, x ) => { // @deprecated, r172
  4274. console.warn( 'THREE.TSL: "atan2" is overloaded. Use "atan" instead.' );
  4275. return atan( y, x );
  4276. };
  4277. // GLSL alias function
  4278. const faceforward = faceForward;
  4279. const inversesqrt = inverseSqrt;
  4280. // Method chaining
  4281. addMethodChaining( 'all', all );
  4282. addMethodChaining( 'any', any );
  4283. addMethodChaining( 'equals', equals );
  4284. addMethodChaining( 'radians', radians );
  4285. addMethodChaining( 'degrees', degrees );
  4286. addMethodChaining( 'exp', exp );
  4287. addMethodChaining( 'exp2', exp2 );
  4288. addMethodChaining( 'log', log );
  4289. addMethodChaining( 'log2', log2 );
  4290. addMethodChaining( 'sqrt', sqrt );
  4291. addMethodChaining( 'inverseSqrt', inverseSqrt );
  4292. addMethodChaining( 'floor', floor );
  4293. addMethodChaining( 'ceil', ceil );
  4294. addMethodChaining( 'normalize', normalize );
  4295. addMethodChaining( 'fract', fract );
  4296. addMethodChaining( 'sin', sin );
  4297. addMethodChaining( 'cos', cos );
  4298. addMethodChaining( 'tan', tan );
  4299. addMethodChaining( 'asin', asin );
  4300. addMethodChaining( 'acos', acos );
  4301. addMethodChaining( 'atan', atan );
  4302. addMethodChaining( 'abs', abs );
  4303. addMethodChaining( 'sign', sign );
  4304. addMethodChaining( 'length', length );
  4305. addMethodChaining( 'lengthSq', lengthSq );
  4306. addMethodChaining( 'negate', negate );
  4307. addMethodChaining( 'oneMinus', oneMinus );
  4308. addMethodChaining( 'dFdx', dFdx );
  4309. addMethodChaining( 'dFdy', dFdy );
  4310. addMethodChaining( 'round', round );
  4311. addMethodChaining( 'reciprocal', reciprocal );
  4312. addMethodChaining( 'trunc', trunc );
  4313. addMethodChaining( 'fwidth', fwidth );
  4314. addMethodChaining( 'atan2', atan2 );
  4315. addMethodChaining( 'min', min$1 );
  4316. addMethodChaining( 'max', max$1 );
  4317. addMethodChaining( 'mod', mod );
  4318. addMethodChaining( 'step', step );
  4319. addMethodChaining( 'reflect', reflect );
  4320. addMethodChaining( 'distance', distance );
  4321. addMethodChaining( 'dot', dot );
  4322. addMethodChaining( 'cross', cross );
  4323. addMethodChaining( 'pow', pow );
  4324. addMethodChaining( 'pow2', pow2 );
  4325. addMethodChaining( 'pow3', pow3 );
  4326. addMethodChaining( 'pow4', pow4 );
  4327. addMethodChaining( 'transformDirection', transformDirection );
  4328. addMethodChaining( 'mix', mixElement );
  4329. addMethodChaining( 'clamp', clamp );
  4330. addMethodChaining( 'refract', refract );
  4331. addMethodChaining( 'smoothstep', smoothstepElement );
  4332. addMethodChaining( 'faceForward', faceForward );
  4333. addMethodChaining( 'difference', difference );
  4334. addMethodChaining( 'saturate', saturate );
  4335. addMethodChaining( 'cbrt', cbrt );
  4336. addMethodChaining( 'transpose', transpose );
  4337. addMethodChaining( 'rand', rand );
  4338. /** @module ConditionalNode **/
  4339. /**
  4340. * Represents a logical `if/else` statement. Can be used as an alternative
  4341. * to the `If()`/`Else()` syntax.
  4342. *
  4343. * The corresponding TSL `select()` looks like so:
  4344. * ```js
  4345. * velocity = position.greaterThanEqual( limit ).select( velocity.negate(), velocity );
  4346. * ```
  4347. * The `select()` method is called in a chaining fashion on a condition. The parameter nodes of `select()`
  4348. * determine the outcome of the entire statement.
  4349. *
  4350. * @augments Node
  4351. */
  4352. class ConditionalNode extends Node {
  4353. static get type() {
  4354. return 'ConditionalNode';
  4355. }
  4356. /**
  4357. * Constructs a new conditional node.
  4358. *
  4359. * @param {Node} condNode - The node that defines the condition.
  4360. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  4361. * @param {Node?} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  4362. */
  4363. constructor( condNode, ifNode, elseNode = null ) {
  4364. super();
  4365. /**
  4366. * The node that defines the condition.
  4367. *
  4368. * @type {Node}
  4369. */
  4370. this.condNode = condNode;
  4371. /**
  4372. * The node that is evaluate when the condition ends up `true`.
  4373. *
  4374. * @type {Node}
  4375. */
  4376. this.ifNode = ifNode;
  4377. /**
  4378. * The node that is evaluate when the condition ends up `false`.
  4379. *
  4380. * @type {Node?}
  4381. * @default null
  4382. */
  4383. this.elseNode = elseNode;
  4384. }
  4385. /**
  4386. * This method is overwritten since the node type is inferred from the if/else
  4387. * nodes.
  4388. *
  4389. * @param {NodeBuilder} builder - The current node builder.
  4390. * @return {String} The node type.
  4391. */
  4392. getNodeType( builder ) {
  4393. const { ifNode, elseNode } = builder.getNodeProperties( this );
  4394. if ( ifNode === undefined ) {
  4395. // fallback setup
  4396. this.setup( builder );
  4397. return this.getNodeType( builder );
  4398. }
  4399. const ifType = ifNode.getNodeType( builder );
  4400. if ( elseNode !== null ) {
  4401. const elseType = elseNode.getNodeType( builder );
  4402. if ( builder.getTypeLength( elseType ) > builder.getTypeLength( ifType ) ) {
  4403. return elseType;
  4404. }
  4405. }
  4406. return ifType;
  4407. }
  4408. setup( builder ) {
  4409. const condNode = this.condNode.cache();
  4410. const ifNode = this.ifNode.cache();
  4411. const elseNode = this.elseNode ? this.elseNode.cache() : null;
  4412. //
  4413. const currentNodeBlock = builder.context.nodeBlock;
  4414. builder.getDataFromNode( ifNode ).parentNodeBlock = currentNodeBlock;
  4415. if ( elseNode !== null ) builder.getDataFromNode( elseNode ).parentNodeBlock = currentNodeBlock;
  4416. //
  4417. const properties = builder.getNodeProperties( this );
  4418. properties.condNode = condNode;
  4419. properties.ifNode = ifNode.context( { nodeBlock: ifNode } );
  4420. properties.elseNode = elseNode ? elseNode.context( { nodeBlock: elseNode } ) : null;
  4421. }
  4422. generate( builder, output ) {
  4423. const type = this.getNodeType( builder );
  4424. const nodeData = builder.getDataFromNode( this );
  4425. if ( nodeData.nodeProperty !== undefined ) {
  4426. return nodeData.nodeProperty;
  4427. }
  4428. const { condNode, ifNode, elseNode } = builder.getNodeProperties( this );
  4429. const needsOutput = output !== 'void';
  4430. const nodeProperty = needsOutput ? property( type ).build( builder ) : '';
  4431. nodeData.nodeProperty = nodeProperty;
  4432. const nodeSnippet = condNode.build( builder, 'bool' );
  4433. builder.addFlowCode( `\n${ builder.tab }if ( ${ nodeSnippet } ) {\n\n` ).addFlowTab();
  4434. let ifSnippet = ifNode.build( builder, type );
  4435. if ( ifSnippet ) {
  4436. if ( needsOutput ) {
  4437. ifSnippet = nodeProperty + ' = ' + ifSnippet + ';';
  4438. } else {
  4439. ifSnippet = 'return ' + ifSnippet + ';';
  4440. }
  4441. }
  4442. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + ifSnippet + '\n\n' + builder.tab + '}' );
  4443. if ( elseNode !== null ) {
  4444. builder.addFlowCode( ' else {\n\n' ).addFlowTab();
  4445. let elseSnippet = elseNode.build( builder, type );
  4446. if ( elseSnippet ) {
  4447. if ( needsOutput ) {
  4448. elseSnippet = nodeProperty + ' = ' + elseSnippet + ';';
  4449. } else {
  4450. elseSnippet = 'return ' + elseSnippet + ';';
  4451. }
  4452. }
  4453. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + elseSnippet + '\n\n' + builder.tab + '}\n\n' );
  4454. } else {
  4455. builder.addFlowCode( '\n\n' );
  4456. }
  4457. return builder.format( nodeProperty, type, output );
  4458. }
  4459. }
  4460. /**
  4461. * TSL function for creating a conditional node.
  4462. *
  4463. * @function
  4464. * @param {Node} condNode - The node that defines the condition.
  4465. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  4466. * @param {Node?} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  4467. * @returns {ConditionalNode}
  4468. */
  4469. const select = /*@__PURE__*/ nodeProxy( ConditionalNode );
  4470. addMethodChaining( 'select', select );
  4471. // Deprecated
  4472. /**
  4473. * @function
  4474. * @deprecated since r168. Use {@link select} instead.
  4475. *
  4476. * @param {...any} params
  4477. * @returns {ConditionalNode}
  4478. */
  4479. const cond = ( ...params ) => { // @deprecated, r168
  4480. console.warn( 'TSL.ConditionalNode: cond() has been renamed to select().' );
  4481. return select( ...params );
  4482. };
  4483. addMethodChaining( 'cond', cond );
  4484. /** @module ContextNode **/
  4485. /**
  4486. * This node can be used as a context management component for another node.
  4487. * {@link NodeBuilder} performs its node building process in a specific context and
  4488. * this node allows the modify the context. A typical use case is to overwrite `getUV()` e.g.:
  4489. *
  4490. * ```js
  4491. *node.context( { getUV: () => customCoord } );
  4492. *```
  4493. * @augments Node
  4494. */
  4495. class ContextNode extends Node {
  4496. static get type() {
  4497. return 'ContextNode';
  4498. }
  4499. /**
  4500. * Constructs a new context node.
  4501. *
  4502. * @param {Node} node - The node whose context should be modified.
  4503. * @param {Object} [value={}] - The modified context data.
  4504. */
  4505. constructor( node, value = {} ) {
  4506. super();
  4507. /**
  4508. * This flag can be used for type testing.
  4509. *
  4510. * @type {Boolean}
  4511. * @readonly
  4512. * @default true
  4513. */
  4514. this.isContextNode = true;
  4515. /**
  4516. * The node whose context should be modified.
  4517. *
  4518. * @type {Node}
  4519. */
  4520. this.node = node;
  4521. /**
  4522. * The modified context data.
  4523. *
  4524. * @type {Object}
  4525. * @default {}
  4526. */
  4527. this.value = value;
  4528. }
  4529. /**
  4530. * This method is overwritten to ensure it returns the reference to {@link module:ContextNode~ContextNode#node}.
  4531. *
  4532. * @return {Node} A reference to {@link module:ContextNode~ContextNode#node}.
  4533. */
  4534. getScope() {
  4535. return this.node.getScope();
  4536. }
  4537. /**
  4538. * This method is overwritten to ensure it returns the type of {@link module:ContextNode~ContextNode#node}.
  4539. *
  4540. * @param {NodeBuilder} builder - The current node builder.
  4541. * @return {String} The node type.
  4542. */
  4543. getNodeType( builder ) {
  4544. return this.node.getNodeType( builder );
  4545. }
  4546. analyze( builder ) {
  4547. this.node.build( builder );
  4548. }
  4549. setup( builder ) {
  4550. const previousContext = builder.getContext();
  4551. builder.setContext( { ...builder.context, ...this.value } );
  4552. const node = this.node.build( builder );
  4553. builder.setContext( previousContext );
  4554. return node;
  4555. }
  4556. generate( builder, output ) {
  4557. const previousContext = builder.getContext();
  4558. builder.setContext( { ...builder.context, ...this.value } );
  4559. const snippet = this.node.build( builder, output );
  4560. builder.setContext( previousContext );
  4561. return snippet;
  4562. }
  4563. }
  4564. /**
  4565. * TSL function for creating a context node.
  4566. *
  4567. * @function
  4568. * @param {Node} node - The node whose context should be modified.
  4569. * @param {Object} [value={}] - The modified context data.
  4570. * @returns {ContextNode}
  4571. */
  4572. const context = /*@__PURE__*/ nodeProxy( ContextNode );
  4573. /**
  4574. * TSL function for defining a label context value for a given node.
  4575. *
  4576. * @function
  4577. * @param {Node} node - The node whose context should be modified.
  4578. * @param {String} name - The name/label to set.
  4579. * @returns {ContextNode}
  4580. */
  4581. const label = ( node, name ) => context( node, { label: name } );
  4582. addMethodChaining( 'context', context );
  4583. addMethodChaining( 'label', label );
  4584. /** @module VarNode **/
  4585. /**
  4586. * Class for representing shader variables as nodes. Variables are created from
  4587. * existing nodes like the following:
  4588. *
  4589. * ```js
  4590. * const depth = sampleDepth( uvNode ).toVar( 'depth' );
  4591. * ```
  4592. *
  4593. * @augments Node
  4594. */
  4595. class VarNode extends Node {
  4596. static get type() {
  4597. return 'VarNode';
  4598. }
  4599. /**
  4600. * Constructs a new variable node.
  4601. *
  4602. * @param {Node} node - The node for which a variable should be created.
  4603. * @param {String?} name - The name of the variable in the shader.
  4604. * @param {Boolean?} readOnly - The read-only flag.
  4605. */
  4606. constructor( node, name = null, readOnly = false ) {
  4607. super();
  4608. /**
  4609. * The node for which a variable should be created.
  4610. *
  4611. * @type {Node}
  4612. */
  4613. this.node = node;
  4614. /**
  4615. * The name of the variable in the shader. If no name is defined,
  4616. * the node system auto-generates one.
  4617. *
  4618. * @type {String?}
  4619. * @default null
  4620. */
  4621. this.name = name;
  4622. /**
  4623. * `VarNode` sets this property to `true` by default.
  4624. *
  4625. * @type {Boolean}
  4626. * @default true
  4627. */
  4628. this.global = true;
  4629. /**
  4630. * This flag can be used for type testing.
  4631. *
  4632. * @type {Boolean}
  4633. * @readonly
  4634. * @default true
  4635. */
  4636. this.isVarNode = true;
  4637. /**
  4638. *
  4639. * The read-only flag.
  4640. *
  4641. * @type {Boolean}
  4642. * @default false
  4643. */
  4644. this.readOnly = readOnly;
  4645. }
  4646. getHash( builder ) {
  4647. return this.name || super.getHash( builder );
  4648. }
  4649. getElementType( builder ) {
  4650. return this.node.getElementType( builder );
  4651. }
  4652. getNodeType( builder ) {
  4653. return this.node.getNodeType( builder );
  4654. }
  4655. generate( builder ) {
  4656. const { node, name, readOnly } = this;
  4657. const { renderer } = builder;
  4658. const isWebGPUBackend = renderer.backend.isWebGPUBackend === true;
  4659. let isDeterministic = false;
  4660. let shouldTreatAsReadOnly = false;
  4661. if ( readOnly ) {
  4662. isDeterministic = builder.isDeterministic( node );
  4663. shouldTreatAsReadOnly = isWebGPUBackend ? readOnly : isDeterministic;
  4664. }
  4665. const vectorType = builder.getVectorType( this.getNodeType( builder ) );
  4666. const snippet = node.build( builder, vectorType );
  4667. const nodeVar = builder.getVarFromNode( this, name, vectorType, undefined, shouldTreatAsReadOnly );
  4668. const propertyName = builder.getPropertyName( nodeVar );
  4669. let declarationPrefix = propertyName;
  4670. if ( shouldTreatAsReadOnly ) {
  4671. if ( isWebGPUBackend ) {
  4672. declarationPrefix = isDeterministic
  4673. ? `const ${ propertyName }`
  4674. : `let ${ propertyName }`;
  4675. } else {
  4676. const count = builder.getArrayCount( node );
  4677. declarationPrefix = `const ${ builder.getVar( nodeVar.type, propertyName, count ) }`;
  4678. }
  4679. }
  4680. builder.addLineFlowCode( `${ declarationPrefix } = ${ snippet }`, this );
  4681. return propertyName;
  4682. }
  4683. }
  4684. /**
  4685. * TSL function for creating a var node.
  4686. *
  4687. * @function
  4688. * @param {Node} node - The node for which a variable should be created.
  4689. * @param {String?} name - The name of the variable in the shader.
  4690. * @returns {VarNode}
  4691. */
  4692. const createVar = /*@__PURE__*/ nodeProxy( VarNode );
  4693. /**
  4694. * TSL function for creating a var node.
  4695. *
  4696. * @function
  4697. * @param {Node} node - The node for which a variable should be created.
  4698. * @param {String?} name - The name of the variable in the shader.
  4699. * @returns {VarNode}
  4700. */
  4701. const Var = ( node, name = null ) => createVar( node, name ).append();
  4702. /**
  4703. * TSL function for creating a const node.
  4704. *
  4705. * @function
  4706. * @param {Node} node - The node for which a constant should be created.
  4707. * @param {String?} name - The name of the constant in the shader.
  4708. * @returns {VarNode}
  4709. */
  4710. const Const = ( node, name = null ) => createVar( node, name, true ).append();
  4711. // Method chaining
  4712. addMethodChaining( 'toVar', Var );
  4713. addMethodChaining( 'toConst', Const );
  4714. // Deprecated
  4715. /**
  4716. * @function
  4717. * @deprecated since r170. Use `Var( node )` or `node.toVar()` instead.
  4718. *
  4719. * @param {Any} node
  4720. * @returns {VarNode}
  4721. */
  4722. const temp = ( node ) => { // @deprecated, r170
  4723. console.warn( 'TSL: "temp( node )" is deprecated. Use "Var( node )" or "node.toVar()" instead.' );
  4724. return createVar( node );
  4725. };
  4726. addMethodChaining( 'temp', temp );
  4727. /** @module VaryingNode **/
  4728. /**
  4729. * Class for representing shader varyings as nodes. Varyings are create from
  4730. * existing nodes like the following:
  4731. *
  4732. * ```js
  4733. * const positionLocal = positionGeometry.toVarying( 'vPositionLocal' );
  4734. * ```
  4735. *
  4736. * @augments Node
  4737. */
  4738. class VaryingNode extends Node {
  4739. static get type() {
  4740. return 'VaryingNode';
  4741. }
  4742. /**
  4743. * Constructs a new varying node.
  4744. *
  4745. * @param {Node} node - The node for which a varying should be created.
  4746. * @param {String?} name - The name of the varying in the shader.
  4747. */
  4748. constructor( node, name = null ) {
  4749. super();
  4750. /**
  4751. * The node for which a varying should be created.
  4752. *
  4753. * @type {Node}
  4754. */
  4755. this.node = node;
  4756. /**
  4757. * The name of the varying in the shader. If no name is defined,
  4758. * the node system auto-generates one.
  4759. *
  4760. * @type {String?}
  4761. * @default null
  4762. */
  4763. this.name = name;
  4764. /**
  4765. * This flag can be used for type testing.
  4766. *
  4767. * @type {Boolean}
  4768. * @readonly
  4769. * @default true
  4770. */
  4771. this.isVaryingNode = true;
  4772. }
  4773. /**
  4774. * The method is overwritten so it always returns `true`.
  4775. *
  4776. * @param {NodeBuilder} builder - The current node builder.
  4777. * @return {Boolean} Whether this node is global or not.
  4778. */
  4779. isGlobal( /*builder*/ ) {
  4780. return true;
  4781. }
  4782. getHash( builder ) {
  4783. return this.name || super.getHash( builder );
  4784. }
  4785. getNodeType( builder ) {
  4786. // VaryingNode is auto type
  4787. return this.node.getNodeType( builder );
  4788. }
  4789. /**
  4790. * This method performs the setup of a varying node with the current node builder.
  4791. *
  4792. * @param {NodeBuilder} builder - The current node builder.
  4793. * @return {NodeVarying} The node varying from the node builder.
  4794. */
  4795. setupVarying( builder ) {
  4796. const properties = builder.getNodeProperties( this );
  4797. let varying = properties.varying;
  4798. if ( varying === undefined ) {
  4799. const name = this.name;
  4800. const type = this.getNodeType( builder );
  4801. properties.varying = varying = builder.getVaryingFromNode( this, name, type );
  4802. properties.node = this.node;
  4803. }
  4804. // this property can be used to check if the varying can be optimized for a variable
  4805. varying.needsInterpolation || ( varying.needsInterpolation = ( builder.shaderStage === 'fragment' ) );
  4806. return varying;
  4807. }
  4808. setup( builder ) {
  4809. this.setupVarying( builder );
  4810. }
  4811. analyze( builder ) {
  4812. this.setupVarying( builder );
  4813. return this.node.analyze( builder );
  4814. }
  4815. generate( builder ) {
  4816. const properties = builder.getNodeProperties( this );
  4817. const varying = this.setupVarying( builder );
  4818. const needsReassign = builder.shaderStage === 'fragment' && properties.reassignPosition === true && builder.context.needsPositionReassign;
  4819. if ( properties.propertyName === undefined || needsReassign ) {
  4820. const type = this.getNodeType( builder );
  4821. const propertyName = builder.getPropertyName( varying, NodeShaderStage.VERTEX );
  4822. // force node run in vertex stage
  4823. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node, type, propertyName );
  4824. properties.propertyName = propertyName;
  4825. if ( needsReassign ) {
  4826. // once reassign varying in fragment stage
  4827. properties.reassignPosition = false;
  4828. } else if ( properties.reassignPosition === undefined && builder.context.isPositionNodeInput ) {
  4829. properties.reassignPosition = true;
  4830. }
  4831. }
  4832. return builder.getPropertyName( varying );
  4833. }
  4834. }
  4835. /**
  4836. * TSL function for creating a varying node.
  4837. *
  4838. * @function
  4839. * @param {Node} node - The node for which a varying should be created.
  4840. * @param {String?} name - The name of the varying in the shader.
  4841. * @returns {VaryingNode}
  4842. */
  4843. const varying = /*@__PURE__*/ nodeProxy( VaryingNode );
  4844. /**
  4845. * Computes a node in the vertex stage.
  4846. *
  4847. * @function
  4848. * @param {Node} node - The node which should be executed in the vertex stage.
  4849. * @returns {VaryingNode}
  4850. */
  4851. const vertexStage = ( node ) => varying( node );
  4852. addMethodChaining( 'toVarying', varying );
  4853. addMethodChaining( 'toVertexStage', vertexStage );
  4854. // Deprecated
  4855. addMethodChaining( 'varying', ( ...params ) => { // @deprecated, r173
  4856. console.warn( 'TSL.VaryingNode: .varying() has been renamed to .toVarying().' );
  4857. return varying( ...params );
  4858. } );
  4859. addMethodChaining( 'vertexStage', ( ...params ) => { // @deprecated, r173
  4860. console.warn( 'TSL.VaryingNode: .vertexStage() has been renamed to .toVertexStage().' );
  4861. return varying( ...params );
  4862. } );
  4863. /** @module ColorSpaceFunctions **/
  4864. /**
  4865. * Converts the given color value from sRGB to linear-sRGB color space.
  4866. *
  4867. * @method
  4868. * @param {Node<vec3>} color - The sRGB color.
  4869. * @return {Node<vec3>} The linear-sRGB color.
  4870. */
  4871. const sRGBTransferEOTF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  4872. const a = color.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 );
  4873. const b = color.mul( 0.0773993808 );
  4874. const factor = color.lessThanEqual( 0.04045 );
  4875. const rgbResult = mix( a, b, factor );
  4876. return rgbResult;
  4877. } ).setLayout( {
  4878. name: 'sRGBTransferEOTF',
  4879. type: 'vec3',
  4880. inputs: [
  4881. { name: 'color', type: 'vec3' }
  4882. ]
  4883. } );
  4884. /**
  4885. * Converts the given color value from linear-sRGB to sRGB color space.
  4886. *
  4887. * @method
  4888. * @param {Node<vec3>} color - The linear-sRGB color.
  4889. * @return {Node<vec3>} The sRGB color.
  4890. */
  4891. const sRGBTransferOETF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  4892. const a = color.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 );
  4893. const b = color.mul( 12.92 );
  4894. const factor = color.lessThanEqual( 0.0031308 );
  4895. const rgbResult = mix( a, b, factor );
  4896. return rgbResult;
  4897. } ).setLayout( {
  4898. name: 'sRGBTransferOETF',
  4899. type: 'vec3',
  4900. inputs: [
  4901. { name: 'color', type: 'vec3' }
  4902. ]
  4903. } );
  4904. /** @module ColorSpaceNode **/
  4905. const WORKING_COLOR_SPACE = 'WorkingColorSpace';
  4906. const OUTPUT_COLOR_SPACE = 'OutputColorSpace';
  4907. /**
  4908. * This node represents a color space conversion. Meaning it converts
  4909. * a color value from a source to a target color space.
  4910. *
  4911. * @augments TempNode
  4912. */
  4913. class ColorSpaceNode extends TempNode {
  4914. static get type() {
  4915. return 'ColorSpaceNode';
  4916. }
  4917. /**
  4918. * Constructs a new color space node.
  4919. *
  4920. * @param {Node} colorNode - Represents the color to convert.
  4921. * @param {String} source - The source color space.
  4922. * @param {String} target - The target color space.
  4923. */
  4924. constructor( colorNode, source, target ) {
  4925. super( 'vec4' );
  4926. /**
  4927. * Represents the color to convert.
  4928. *
  4929. * @type {Node}
  4930. */
  4931. this.colorNode = colorNode;
  4932. /**
  4933. * The source color space.
  4934. *
  4935. * @type {String}
  4936. */
  4937. this.source = source;
  4938. /**
  4939. * The target color space.
  4940. *
  4941. * @type {String}
  4942. */
  4943. this.target = target;
  4944. }
  4945. /**
  4946. * This method resolves the constants `WORKING_COLOR_SPACE` and
  4947. * `OUTPUT_COLOR_SPACE` based on the current configuration of the
  4948. * color management and renderer.
  4949. *
  4950. * @param {NodeBuilder} builder - The current node builder.
  4951. * @param {String} colorSpace - The color space to resolve.
  4952. * @return {String} The resolved color space.
  4953. */
  4954. resolveColorSpace( builder, colorSpace ) {
  4955. if ( colorSpace === WORKING_COLOR_SPACE ) {
  4956. return ColorManagement.workingColorSpace;
  4957. } else if ( colorSpace === OUTPUT_COLOR_SPACE ) {
  4958. return builder.context.outputColorSpace || builder.renderer.outputColorSpace;
  4959. }
  4960. return colorSpace;
  4961. }
  4962. setup( builder ) {
  4963. const { colorNode } = this;
  4964. const source = this.resolveColorSpace( builder, this.source );
  4965. const target = this.resolveColorSpace( builder, this.target );
  4966. let outputNode = colorNode;
  4967. if ( ColorManagement.enabled === false || source === target || ! source || ! target ) {
  4968. return outputNode;
  4969. }
  4970. if ( ColorManagement.getTransfer( source ) === SRGBTransfer ) {
  4971. outputNode = vec4( sRGBTransferEOTF( outputNode.rgb ), outputNode.a );
  4972. }
  4973. if ( ColorManagement.getPrimaries( source ) !== ColorManagement.getPrimaries( target ) ) {
  4974. outputNode = vec4(
  4975. mat3( ColorManagement._getMatrix( new Matrix3(), source, target ) ).mul( outputNode.rgb ),
  4976. outputNode.a
  4977. );
  4978. }
  4979. if ( ColorManagement.getTransfer( target ) === SRGBTransfer ) {
  4980. outputNode = vec4( sRGBTransferOETF( outputNode.rgb ), outputNode.a );
  4981. }
  4982. return outputNode;
  4983. }
  4984. }
  4985. /**
  4986. * TSL function for converting a given color node to the current output color space.
  4987. *
  4988. * @function
  4989. * @param {Node} node - Represents the node to convert.
  4990. * @returns {ColorSpaceNode}
  4991. */
  4992. const toOutputColorSpace = ( node ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, OUTPUT_COLOR_SPACE ) );
  4993. /**
  4994. * TSL function for converting a given color node to the current working color space.
  4995. *
  4996. * @function
  4997. * @param {Node} node - Represents the node to convert.
  4998. * @returns {ColorSpaceNode}
  4999. */
  5000. const toWorkingColorSpace = ( node ) => nodeObject( new ColorSpaceNode( nodeObject( node ), OUTPUT_COLOR_SPACE, WORKING_COLOR_SPACE ) );
  5001. /**
  5002. * TSL function for converting a given color node from the current working color space to the given color space.
  5003. *
  5004. * @function
  5005. * @param {Node} node - Represents the node to convert.
  5006. * @param {String} colorSpace - The target color space.
  5007. * @returns {ColorSpaceNode}
  5008. */
  5009. const workingToColorSpace = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, colorSpace ) );
  5010. /**
  5011. * TSL function for converting a given color node from the given color space to the current working color space.
  5012. *
  5013. * @function
  5014. * @param {Node} node - Represents the node to convert.
  5015. * @param {String} colorSpace - The source color space.
  5016. * @returns {ColorSpaceNode}
  5017. */
  5018. const colorSpaceToWorking = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), colorSpace, WORKING_COLOR_SPACE ) );
  5019. /**
  5020. * TSL function for converting a given color node from one color space to another one.
  5021. *
  5022. * @function
  5023. * @param {Node} node - Represents the node to convert.
  5024. * @param {String} sourceColorSpace - The source color space.
  5025. * @param {String} targetColorSpace - The target color space.
  5026. * @returns {ColorSpaceNode}
  5027. */
  5028. const convertColorSpace = ( node, sourceColorSpace, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, targetColorSpace ) );
  5029. addMethodChaining( 'toOutputColorSpace', toOutputColorSpace );
  5030. addMethodChaining( 'toWorkingColorSpace', toWorkingColorSpace );
  5031. addMethodChaining( 'workingToColorSpace', workingToColorSpace );
  5032. addMethodChaining( 'colorSpaceToWorking', colorSpaceToWorking );
  5033. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  5034. /** @module ReferenceBaseNode **/
  5035. /**
  5036. * This class is only relevant if the referenced property is array-like.
  5037. * In this case, `ReferenceElementNode` allows to refer to a specific
  5038. * element inside the data structure via an index.
  5039. *
  5040. * @augments ArrayElementNode
  5041. */
  5042. let ReferenceElementNode$1 = class ReferenceElementNode extends ArrayElementNode {
  5043. static get type() {
  5044. return 'ReferenceElementNode';
  5045. }
  5046. /**
  5047. * Constructs a new reference element node.
  5048. *
  5049. * @param {ReferenceBaseNode?} referenceNode - The reference node.
  5050. * @param {Node} indexNode - The index node that defines the element access.
  5051. */
  5052. constructor( referenceNode, indexNode ) {
  5053. super( referenceNode, indexNode );
  5054. /**
  5055. * Similar to {@link module:ReferenceBaseNode~ReferenceBaseNode#reference}, an additional
  5056. * property references to the current node.
  5057. *
  5058. * @type {ReferenceBaseNode?}
  5059. * @default null
  5060. */
  5061. this.referenceNode = referenceNode;
  5062. /**
  5063. * This flag can be used for type testing.
  5064. *
  5065. * @type {Boolean}
  5066. * @readonly
  5067. * @default true
  5068. */
  5069. this.isReferenceElementNode = true;
  5070. }
  5071. /**
  5072. * This method is overwritten since the node type is inferred from
  5073. * the uniform type of the reference node.
  5074. *
  5075. * @return {String} The node type.
  5076. */
  5077. getNodeType() {
  5078. return this.referenceNode.uniformType;
  5079. }
  5080. generate( builder ) {
  5081. const snippet = super.generate( builder );
  5082. const arrayType = this.referenceNode.getNodeType();
  5083. const elementType = this.getNodeType();
  5084. return builder.format( snippet, arrayType, elementType );
  5085. }
  5086. };
  5087. /**
  5088. * Base class for nodes which establishes a reference to a property of another object.
  5089. * In this way, the value of the node is automatically linked to the value of
  5090. * referenced object. Reference nodes internally represent the linked value
  5091. * as a uniform.
  5092. *
  5093. * @augments Node
  5094. */
  5095. class ReferenceBaseNode extends Node {
  5096. static get type() {
  5097. return 'ReferenceBaseNode';
  5098. }
  5099. /**
  5100. * Constructs a new reference base node.
  5101. *
  5102. * @param {String} property - The name of the property the node refers to.
  5103. * @param {String} uniformType - The uniform type that should be used to represent the property value.
  5104. * @param {Object?} [object=null] - The object the property belongs to.
  5105. * @param {Number?} [count=null] - When the linked property is an array-like, this parameter defines its length.
  5106. */
  5107. constructor( property, uniformType, object = null, count = null ) {
  5108. super();
  5109. /**
  5110. * The name of the property the node refers to.
  5111. *
  5112. * @type {String}
  5113. */
  5114. this.property = property;
  5115. /**
  5116. * The uniform type that should be used to represent the property value.
  5117. *
  5118. * @type {String}
  5119. */
  5120. this.uniformType = uniformType;
  5121. /**
  5122. * The object the property belongs to.
  5123. *
  5124. * @type {Object?}
  5125. * @default null
  5126. */
  5127. this.object = object;
  5128. /**
  5129. * When the linked property is an array, this parameter defines its length.
  5130. *
  5131. * @type {Number?}
  5132. * @default null
  5133. */
  5134. this.count = count;
  5135. /**
  5136. * The property name might have dots so nested properties can be referred.
  5137. * The hierarchy of the names is stored inside this array.
  5138. *
  5139. * @type {Array<String>}
  5140. */
  5141. this.properties = property.split( '.' );
  5142. /**
  5143. * Points to the current referred object. This property exists next to {@link module:ReferenceNode~ReferenceNode#object}
  5144. * since the final reference might be updated from calling code.
  5145. *
  5146. * @type {Object?}
  5147. * @default null
  5148. */
  5149. this.reference = object;
  5150. /**
  5151. * The uniform node that holds the value of the reference node.
  5152. *
  5153. * @type {UniformNode}
  5154. * @default null
  5155. */
  5156. this.node = null;
  5157. /**
  5158. * The uniform group of the internal uniform.
  5159. *
  5160. * @type {UniformGroupNode}
  5161. * @default null
  5162. */
  5163. this.group = null;
  5164. /**
  5165. * Overwritten since reference nodes are updated per object.
  5166. *
  5167. * @type {String}
  5168. * @default 'object'
  5169. */
  5170. this.updateType = NodeUpdateType.OBJECT;
  5171. }
  5172. /**
  5173. * Sets the uniform group for this reference node.
  5174. *
  5175. * @param {UniformGroupNode} group - The uniform group to set.
  5176. * @return {ReferenceBaseNode} A reference to this node.
  5177. */
  5178. setGroup( group ) {
  5179. this.group = group;
  5180. return this;
  5181. }
  5182. /**
  5183. * When the referred property is array-like, this method can be used
  5184. * to access elements via an index node.
  5185. *
  5186. * @param {IndexNode} indexNode - indexNode.
  5187. * @return {ReferenceElementNode} A reference to an element.
  5188. */
  5189. element( indexNode ) {
  5190. return nodeObject( new ReferenceElementNode$1( this, nodeObject( indexNode ) ) );
  5191. }
  5192. /**
  5193. * Sets the node type which automatically defines the internal
  5194. * uniform type.
  5195. *
  5196. * @param {String} uniformType - The type to set.
  5197. */
  5198. setNodeType( uniformType ) {
  5199. const node = uniform( null, uniformType ).getSelf();
  5200. if ( this.group !== null ) {
  5201. node.setGroup( this.group );
  5202. }
  5203. this.node = node;
  5204. }
  5205. /**
  5206. * This method is overwritten since the node type is inferred from
  5207. * the type of the reference node.
  5208. *
  5209. * @param {NodeBuilder} builder - The current node builder.
  5210. * @return {String} The node type.
  5211. */
  5212. getNodeType( builder ) {
  5213. if ( this.node === null ) {
  5214. this.updateReference( builder );
  5215. this.updateValue();
  5216. }
  5217. return this.node.getNodeType( builder );
  5218. }
  5219. /**
  5220. * Returns the property value from the given referred object.
  5221. *
  5222. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  5223. * @return {Any} The value.
  5224. */
  5225. getValueFromReference( object = this.reference ) {
  5226. const { properties } = this;
  5227. let value = object[ properties[ 0 ] ];
  5228. for ( let i = 1; i < properties.length; i ++ ) {
  5229. value = value[ properties[ i ] ];
  5230. }
  5231. return value;
  5232. }
  5233. /**
  5234. * Allows to update the reference based on the given state. The state is only
  5235. * evaluated {@link module:ReferenceBaseNode~ReferenceBaseNode#object} is not set.
  5236. *
  5237. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  5238. * @return {Object} The updated reference.
  5239. */
  5240. updateReference( state ) {
  5241. this.reference = this.object !== null ? this.object : state.object;
  5242. return this.reference;
  5243. }
  5244. /**
  5245. * The output of the reference node is the internal uniform node.
  5246. *
  5247. * @return {UniformNode} The output node.
  5248. */
  5249. setup() {
  5250. this.updateValue();
  5251. return this.node;
  5252. }
  5253. /**
  5254. * Overwritten to to update the internal uniform value.
  5255. *
  5256. * @param {NodeFrame} frame - A reference to the current node frame.
  5257. */
  5258. update( /*frame*/ ) {
  5259. this.updateValue();
  5260. }
  5261. /**
  5262. * Retrieves the value from the referred object property and uses it
  5263. * to updated the internal uniform.
  5264. */
  5265. updateValue() {
  5266. if ( this.node === null ) this.setNodeType( this.uniformType );
  5267. const value = this.getValueFromReference();
  5268. if ( Array.isArray( value ) ) {
  5269. this.node.array = value;
  5270. } else {
  5271. this.node.value = value;
  5272. }
  5273. }
  5274. }
  5275. /**
  5276. * TSL function for creating a reference base node.
  5277. *
  5278. * @function
  5279. * @param {String} name - The name of the property the node refers to.
  5280. * @param {String} type - The uniform type that should be used to represent the property value.
  5281. * @param {Object} object - The object the property belongs to.
  5282. * @returns {ReferenceBaseNode}
  5283. */
  5284. const reference$1 = ( name, type, object ) => nodeObject( new ReferenceBaseNode( name, type, object ) );
  5285. /** @module RendererReferenceNode **/
  5286. /**
  5287. * This node is a special type of reference node which is intended
  5288. * for linking renderer properties with node values.
  5289. * ```js
  5290. * const exposureNode = rendererReference( 'toneMappingExposure', 'float', renderer );
  5291. * ```
  5292. * When changing `renderer.toneMappingExposure`, the node value of `exposureNode` will
  5293. * automatically be updated.
  5294. *
  5295. * @augments ReferenceBaseNode
  5296. */
  5297. class RendererReferenceNode extends ReferenceBaseNode {
  5298. static get type() {
  5299. return 'RendererReferenceNode';
  5300. }
  5301. /**
  5302. * Constructs a new renderer reference node.
  5303. *
  5304. * @param {String} property - The name of the property the node refers to.
  5305. * @param {String} inputType - The uniform type that should be used to represent the property value.
  5306. * @param {Renderer?} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  5307. * the node refers to the renderer of the current state.
  5308. */
  5309. constructor( property, inputType, renderer = null ) {
  5310. super( property, inputType, renderer );
  5311. /**
  5312. * The renderer the property belongs to. When no renderer is set,
  5313. * the node refers to the renderer of the current state.
  5314. *
  5315. * @type {Renderer?}
  5316. * @default null
  5317. */
  5318. this.renderer = renderer;
  5319. this.setGroup( renderGroup );
  5320. }
  5321. /**
  5322. * Updates the reference based on the given state. The state is only evaluated
  5323. * {@link module:RendererReferenceNode~RendererReferenceNode#renderer} is not set.
  5324. *
  5325. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  5326. * @return {Object} The updated reference.
  5327. */
  5328. updateReference( state ) {
  5329. this.reference = this.renderer !== null ? this.renderer : state.renderer;
  5330. return this.reference;
  5331. }
  5332. }
  5333. /**
  5334. * TSL function for creating a renderer reference node.
  5335. *
  5336. * @function
  5337. * @param {String} name - The name of the property the node refers to.
  5338. * @param {String} type - The uniform type that should be used to represent the property value.
  5339. * @param {Renderer?} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  5340. * the node refers to the renderer of the current state.
  5341. * @returns {RendererReferenceNode}
  5342. */
  5343. const rendererReference = ( name, type, renderer = null ) => nodeObject( new RendererReferenceNode( name, type, renderer ) );
  5344. /** @module ToneMappingNode **/
  5345. /**
  5346. * This node represents a tone mapping operation.
  5347. *
  5348. * @augments TempNode
  5349. */
  5350. class ToneMappingNode extends TempNode {
  5351. static get type() {
  5352. return 'ToneMappingNode';
  5353. }
  5354. /**
  5355. * Constructs a new tone mapping node.
  5356. *
  5357. * @param {Number} toneMapping - The tone mapping type.
  5358. * @param {Node} exposureNode - The tone mapping exposure.
  5359. * @param {Node} [colorNode=null] - The color node to process.
  5360. */
  5361. constructor( toneMapping, exposureNode = toneMappingExposure, colorNode = null ) {
  5362. super( 'vec3' );
  5363. /**
  5364. * The tone mapping type.
  5365. *
  5366. * @type {Number}
  5367. */
  5368. this.toneMapping = toneMapping;
  5369. /**
  5370. * The tone mapping exposure.
  5371. *
  5372. * @type {Node}
  5373. * @default null
  5374. */
  5375. this.exposureNode = exposureNode;
  5376. /**
  5377. * Represents the color to process.
  5378. *
  5379. * @type {Node?}
  5380. * @default null
  5381. */
  5382. this.colorNode = colorNode;
  5383. }
  5384. /**
  5385. * Overwrites the default `customCacheKey()` implementation by including the tone
  5386. * mapping type into the cache key.
  5387. *
  5388. * @return {Number} The hash.
  5389. */
  5390. customCacheKey() {
  5391. return hash$1( this.toneMapping );
  5392. }
  5393. setup( builder ) {
  5394. const colorNode = this.colorNode || builder.context.color;
  5395. const toneMapping = this.toneMapping;
  5396. if ( toneMapping === NoToneMapping ) return colorNode;
  5397. let outputNode = null;
  5398. const toneMappingFn = builder.renderer.library.getToneMappingFunction( toneMapping );
  5399. if ( toneMappingFn !== null ) {
  5400. outputNode = vec4( toneMappingFn( colorNode.rgb, this.exposureNode ), colorNode.a );
  5401. } else {
  5402. console.error( 'ToneMappingNode: Unsupported Tone Mapping configuration.', toneMapping );
  5403. outputNode = colorNode;
  5404. }
  5405. return outputNode;
  5406. }
  5407. }
  5408. /**
  5409. * TSL function for creating a tone mapping node.
  5410. *
  5411. * @function
  5412. * @param {Number} mapping - The tone mapping type.
  5413. * @param {Node<float> | Number} exposure - The tone mapping exposure.
  5414. * @param {Node<vec3> | Color} color - The color node to process.
  5415. * @returns {ToneMappingNode<vec3>}
  5416. */
  5417. const toneMapping = ( mapping, exposure, color ) => nodeObject( new ToneMappingNode( mapping, nodeObject( exposure ), nodeObject( color ) ) );
  5418. /**
  5419. * TSL object that represents the global tone mapping exposure of the renderer.
  5420. *
  5421. * @type {RendererReferenceNode<vec3>}
  5422. */
  5423. const toneMappingExposure = /*@__PURE__*/ rendererReference( 'toneMappingExposure', 'float' );
  5424. addMethodChaining( 'toneMapping', ( color, mapping, exposure ) => toneMapping( mapping, exposure, color ) );
  5425. /** @module BufferAttributeNode **/
  5426. /**
  5427. * In earlier `three.js` versions it was only possible to define attribute data
  5428. * on geometry level. With `BufferAttributeNode`, it is also possible to do this
  5429. * on the node level.
  5430. * ```js
  5431. * const geometry = new THREE.PlaneGeometry();
  5432. * const positionAttribute = geometry.getAttribute( 'position' );
  5433. *
  5434. * const colors = [];
  5435. * for ( let i = 0; i < position.count; i ++ ) {
  5436. * colors.push( 1, 0, 0 );
  5437. * }
  5438. *
  5439. * material.colorNode = bufferAttribute( new THREE.Float32BufferAttribute( colors, 3 ) );
  5440. * ```
  5441. * This new approach is especially interesting when geometry data are generated via
  5442. * compute shaders. The below line converts a storage buffer into an attribute node.
  5443. * ```js
  5444. * material.positionNode = positionBuffer.toAttribute();
  5445. * ```
  5446. * @augments InputNode
  5447. */
  5448. class BufferAttributeNode extends InputNode {
  5449. static get type() {
  5450. return 'BufferAttributeNode';
  5451. }
  5452. /**
  5453. * Constructs a new buffer attribute node.
  5454. *
  5455. * @param {BufferAttribute|InterleavedBuffer|TypedArray} value - The attribute data.
  5456. * @param {String?} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  5457. * @param {Number} [bufferStride=0] - The buffer stride.
  5458. * @param {Number} [bufferOffset=0] - The buffer offset.
  5459. */
  5460. constructor( value, bufferType = null, bufferStride = 0, bufferOffset = 0 ) {
  5461. super( value, bufferType );
  5462. /**
  5463. * This flag can be used for type testing.
  5464. *
  5465. * @type {Boolean}
  5466. * @readonly
  5467. * @default true
  5468. */
  5469. this.isBufferNode = true;
  5470. /**
  5471. * The buffer type (e.g. `'vec3'`).
  5472. *
  5473. * @type {String}
  5474. * @default null
  5475. */
  5476. this.bufferType = bufferType;
  5477. /**
  5478. * The buffer stride.
  5479. *
  5480. * @type {Number}
  5481. * @default 0
  5482. */
  5483. this.bufferStride = bufferStride;
  5484. /**
  5485. * The buffer offset.
  5486. *
  5487. * @type {Number}
  5488. * @default 0
  5489. */
  5490. this.bufferOffset = bufferOffset;
  5491. /**
  5492. * The usage property. Set this to `THREE.DynamicDrawUsage` via `.setUsage()`,
  5493. * if you are planning to update the attribute data per frame.
  5494. *
  5495. * @type {Number}
  5496. * @default StaticDrawUsage
  5497. */
  5498. this.usage = StaticDrawUsage;
  5499. /**
  5500. * Whether the attribute is instanced or not.
  5501. *
  5502. * @type {Boolean}
  5503. * @default false
  5504. */
  5505. this.instanced = false;
  5506. /**
  5507. * A reference to the buffer attribute.
  5508. *
  5509. * @type {BufferAttribute?}
  5510. * @default null
  5511. */
  5512. this.attribute = null;
  5513. /**
  5514. * `BufferAttributeNode` sets this property to `true` by default.
  5515. *
  5516. * @type {Boolean}
  5517. * @default true
  5518. */
  5519. this.global = true;
  5520. if ( value && value.isBufferAttribute === true ) {
  5521. this.attribute = value;
  5522. this.usage = value.usage;
  5523. this.instanced = value.isInstancedBufferAttribute;
  5524. }
  5525. }
  5526. /**
  5527. * This method is overwritten since the attribute data might be shared
  5528. * and thus the hash should be shared as well.
  5529. *
  5530. * @param {NodeBuilder} builder - The current node builder.
  5531. * @return {String} The hash.
  5532. */
  5533. getHash( builder ) {
  5534. if ( this.bufferStride === 0 && this.bufferOffset === 0 ) {
  5535. let bufferData = builder.globalCache.getData( this.value );
  5536. if ( bufferData === undefined ) {
  5537. bufferData = {
  5538. node: this
  5539. };
  5540. builder.globalCache.setData( this.value, bufferData );
  5541. }
  5542. return bufferData.node.uuid;
  5543. }
  5544. return this.uuid;
  5545. }
  5546. /**
  5547. * This method is overwritten since the node type is inferred from
  5548. * the buffer attribute.
  5549. *
  5550. * @param {NodeBuilder} builder - The current node builder.
  5551. * @return {String} The node type.
  5552. */
  5553. getNodeType( builder ) {
  5554. if ( this.bufferType === null ) {
  5555. this.bufferType = builder.getTypeFromAttribute( this.attribute );
  5556. }
  5557. return this.bufferType;
  5558. }
  5559. /**
  5560. * Depending on which value was passed to the node, `setup()` behaves
  5561. * differently. If no instance of `BufferAttribute` was passed, the method
  5562. * creates an internal attribute and configures it respectively.
  5563. *
  5564. * @param {NodeBuilder} builder - The current node builder.
  5565. */
  5566. setup( builder ) {
  5567. if ( this.attribute !== null ) return;
  5568. const type = this.getNodeType( builder );
  5569. const array = this.value;
  5570. const itemSize = builder.getTypeLength( type );
  5571. const stride = this.bufferStride || itemSize;
  5572. const offset = this.bufferOffset;
  5573. const buffer = array.isInterleavedBuffer === true ? array : new InterleavedBuffer( array, stride );
  5574. const bufferAttribute = new InterleavedBufferAttribute( buffer, itemSize, offset );
  5575. buffer.setUsage( this.usage );
  5576. this.attribute = bufferAttribute;
  5577. this.attribute.isInstancedBufferAttribute = this.instanced; // @TODO: Add a possible: InstancedInterleavedBufferAttribute
  5578. }
  5579. /**
  5580. * Generates the code snippet of the buffer attribute node.
  5581. *
  5582. * @param {NodeBuilder} builder - The current node builder.
  5583. * @return {String} The generated code snippet.
  5584. */
  5585. generate( builder ) {
  5586. const nodeType = this.getNodeType( builder );
  5587. const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType );
  5588. const propertyName = builder.getPropertyName( nodeAttribute );
  5589. let output = null;
  5590. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  5591. this.name = propertyName;
  5592. output = propertyName;
  5593. } else {
  5594. const nodeVarying = varying( this );
  5595. output = nodeVarying.build( builder, nodeType );
  5596. }
  5597. return output;
  5598. }
  5599. /**
  5600. * Overwrites the default implementation to return a fixed value `'bufferAttribute'`.
  5601. *
  5602. * @param {NodeBuilder} builder - The current node builder.
  5603. * @return {String} The input type.
  5604. */
  5605. getInputType( /*builder*/ ) {
  5606. return 'bufferAttribute';
  5607. }
  5608. /**
  5609. * Sets the `usage` property to the given value.
  5610. *
  5611. * @param {Number} value - The usage to set.
  5612. * @return {BufferAttributeNode} A reference to this node.
  5613. */
  5614. setUsage( value ) {
  5615. this.usage = value;
  5616. if ( this.attribute && this.attribute.isBufferAttribute === true ) {
  5617. this.attribute.usage = value;
  5618. }
  5619. return this;
  5620. }
  5621. /**
  5622. * Sets the `instanced` property to the given value.
  5623. *
  5624. * @param {Boolean} value - The value to set.
  5625. * @return {BufferAttributeNode} A reference to this node.
  5626. */
  5627. setInstanced( value ) {
  5628. this.instanced = value;
  5629. return this;
  5630. }
  5631. }
  5632. /**
  5633. * TSL function for creating a buffer attribute node.
  5634. *
  5635. * @function
  5636. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  5637. * @param {String?} [type=null] - The buffer type (e.g. `'vec3'`).
  5638. * @param {Number} [stride=0] - The buffer stride.
  5639. * @param {Number} [offset=0] - The buffer offset.
  5640. * @returns {BufferAttributeNode}
  5641. */
  5642. const bufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => nodeObject( new BufferAttributeNode( array, type, stride, offset ) );
  5643. /**
  5644. * TSL function for creating a buffer attribute node but with dynamic draw usage.
  5645. * Use this function if attribute data are updated per frame.
  5646. *
  5647. * @function
  5648. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  5649. * @param {String?} [type=null] - The buffer type (e.g. `'vec3'`).
  5650. * @param {Number} [stride=0] - The buffer stride.
  5651. * @param {Number} [offset=0] - The buffer offset.
  5652. * @returns {BufferAttributeNode}
  5653. */
  5654. const dynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => bufferAttribute( array, type, stride, offset ).setUsage( DynamicDrawUsage );
  5655. /**
  5656. * TSL function for creating a buffer attribute node but with enabled instancing
  5657. *
  5658. * @function
  5659. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  5660. * @param {String?} [type=null] - The buffer type (e.g. `'vec3'`).
  5661. * @param {Number} [stride=0] - The buffer stride.
  5662. * @param {Number} [offset=0] - The buffer offset.
  5663. * @returns {BufferAttributeNode}
  5664. */
  5665. const instancedBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => bufferAttribute( array, type, stride, offset ).setInstanced( true );
  5666. /**
  5667. * TSL function for creating a buffer attribute node but with dynamic draw usage and enabled instancing
  5668. *
  5669. * @function
  5670. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  5671. * @param {String?} [type=null] - The buffer type (e.g. `'vec3'`).
  5672. * @param {Number} [stride=0] - The buffer stride.
  5673. * @param {Number} [offset=0] - The buffer offset.
  5674. * @returns {BufferAttributeNode}
  5675. */
  5676. const instancedDynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => dynamicBufferAttribute( array, type, stride, offset ).setInstanced( true );
  5677. addMethodChaining( 'toAttribute', ( bufferNode ) => bufferAttribute( bufferNode.value ) );
  5678. /** @module ComputeNode **/
  5679. /**
  5680. * TODO
  5681. *
  5682. * @augments Node
  5683. */
  5684. class ComputeNode extends Node {
  5685. static get type() {
  5686. return 'ComputeNode';
  5687. }
  5688. /**
  5689. * Constructs a new compute node.
  5690. *
  5691. * @param {Node} computeNode - TODO
  5692. * @param {Number} count - TODO.
  5693. * @param {Array<Number>} [workgroupSize=[64]] - TODO.
  5694. */
  5695. constructor( computeNode, count, workgroupSize = [ 64 ] ) {
  5696. super( 'void' );
  5697. /**
  5698. * This flag can be used for type testing.
  5699. *
  5700. * @type {Boolean}
  5701. * @readonly
  5702. * @default true
  5703. */
  5704. this.isComputeNode = true;
  5705. /**
  5706. * TODO
  5707. *
  5708. * @type {Node}
  5709. */
  5710. this.computeNode = computeNode;
  5711. /**
  5712. * TODO
  5713. *
  5714. * @type {Number}
  5715. */
  5716. this.count = count;
  5717. /**
  5718. * TODO
  5719. *
  5720. * @type {Array<Number>}
  5721. * @default [64]
  5722. */
  5723. this.workgroupSize = workgroupSize;
  5724. /**
  5725. * TODO
  5726. *
  5727. * @type {Number}
  5728. */
  5729. this.dispatchCount = 0;
  5730. /**
  5731. * TODO
  5732. *
  5733. * @type {Number}
  5734. */
  5735. this.version = 1;
  5736. /**
  5737. * The name or label of the uniform.
  5738. *
  5739. * @type {String}
  5740. * @default ''
  5741. */
  5742. this.name = '';
  5743. /**
  5744. * The `updateBeforeType` is set to `NodeUpdateType.OBJECT` since {@link ComputeNode#updateBefore}
  5745. * is executed once per object by default.
  5746. *
  5747. * @type {String}
  5748. * @default 'object'
  5749. */
  5750. this.updateBeforeType = NodeUpdateType.OBJECT;
  5751. /**
  5752. * TODO
  5753. *
  5754. * @type {Function}
  5755. */
  5756. this.onInitFunction = null;
  5757. this.updateDispatchCount();
  5758. }
  5759. /**
  5760. * Executes the `dispose` event for this node.
  5761. */
  5762. dispose() {
  5763. this.dispatchEvent( { type: 'dispose' } );
  5764. }
  5765. /**
  5766. * Sets the {@link ComputeNode#name} property.
  5767. *
  5768. * @param {String} name - The name of the uniform.
  5769. * @return {ComputeNode} A reference to this node.
  5770. */
  5771. label( name ) {
  5772. this.name = name;
  5773. return this;
  5774. }
  5775. /**
  5776. * TODO
  5777. */
  5778. updateDispatchCount() {
  5779. const { count, workgroupSize } = this;
  5780. let size = workgroupSize[ 0 ];
  5781. for ( let i = 1; i < workgroupSize.length; i ++ )
  5782. size *= workgroupSize[ i ];
  5783. this.dispatchCount = Math.ceil( count / size );
  5784. }
  5785. /**
  5786. * TODO
  5787. *
  5788. * @param {Function} callback - TODO.
  5789. * @return {ComputeNode} A reference to this node.
  5790. */
  5791. onInit( callback ) {
  5792. this.onInitFunction = callback;
  5793. return this;
  5794. }
  5795. /**
  5796. * The method execute the compute for this node.
  5797. *
  5798. * @param {NodeFrame} frame - A reference to the current node frame.
  5799. */
  5800. updateBefore( { renderer } ) {
  5801. renderer.compute( this );
  5802. }
  5803. generate( builder ) {
  5804. const { shaderStage } = builder;
  5805. if ( shaderStage === 'compute' ) {
  5806. const snippet = this.computeNode.build( builder, 'void' );
  5807. if ( snippet !== '' ) {
  5808. builder.addLineFlowCode( snippet, this );
  5809. }
  5810. }
  5811. }
  5812. }
  5813. /**
  5814. * TSL function for creating a compute node.
  5815. *
  5816. * @function
  5817. * @param {Node} node - TODO
  5818. * @param {Number} count - TODO.
  5819. * @param {Array<Number>} [workgroupSize=[64]] - TODO.
  5820. * @returns {AtomicFunctionNode}
  5821. */
  5822. const compute = ( node, count, workgroupSize ) => nodeObject( new ComputeNode( nodeObject( node ), count, workgroupSize ) );
  5823. addMethodChaining( 'compute', compute );
  5824. /** @module CacheNode **/
  5825. /**
  5826. * This node can be used as a cache management component for another node.
  5827. * Caching is in general used by default in {@link NodeBuilder} but this node
  5828. * allows the usage of a shared parent cache during the build process.
  5829. *
  5830. * @augments Node
  5831. */
  5832. class CacheNode extends Node {
  5833. static get type() {
  5834. return 'CacheNode';
  5835. }
  5836. /**
  5837. * Constructs a new cache node.
  5838. *
  5839. * @param {Node} node - The node that should be cached.
  5840. * @param {Boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  5841. */
  5842. constructor( node, parent = true ) {
  5843. super();
  5844. /**
  5845. * The node that should be cached.
  5846. *
  5847. * @type {Node}
  5848. */
  5849. this.node = node;
  5850. /**
  5851. * Whether this node refers to a shared parent cache or not.
  5852. *
  5853. * @type {Boolean}
  5854. * @default true
  5855. */
  5856. this.parent = parent;
  5857. /**
  5858. * This flag can be used for type testing.
  5859. *
  5860. * @type {Boolean}
  5861. * @readonly
  5862. * @default true
  5863. */
  5864. this.isCacheNode = true;
  5865. }
  5866. getNodeType( builder ) {
  5867. const previousCache = builder.getCache();
  5868. const cache = builder.getCacheFromNode( this, this.parent );
  5869. builder.setCache( cache );
  5870. const nodeType = this.node.getNodeType( builder );
  5871. builder.setCache( previousCache );
  5872. return nodeType;
  5873. }
  5874. build( builder, ...params ) {
  5875. const previousCache = builder.getCache();
  5876. const cache = builder.getCacheFromNode( this, this.parent );
  5877. builder.setCache( cache );
  5878. const data = this.node.build( builder, ...params );
  5879. builder.setCache( previousCache );
  5880. return data;
  5881. }
  5882. }
  5883. /**
  5884. * TSL function for creating a cache node.
  5885. *
  5886. * @function
  5887. * @param {Node} node - The node that should be cached.
  5888. * @param {Boolean} parent - Whether this node refers to a shared parent cache or not.
  5889. * @returns {CacheNode}
  5890. */
  5891. const cache = ( node, parent ) => nodeObject( new CacheNode( nodeObject( node ), parent ) );
  5892. addMethodChaining( 'cache', cache );
  5893. /** @module BypassNode **/
  5894. /**
  5895. * The class generates the code of a given node but returns another node in the output.
  5896. * This can be used to call a method or node that does not return a value, i.e.
  5897. * type `void` on an input where returning a value is required. Example:
  5898. *
  5899. * ```js
  5900. * material.colorNode = myColor.bypass( runVoidFn() )
  5901. *```
  5902. *
  5903. * @augments Node
  5904. */
  5905. class BypassNode extends Node {
  5906. static get type() {
  5907. return 'BypassNode';
  5908. }
  5909. /**
  5910. * Constructs a new bypass node.
  5911. *
  5912. * @param {Node} outputNode - The output node.
  5913. * @param {Node} callNode - The call node.
  5914. */
  5915. constructor( outputNode, callNode ) {
  5916. super();
  5917. /**
  5918. * This flag can be used for type testing.
  5919. *
  5920. * @type {Boolean}
  5921. * @readonly
  5922. * @default true
  5923. */
  5924. this.isBypassNode = true;
  5925. /**
  5926. * The output node.
  5927. *
  5928. * @type {Node}
  5929. */
  5930. this.outputNode = outputNode;
  5931. /**
  5932. * The call node.
  5933. *
  5934. * @type {Node}
  5935. */
  5936. this.callNode = callNode;
  5937. }
  5938. getNodeType( builder ) {
  5939. return this.outputNode.getNodeType( builder );
  5940. }
  5941. generate( builder ) {
  5942. const snippet = this.callNode.build( builder, 'void' );
  5943. if ( snippet !== '' ) {
  5944. builder.addLineFlowCode( snippet, this );
  5945. }
  5946. return this.outputNode.build( builder );
  5947. }
  5948. }
  5949. /**
  5950. * TSL function for creating a bypass node.
  5951. *
  5952. * @function
  5953. * @param {Node} outputNode - The output node.
  5954. * @param {Node} callNode - The call node.
  5955. * @returns {BypassNode}
  5956. */
  5957. const bypass = /*@__PURE__*/ nodeProxy( BypassNode );
  5958. addMethodChaining( 'bypass', bypass );
  5959. /** @module RemapNode **/
  5960. /**
  5961. * This node allows to remap a node value from one range into another. E.g a value of
  5962. * `0.4` in the range `[ 0.3, 0.5 ]` should be remapped into the normalized range `[ 0, 1 ]`.
  5963. * `RemapNode` takes care of that and converts the original value of `0.4` to `0.5`.
  5964. *
  5965. * @augments Node
  5966. */
  5967. class RemapNode extends Node {
  5968. static get type() {
  5969. return 'RemapNode';
  5970. }
  5971. /**
  5972. * Constructs a new remap node.
  5973. *
  5974. * @param {Node} node - The node that should be remapped.
  5975. * @param {Node} inLowNode - The source or current lower bound of the range.
  5976. * @param {Node} inHighNode - The source or current upper bound of the range.
  5977. * @param {Node} [outLowNode=float(0)] - The target lower bound of the range.
  5978. * @param {Node} [outHighNode=float(1)] - The target upper bound of the range.
  5979. */
  5980. constructor( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) {
  5981. super();
  5982. /**
  5983. * The node that should be remapped.
  5984. *
  5985. * @type {Node}
  5986. */
  5987. this.node = node;
  5988. /**
  5989. * The source or current lower bound of the range.
  5990. *
  5991. * @type {Node}
  5992. */
  5993. this.inLowNode = inLowNode;
  5994. /**
  5995. * The source or current upper bound of the range.
  5996. *
  5997. * @type {Node}
  5998. */
  5999. this.inHighNode = inHighNode;
  6000. /**
  6001. * The target lower bound of the range.
  6002. *
  6003. * @type {Node}
  6004. * @default float(0)
  6005. */
  6006. this.outLowNode = outLowNode;
  6007. /**
  6008. * The target upper bound of the range.
  6009. *
  6010. * @type {Node}
  6011. * @default float(1)
  6012. */
  6013. this.outHighNode = outHighNode;
  6014. /**
  6015. * Whether the node value should be clamped before
  6016. * remapping it to the target range.
  6017. *
  6018. * @type {Boolean}
  6019. * @default true
  6020. */
  6021. this.doClamp = true;
  6022. }
  6023. setup() {
  6024. const { node, inLowNode, inHighNode, outLowNode, outHighNode, doClamp } = this;
  6025. let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) );
  6026. if ( doClamp === true ) t = t.clamp();
  6027. return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode );
  6028. }
  6029. }
  6030. /**
  6031. * TSL function for creating a remap node.
  6032. *
  6033. * @function
  6034. * @param {Node} node - The node that should be remapped.
  6035. * @param {Node} inLowNode - The source or current lower bound of the range.
  6036. * @param {Node} inHighNode - The source or current upper bound of the range.
  6037. * @param {Node} [outLowNode=float(0)] - The target lower bound of the range.
  6038. * @param {Node} [outHighNode=float(1)] - The target upper bound of the range.
  6039. * @returns {RemapNode}
  6040. */
  6041. const remap = /*@__PURE__*/ nodeProxy( RemapNode, null, null, { doClamp: false } );
  6042. /**
  6043. * TSL function for creating a remap node, but with enabled clamping.
  6044. *
  6045. * @function
  6046. * @param {Node} node - The node that should be remapped.
  6047. * @param {Node} inLowNode - The source or current lower bound of the range.
  6048. * @param {Node} inHighNode - The source or current upper bound of the range.
  6049. * @param {Node} [outLowNode=float(0)] - The target lower bound of the range.
  6050. * @param {Node} [outHighNode=float(1)] - The target upper bound of the range.
  6051. * @returns {RemapNode}
  6052. */
  6053. const remapClamp = /*@__PURE__*/ nodeProxy( RemapNode );
  6054. addMethodChaining( 'remap', remap );
  6055. addMethodChaining( 'remapClamp', remapClamp );
  6056. /** @module ExpressionNode **/
  6057. /**
  6058. * This class can be used to implement basic expressions in shader code.
  6059. * Basic examples for that are `return`, `continue` or `discard` statements.
  6060. *
  6061. * @augments Node
  6062. */
  6063. class ExpressionNode extends Node {
  6064. static get type() {
  6065. return 'ExpressionNode';
  6066. }
  6067. /**
  6068. * Constructs a new expression node.
  6069. *
  6070. * @param {String} [snippet=''] - The native code snippet.
  6071. * @param {String} [nodeType='void'] - The node type.
  6072. */
  6073. constructor( snippet = '', nodeType = 'void' ) {
  6074. super( nodeType );
  6075. /**
  6076. * The native code snippet.
  6077. *
  6078. * @type {String}
  6079. * @default ''
  6080. */
  6081. this.snippet = snippet;
  6082. }
  6083. generate( builder, output ) {
  6084. const type = this.getNodeType( builder );
  6085. const snippet = this.snippet;
  6086. if ( type === 'void' ) {
  6087. builder.addLineFlowCode( snippet, this );
  6088. } else {
  6089. return builder.format( `( ${ snippet } )`, type, output );
  6090. }
  6091. }
  6092. }
  6093. /**
  6094. * TSL function for creating an expression node.
  6095. *
  6096. * @function
  6097. * @param {String} [snippet=''] - The native code snippet.
  6098. * @param {String} [nodeType='void'] - The node type.
  6099. * @returns {ExpressionNode}
  6100. */
  6101. const expression = /*@__PURE__*/ nodeProxy( ExpressionNode );
  6102. /** @module Discard **/
  6103. /**
  6104. * Represents a `discard` shader operation in TSL.
  6105. *
  6106. * @method
  6107. * @param {ConditionalNode?} conditional - An optional conditional node. It allows to decide whether the discard should be executed or not.
  6108. * @return {Node} The `discard` expression.
  6109. */
  6110. const Discard = ( conditional ) => ( conditional ? select( conditional, expression( 'discard' ) ) : expression( 'discard' ) ).append();
  6111. /**
  6112. * Represents a `return` shader operation in TSL.
  6113. *
  6114. * @method
  6115. * @return {ExpressionNode} The `return` expression.
  6116. */
  6117. const Return = () => expression( 'return' ).append();
  6118. addMethodChaining( 'discard', Discard );
  6119. /** @module RenderOutputNode **/
  6120. /**
  6121. * Normally, tone mapping and color conversion happens automatically
  6122. * before outputting pixel too the default (screen) framebuffer. In certain
  6123. * post processing setups this happens to late because certain effects
  6124. * require e.g. sRGB input. For such scenarios, `RenderOutputNode` can be used
  6125. * to apply tone mapping and color space conversion at an arbitrary point
  6126. * in the effect chain.
  6127. *
  6128. * When applying tone mapping and color space conversion manually with this node,
  6129. * you have to set {@link PostProcessing#outputColorTransform} to `false`.
  6130. *
  6131. * ```js
  6132. * const postProcessing = new PostProcessing( renderer );
  6133. * postProcessing.outputColorTransform = false;
  6134. *
  6135. * const scenePass = pass( scene, camera );
  6136. * const outputPass = renderOutput( scenePass );
  6137. *
  6138. * postProcessing.outputNode = outputPass;
  6139. * ```
  6140. *
  6141. * @augments TempNode
  6142. */
  6143. class RenderOutputNode extends TempNode {
  6144. static get type() {
  6145. return 'RenderOutputNode';
  6146. }
  6147. /**
  6148. * Constructs a new render output node.
  6149. *
  6150. * @param {Node} colorNode - The color node to process.
  6151. * @param {Number} toneMapping - The tone mapping type.
  6152. * @param {String} outputColorSpace - The output color space.
  6153. */
  6154. constructor( colorNode, toneMapping, outputColorSpace ) {
  6155. super( 'vec4' );
  6156. /**
  6157. * The color node to process.
  6158. *
  6159. * @type {Node}
  6160. */
  6161. this.colorNode = colorNode;
  6162. /**
  6163. * The tone mapping type.
  6164. *
  6165. * @type {Number?}
  6166. */
  6167. this.toneMapping = toneMapping;
  6168. /**
  6169. * The output color space.
  6170. *
  6171. * @type {String?}
  6172. */
  6173. this.outputColorSpace = outputColorSpace;
  6174. /**
  6175. * This flag can be used for type testing.
  6176. *
  6177. * @type {Boolean}
  6178. * @readonly
  6179. * @default true
  6180. */
  6181. this.isRenderOutputNode = true;
  6182. }
  6183. setup( { context } ) {
  6184. let outputNode = this.colorNode || context.color;
  6185. // tone mapping
  6186. const toneMapping = ( this.toneMapping !== null ? this.toneMapping : context.toneMapping ) || NoToneMapping;
  6187. const outputColorSpace = ( this.outputColorSpace !== null ? this.outputColorSpace : context.outputColorSpace ) || NoColorSpace;
  6188. if ( toneMapping !== NoToneMapping ) {
  6189. outputNode = outputNode.toneMapping( toneMapping );
  6190. }
  6191. // working to output color space
  6192. if ( outputColorSpace !== NoColorSpace && outputColorSpace !== ColorManagement.workingColorSpace ) {
  6193. outputNode = outputNode.workingToColorSpace( outputColorSpace );
  6194. }
  6195. return outputNode;
  6196. }
  6197. }
  6198. /**
  6199. * TSL function for creating a posterize node.
  6200. *
  6201. * @function
  6202. * @param {Node} color - The color node to process.
  6203. * @param {Number?} [toneMapping=null] - The tone mapping type.
  6204. * @param {String?} [outputColorSpace=null] - The output color space.
  6205. * @returns {RenderOutputNode}
  6206. */
  6207. const renderOutput = ( color, toneMapping = null, outputColorSpace = null ) => nodeObject( new RenderOutputNode( nodeObject( color ), toneMapping, outputColorSpace ) );
  6208. addMethodChaining( 'renderOutput', renderOutput );
  6209. // Non-PURE exports list, side-effects are required here.
  6210. // TSL Base Syntax
  6211. function addNodeElement( name/*, nodeElement*/ ) {
  6212. console.warn( 'THREE.TSLBase: AddNodeElement has been removed in favor of tree-shaking. Trying add', name );
  6213. }
  6214. /** @module AttributeNode **/
  6215. /**
  6216. * Base class for representing shader attributes as nodes.
  6217. *
  6218. * @augments Node
  6219. */
  6220. class AttributeNode extends Node {
  6221. static get type() {
  6222. return 'AttributeNode';
  6223. }
  6224. /**
  6225. * Constructs a new attribute node.
  6226. *
  6227. * @param {String} attributeName - The name of the attribute.
  6228. * @param {String?} nodeType - The node type.
  6229. */
  6230. constructor( attributeName, nodeType = null ) {
  6231. super( nodeType );
  6232. /**
  6233. * `AttributeNode` sets this property to `true` by default.
  6234. *
  6235. * @type {Boolean}
  6236. * @default true
  6237. */
  6238. this.global = true;
  6239. this._attributeName = attributeName;
  6240. }
  6241. getHash( builder ) {
  6242. return this.getAttributeName( builder );
  6243. }
  6244. getNodeType( builder ) {
  6245. let nodeType = this.nodeType;
  6246. if ( nodeType === null ) {
  6247. const attributeName = this.getAttributeName( builder );
  6248. if ( builder.hasGeometryAttribute( attributeName ) ) {
  6249. const attribute = builder.geometry.getAttribute( attributeName );
  6250. nodeType = builder.getTypeFromAttribute( attribute );
  6251. } else {
  6252. nodeType = 'float';
  6253. }
  6254. }
  6255. return nodeType;
  6256. }
  6257. /**
  6258. * Sets the attribute name to the given value. The method can be
  6259. * overwritten in derived classes if the final name must be computed
  6260. * analytically.
  6261. *
  6262. * @param {String} attributeName - The name of the attribute.
  6263. * @return {AttributeNode} A reference to this node.
  6264. */
  6265. setAttributeName( attributeName ) {
  6266. this._attributeName = attributeName;
  6267. return this;
  6268. }
  6269. /**
  6270. * Returns the attribute name of this node. The method can be
  6271. * overwritten in derived classes if the final name must be computed
  6272. * analytically.
  6273. *
  6274. * @param {NodeBuilder} builder - The current node builder.
  6275. * @return {String} The attribute name.
  6276. */
  6277. getAttributeName( /*builder*/ ) {
  6278. return this._attributeName;
  6279. }
  6280. generate( builder ) {
  6281. const attributeName = this.getAttributeName( builder );
  6282. const nodeType = this.getNodeType( builder );
  6283. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  6284. if ( geometryAttribute === true ) {
  6285. const attribute = builder.geometry.getAttribute( attributeName );
  6286. const attributeType = builder.getTypeFromAttribute( attribute );
  6287. const nodeAttribute = builder.getAttribute( attributeName, attributeType );
  6288. if ( builder.shaderStage === 'vertex' ) {
  6289. return builder.format( nodeAttribute.name, attributeType, nodeType );
  6290. } else {
  6291. const nodeVarying = varying( this );
  6292. return nodeVarying.build( builder, nodeType );
  6293. }
  6294. } else {
  6295. console.warn( `AttributeNode: Vertex attribute "${ attributeName }" not found on geometry.` );
  6296. return builder.generateConst( nodeType );
  6297. }
  6298. }
  6299. serialize( data ) {
  6300. super.serialize( data );
  6301. data.global = this.global;
  6302. data._attributeName = this._attributeName;
  6303. }
  6304. deserialize( data ) {
  6305. super.deserialize( data );
  6306. this.global = data.global;
  6307. this._attributeName = data._attributeName;
  6308. }
  6309. }
  6310. /**
  6311. * TSL function for creating an attribute node.
  6312. *
  6313. * @function
  6314. * @param {String} name - The name of the attribute.
  6315. * @param {String?} nodeType - The node type.
  6316. * @returns {AttributeNode}
  6317. */
  6318. const attribute = ( name, nodeType ) => nodeObject( new AttributeNode( name, nodeType ) );
  6319. /** @module UV **/
  6320. /**
  6321. * TSL function for creating an uv attribute node with the given index.
  6322. *
  6323. * @function
  6324. * @param {Number} [index=0] - The uv index.
  6325. * @return {AttributeNode<vec2>} The uv attribute node.
  6326. */
  6327. const uv = ( index = 0 ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' );
  6328. /** @module TextureSizeNode **/
  6329. /**
  6330. * A node that represents the dimensions of a texture. The texture size is
  6331. * retrieved in the shader via built-in shader functions like `textureDimensions()`
  6332. * or `textureSize()`.
  6333. *
  6334. * @augments Node
  6335. */
  6336. class TextureSizeNode extends Node {
  6337. static get type() {
  6338. return 'TextureSizeNode';
  6339. }
  6340. /**
  6341. * Constructs a new texture size node.
  6342. *
  6343. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  6344. * @param {Node<int>?} [levelNode=null] - A level node which defines the requested mip.
  6345. */
  6346. constructor( textureNode, levelNode = null ) {
  6347. super( 'uvec2' );
  6348. /**
  6349. * This flag can be used for type testing.
  6350. *
  6351. * @type {Boolean}
  6352. * @readonly
  6353. * @default true
  6354. */
  6355. this.isTextureSizeNode = true;
  6356. /**
  6357. * A texture node which size should be retrieved.
  6358. *
  6359. * @type {TextureNode}
  6360. */
  6361. this.textureNode = textureNode;
  6362. /**
  6363. * A level node which defines the requested mip.
  6364. *
  6365. * @type {Node<int>}
  6366. * @default null
  6367. */
  6368. this.levelNode = levelNode;
  6369. }
  6370. generate( builder, output ) {
  6371. const textureProperty = this.textureNode.build( builder, 'property' );
  6372. const level = this.levelNode === null ? '0' : this.levelNode.build( builder, 'int' );
  6373. return builder.format( `${ builder.getMethod( 'textureDimensions' ) }( ${ textureProperty }, ${ level } )`, this.getNodeType( builder ), output );
  6374. }
  6375. }
  6376. /**
  6377. * TSL function for creating a texture size node.
  6378. *
  6379. * @function
  6380. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  6381. * @param {Node<int>?} [levelNode=null] - A level node which defines the requested mip.
  6382. * @returns {TextureSizeNode}
  6383. */
  6384. const textureSize = /*@__PURE__*/ nodeProxy( TextureSizeNode );
  6385. /** @module MatcapUVNode **/
  6386. /**
  6387. * A special type of uniform node that computes the
  6388. * maximum mipmap level for a given texture node.
  6389. *
  6390. * ```js
  6391. * const level = maxMipLevel( textureNode );
  6392. * ```
  6393. *
  6394. * @augments module:UniformNode~UniformNode
  6395. */
  6396. class MaxMipLevelNode extends UniformNode {
  6397. static get type() {
  6398. return 'MaxMipLevelNode';
  6399. }
  6400. /**
  6401. * Constructs a new max mip level node.
  6402. *
  6403. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  6404. */
  6405. constructor( textureNode ) {
  6406. super( 0 );
  6407. /**
  6408. * The texture node to compute the max mip level for.
  6409. *
  6410. * @private
  6411. * @type {TextureNode}
  6412. */
  6413. this._textureNode = textureNode;
  6414. /**
  6415. * The `updateType` is set to `NodeUpdateType.FRAME` since the node updates
  6416. * the texture once per frame in its {@link MaxMipLevelNode#update} method.
  6417. *
  6418. * @type {String}
  6419. * @default 'frame'
  6420. */
  6421. this.updateType = NodeUpdateType.FRAME;
  6422. }
  6423. /**
  6424. * The texture node to compute the max mip level for.
  6425. *
  6426. * @readonly
  6427. * @type {TextureNode}
  6428. */
  6429. get textureNode() {
  6430. return this._textureNode;
  6431. }
  6432. /**
  6433. * The texture.
  6434. *
  6435. * @readonly
  6436. * @type {Texture}
  6437. */
  6438. get texture() {
  6439. return this._textureNode.value;
  6440. }
  6441. update() {
  6442. const texture = this.texture;
  6443. const images = texture.images;
  6444. const image = ( images && images.length > 0 ) ? ( ( images[ 0 ] && images[ 0 ].image ) || images[ 0 ] ) : texture.image;
  6445. if ( image && image.width !== undefined ) {
  6446. const { width, height } = image;
  6447. this.value = Math.log2( Math.max( width, height ) );
  6448. }
  6449. }
  6450. }
  6451. /**
  6452. * TSL function for creating a max mip level node.
  6453. *
  6454. * @function
  6455. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  6456. * @returns {MaxMipLevelNode}
  6457. */
  6458. const maxMipLevel = /*@__PURE__*/ nodeProxy( MaxMipLevelNode );
  6459. /** @module TextureNode **/
  6460. /**
  6461. * This type of uniform node represents a 2D texture.
  6462. *
  6463. * @augments module:UniformNode~UniformNode
  6464. */
  6465. class TextureNode extends UniformNode {
  6466. static get type() {
  6467. return 'TextureNode';
  6468. }
  6469. /**
  6470. * Constructs a new texture node.
  6471. *
  6472. * @param {Texture} value - The texture.
  6473. * @param {Node<vec2|vec3>?} [uvNode=null] - The uv node.
  6474. * @param {Node<int>?} [levelNode=null] - The level node.
  6475. * @param {Node<float>?} [biasNode=null] - The bias node.
  6476. */
  6477. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  6478. super( value );
  6479. /**
  6480. * This flag can be used for type testing.
  6481. *
  6482. * @type {Boolean}
  6483. * @readonly
  6484. * @default true
  6485. */
  6486. this.isTextureNode = true;
  6487. /**
  6488. * Represents the texture coordinates.
  6489. *
  6490. * @type {Node<vec2|vec3>?}
  6491. * @default null
  6492. */
  6493. this.uvNode = uvNode;
  6494. /**
  6495. * Represents the mip level that should be selected.
  6496. *
  6497. * @type {Node<int>?}
  6498. * @default null
  6499. */
  6500. this.levelNode = levelNode;
  6501. /**
  6502. * Represents the bias to be applied during level-of-detail computation.
  6503. *
  6504. * @type {Node<float>?}
  6505. * @default null
  6506. */
  6507. this.biasNode = biasNode;
  6508. /**
  6509. * Represents a reference value a texture sample is compared to.
  6510. *
  6511. * @type {Node<float>?}
  6512. * @default null
  6513. */
  6514. this.compareNode = null;
  6515. /**
  6516. * When using texture arrays, the depth node defines the layer to select.
  6517. *
  6518. * @type {Node<int>?}
  6519. * @default null
  6520. */
  6521. this.depthNode = null;
  6522. /**
  6523. * When defined, a texture is sampled using explicit gradients.
  6524. *
  6525. * @type {Array<Node<vec2>>?}
  6526. * @default null
  6527. */
  6528. this.gradNode = null;
  6529. /**
  6530. * Whether texture values should be sampled or fetched.
  6531. *
  6532. * @type {Boolean}
  6533. * @default true
  6534. */
  6535. this.sampler = true;
  6536. /**
  6537. * Whether the uv transformation matrix should be
  6538. * automatically updated or not. Use `setUpdateMatrix()`
  6539. * if you want to change the value of the property.
  6540. *
  6541. * @type {Boolean}
  6542. * @default false
  6543. */
  6544. this.updateMatrix = false;
  6545. /**
  6546. * By default the `update()` method is not executed. `setUpdateMatrix()`
  6547. * sets the value to `frame` when the uv transformation matrix should
  6548. * automatically be updated.
  6549. *
  6550. * @type {String}
  6551. * @default 'none'
  6552. */
  6553. this.updateType = NodeUpdateType.NONE;
  6554. /**
  6555. * The reference node.
  6556. *
  6557. * @type {Node?}
  6558. * @default null
  6559. */
  6560. this.referenceNode = null;
  6561. /**
  6562. * The texture value is stored in a private property.
  6563. *
  6564. * @private
  6565. * @type {Texture}
  6566. */
  6567. this._value = value;
  6568. /**
  6569. * The uniform node that represents the uv transformation matrix.
  6570. *
  6571. * @private
  6572. * @type {UniformNode<mat3>?}
  6573. */
  6574. this._matrixUniform = null;
  6575. this.setUpdateMatrix( uvNode === null );
  6576. }
  6577. set value( value ) {
  6578. if ( this.referenceNode ) {
  6579. this.referenceNode.value = value;
  6580. } else {
  6581. this._value = value;
  6582. }
  6583. }
  6584. /**
  6585. * The texture value.
  6586. *
  6587. * @type {Texture}
  6588. */
  6589. get value() {
  6590. return this.referenceNode ? this.referenceNode.value : this._value;
  6591. }
  6592. /**
  6593. * Overwritten since the uniform hash is defined by the texture's UUID.
  6594. *
  6595. * @param {NodeBuilder} builder - The current node builder.
  6596. * @return {String} The uniform hash.
  6597. */
  6598. getUniformHash( /*builder*/ ) {
  6599. return this.value.uuid;
  6600. }
  6601. /**
  6602. * Overwritten since the node type is inferred from the texture type.
  6603. *
  6604. * @param {NodeBuilder} builder - The current node builder.
  6605. * @return {String} The node type.
  6606. */
  6607. getNodeType( /*builder*/ ) {
  6608. if ( this.value.isDepthTexture === true ) return 'float';
  6609. if ( this.value.type === UnsignedIntType ) {
  6610. return 'uvec4';
  6611. } else if ( this.value.type === IntType ) {
  6612. return 'ivec4';
  6613. }
  6614. return 'vec4';
  6615. }
  6616. /**
  6617. * Overwrites the default implementation to return a fixed value `'texture'`.
  6618. *
  6619. * @param {NodeBuilder} builder - The current node builder.
  6620. * @return {String} The input type.
  6621. */
  6622. getInputType( /*builder*/ ) {
  6623. return 'texture';
  6624. }
  6625. /**
  6626. * Returns a default uvs based on the current texture's channel.
  6627. *
  6628. * @return {AttributeNode<vec2>} The default uvs.
  6629. */
  6630. getDefaultUV() {
  6631. return uv( this.value.channel );
  6632. }
  6633. /**
  6634. * Overwritten to always return the texture reference of the node.
  6635. *
  6636. * @param {Any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  6637. * @return {Texture} The texture reference.
  6638. */
  6639. updateReference( /*state*/ ) {
  6640. return this.value;
  6641. }
  6642. /**
  6643. * Transforms the given uv node with the texture transformation matrix.
  6644. *
  6645. * @param {Node} uvNode - The uv node to transform.
  6646. * @return {Node} The transformed uv node.
  6647. */
  6648. getTransformedUV( uvNode ) {
  6649. if ( this._matrixUniform === null ) this._matrixUniform = uniform( this.value.matrix );
  6650. return this._matrixUniform.mul( vec3( uvNode, 1 ) ).xy;
  6651. }
  6652. /**
  6653. * Defines whether the uv transformation matrix should automatically be updated or not.
  6654. *
  6655. * @param {Boolean} value - The update toggle.
  6656. * @return {TextureNode} A reference to this node.
  6657. */
  6658. setUpdateMatrix( value ) {
  6659. this.updateMatrix = value;
  6660. this.updateType = value ? NodeUpdateType.RENDER : NodeUpdateType.NONE;
  6661. return this;
  6662. }
  6663. /**
  6664. * Setups the uv node. Depending on the backend as well as texture's image and type, it might be necessary
  6665. * to modify the uv node for correct sampling.
  6666. *
  6667. * @param {NodeBuilder} builder - The current node builder.
  6668. * @param {Node} uvNode - The uv node to setup.
  6669. * @return {Node} The updated uv node.
  6670. */
  6671. setupUV( builder, uvNode ) {
  6672. const texture = this.value;
  6673. if ( builder.isFlipY() && ( ( texture.image instanceof ImageBitmap && texture.flipY === true ) || texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true || texture.isDepthTexture === true ) ) {
  6674. if ( this.sampler ) {
  6675. uvNode = uvNode.flipY();
  6676. } else {
  6677. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  6678. }
  6679. }
  6680. return uvNode;
  6681. }
  6682. /**
  6683. * Setups texture node by preparing the internal nodes for code generation.
  6684. *
  6685. * @param {NodeBuilder} builder - The current node builder.
  6686. */
  6687. setup( builder ) {
  6688. const properties = builder.getNodeProperties( this );
  6689. properties.referenceNode = this.referenceNode;
  6690. //
  6691. const texture = this.value;
  6692. if ( ! texture || texture.isTexture !== true ) {
  6693. throw new Error( 'THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().' );
  6694. }
  6695. //
  6696. let uvNode = this.uvNode;
  6697. if ( ( uvNode === null || builder.context.forceUVContext === true ) && builder.context.getUV ) {
  6698. uvNode = builder.context.getUV( this );
  6699. }
  6700. if ( ! uvNode ) uvNode = this.getDefaultUV();
  6701. if ( this.updateMatrix === true ) {
  6702. uvNode = this.getTransformedUV( uvNode );
  6703. }
  6704. uvNode = this.setupUV( builder, uvNode );
  6705. //
  6706. let levelNode = this.levelNode;
  6707. if ( levelNode === null && builder.context.getTextureLevel ) {
  6708. levelNode = builder.context.getTextureLevel( this );
  6709. }
  6710. //
  6711. properties.uvNode = uvNode;
  6712. properties.levelNode = levelNode;
  6713. properties.biasNode = this.biasNode;
  6714. properties.compareNode = this.compareNode;
  6715. properties.gradNode = this.gradNode;
  6716. properties.depthNode = this.depthNode;
  6717. }
  6718. /**
  6719. * Generates the uv code snippet.
  6720. *
  6721. * @param {NodeBuilder} builder - The current node builder.
  6722. * @param {Node} uvNode - The uv node to generate code for.
  6723. * @return {String} The generated code snippet.
  6724. */
  6725. generateUV( builder, uvNode ) {
  6726. return uvNode.build( builder, this.sampler === true ? 'vec2' : 'ivec2' );
  6727. }
  6728. /**
  6729. * Generates the snippet for the texture sampling.
  6730. *
  6731. * @param {NodeBuilder} builder - The current node builder.
  6732. * @param {String} textureProperty - The texture property.
  6733. * @param {String} uvSnippet - The uv snippet.
  6734. * @param {String?} levelSnippet - The level snippet.
  6735. * @param {String?} biasSnippet - The bias snippet.
  6736. * @param {String?} depthSnippet - The depth snippet.
  6737. * @param {String?} compareSnippet - The compare snippet.
  6738. * @param {Array<String>?} gradSnippet - The grad snippet.
  6739. * @return {String} The generated code snippet.
  6740. */
  6741. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet ) {
  6742. const texture = this.value;
  6743. let snippet;
  6744. if ( levelSnippet ) {
  6745. snippet = builder.generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet );
  6746. } else if ( biasSnippet ) {
  6747. snippet = builder.generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet );
  6748. } else if ( gradSnippet ) {
  6749. snippet = builder.generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet );
  6750. } else if ( compareSnippet ) {
  6751. snippet = builder.generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet );
  6752. } else if ( this.sampler === false ) {
  6753. snippet = builder.generateTextureLoad( texture, textureProperty, uvSnippet, depthSnippet );
  6754. } else {
  6755. snippet = builder.generateTexture( texture, textureProperty, uvSnippet, depthSnippet );
  6756. }
  6757. return snippet;
  6758. }
  6759. /**
  6760. * Generates the code snippet of the texture node.
  6761. *
  6762. * @param {NodeBuilder} builder - The current node builder.
  6763. * @param {String} output - The current output.
  6764. * @return {String} The generated code snippet.
  6765. */
  6766. generate( builder, output ) {
  6767. const texture = this.value;
  6768. const properties = builder.getNodeProperties( this );
  6769. const textureProperty = super.generate( builder, 'property' );
  6770. if ( output === 'sampler' ) {
  6771. return textureProperty + '_sampler';
  6772. } else if ( builder.isReference( output ) ) {
  6773. return textureProperty;
  6774. } else {
  6775. const nodeData = builder.getDataFromNode( this );
  6776. let propertyName = nodeData.propertyName;
  6777. if ( propertyName === undefined ) {
  6778. const { uvNode, levelNode, biasNode, compareNode, depthNode, gradNode } = properties;
  6779. const uvSnippet = this.generateUV( builder, uvNode );
  6780. const levelSnippet = levelNode ? levelNode.build( builder, 'float' ) : null;
  6781. const biasSnippet = biasNode ? biasNode.build( builder, 'float' ) : null;
  6782. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  6783. const compareSnippet = compareNode ? compareNode.build( builder, 'float' ) : null;
  6784. const gradSnippet = gradNode ? [ gradNode[ 0 ].build( builder, 'vec2' ), gradNode[ 1 ].build( builder, 'vec2' ) ] : null;
  6785. const nodeVar = builder.getVarFromNode( this );
  6786. propertyName = builder.getPropertyName( nodeVar );
  6787. const snippet = this.generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet );
  6788. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  6789. nodeData.snippet = snippet;
  6790. nodeData.propertyName = propertyName;
  6791. }
  6792. let snippet = propertyName;
  6793. const nodeType = this.getNodeType( builder );
  6794. if ( builder.needsToWorkingColorSpace( texture ) ) {
  6795. snippet = colorSpaceToWorking( expression( snippet, nodeType ), texture.colorSpace ).setup( builder ).build( builder, nodeType );
  6796. }
  6797. return builder.format( snippet, nodeType, output );
  6798. }
  6799. }
  6800. /**
  6801. * Sets the sampler value.
  6802. *
  6803. * @param {Boolean} value - The sampler value to set.
  6804. * @return {TextureNode} A reference to this texture node.
  6805. */
  6806. setSampler( value ) {
  6807. this.sampler = value;
  6808. return this;
  6809. }
  6810. /**
  6811. * Returns the sampler value.
  6812. *
  6813. * @return {Boolean} The sampler value.
  6814. */
  6815. getSampler() {
  6816. return this.sampler;
  6817. }
  6818. // @TODO: Move to TSL
  6819. /**
  6820. * @function
  6821. * @deprecated since r172. Use {@link TextureNode#sample} instead.
  6822. *
  6823. * @param {Node} uvNode - The uv node.
  6824. * @return {TextureNode} A texture node representing the texture sample.
  6825. */
  6826. uv( uvNode ) { // @deprecated, r172
  6827. console.warn( 'THREE.TextureNode: .uv() has been renamed. Use .sample() instead.' );
  6828. return this.sample( uvNode );
  6829. }
  6830. /**
  6831. * Samples the texture with the given uv node.
  6832. *
  6833. * @param {Node} uvNode - The uv node.
  6834. * @return {TextureNode} A texture node representing the texture sample.
  6835. */
  6836. sample( uvNode ) {
  6837. const textureNode = this.clone();
  6838. textureNode.uvNode = nodeObject( uvNode );
  6839. textureNode.referenceNode = this.getSelf();
  6840. return nodeObject( textureNode );
  6841. }
  6842. /**
  6843. * Samples a blurred version of the texture by defining an internal bias.
  6844. *
  6845. * @param {Node<float>} amountNode - How blurred the texture should be.
  6846. * @return {TextureNode} A texture node representing the texture sample.
  6847. */
  6848. blur( amountNode ) {
  6849. const textureNode = this.clone();
  6850. textureNode.biasNode = nodeObject( amountNode ).mul( maxMipLevel( textureNode ) );
  6851. textureNode.referenceNode = this.getSelf();
  6852. return nodeObject( textureNode );
  6853. }
  6854. /**
  6855. * Samples a specific mip of the texture.
  6856. *
  6857. * @param {Node<int>} levelNode - The mip level to sample.
  6858. * @return {TextureNode} A texture node representing the texture sample.
  6859. */
  6860. level( levelNode ) {
  6861. const textureNode = this.clone();
  6862. textureNode.levelNode = nodeObject( levelNode );
  6863. textureNode.referenceNode = this.getSelf();
  6864. return nodeObject( textureNode );
  6865. }
  6866. /**
  6867. * Returns the texture size of the requested level.
  6868. *
  6869. * @param {Node<int>} levelNode - The level to compute the size for.
  6870. * @return {TextureSizeNode} The texture size.
  6871. */
  6872. size( levelNode ) {
  6873. return textureSize( this, levelNode );
  6874. }
  6875. /**
  6876. * Samples the texture with the given bias.
  6877. *
  6878. * @param {Node<float>} biasNode - The bias node.
  6879. * @return {TextureNode} A texture node representing the texture sample.
  6880. */
  6881. bias( biasNode ) {
  6882. const textureNode = this.clone();
  6883. textureNode.biasNode = nodeObject( biasNode );
  6884. textureNode.referenceNode = this.getSelf();
  6885. return nodeObject( textureNode );
  6886. }
  6887. /**
  6888. * Samples the texture by executing a compare operation.
  6889. *
  6890. * @param {Node<float>} compareNode - The node that defines the compare value.
  6891. * @return {TextureNode} A texture node representing the texture sample.
  6892. */
  6893. compare( compareNode ) {
  6894. const textureNode = this.clone();
  6895. textureNode.compareNode = nodeObject( compareNode );
  6896. textureNode.referenceNode = this.getSelf();
  6897. return nodeObject( textureNode );
  6898. }
  6899. /**
  6900. * Samples the texture using an explicit gradient.
  6901. *
  6902. * @param {Node<vec2>} gradNodeX - The gradX node.
  6903. * @param {Node<vec2>} gradNodeY - The gradY node.
  6904. * @return {TextureNode} A texture node representing the texture sample.
  6905. */
  6906. grad( gradNodeX, gradNodeY ) {
  6907. const textureNode = this.clone();
  6908. textureNode.gradNode = [ nodeObject( gradNodeX ), nodeObject( gradNodeY ) ];
  6909. textureNode.referenceNode = this.getSelf();
  6910. return nodeObject( textureNode );
  6911. }
  6912. /**
  6913. * Samples the texture by defining a depth node.
  6914. *
  6915. * @param {Node<int>} depthNode - The depth node.
  6916. * @return {TextureNode} A texture node representing the texture sample.
  6917. */
  6918. depth( depthNode ) {
  6919. const textureNode = this.clone();
  6920. textureNode.depthNode = nodeObject( depthNode );
  6921. textureNode.referenceNode = this.getSelf();
  6922. return nodeObject( textureNode );
  6923. }
  6924. // --
  6925. serialize( data ) {
  6926. super.serialize( data );
  6927. data.value = this.value.toJSON( data.meta ).uuid;
  6928. data.sampler = this.sampler;
  6929. data.updateMatrix = this.updateMatrix;
  6930. data.updateType = this.updateType;
  6931. }
  6932. deserialize( data ) {
  6933. super.deserialize( data );
  6934. this.value = data.meta.textures[ data.value ];
  6935. this.sampler = data.sampler;
  6936. this.updateMatrix = data.updateMatrix;
  6937. this.updateType = data.updateType;
  6938. }
  6939. /**
  6940. * The update is used to implement the update of the uv transformation matrix.
  6941. */
  6942. update() {
  6943. const texture = this.value;
  6944. const matrixUniform = this._matrixUniform;
  6945. if ( matrixUniform !== null ) matrixUniform.value = texture.matrix;
  6946. if ( texture.matrixAutoUpdate === true ) {
  6947. texture.updateMatrix();
  6948. }
  6949. }
  6950. /**
  6951. * Clones the texture node.
  6952. *
  6953. * @return {TextureNode} The cloned texture node.
  6954. */
  6955. clone() {
  6956. const newNode = new this.constructor( this.value, this.uvNode, this.levelNode, this.biasNode );
  6957. newNode.sampler = this.sampler;
  6958. return newNode;
  6959. }
  6960. }
  6961. /**
  6962. * TSL function for creating a texture node.
  6963. *
  6964. * @function
  6965. * @param {Texture} value - The texture.
  6966. * @param {Node<vec2|vec3>?} [uvNode=null] - The uv node.
  6967. * @param {Node<int>?} [levelNode=null] - The level node.
  6968. * @param {Node<float>?} [biasNode=null] - The bias node.
  6969. * @returns {TextureNode}
  6970. */
  6971. const texture = /*@__PURE__*/ nodeProxy( TextureNode );
  6972. /**
  6973. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  6974. *
  6975. * @function
  6976. * @param {Texture} value - The texture.
  6977. * @param {Node<vec2|vec3>?} [uvNode=null] - The uv node.
  6978. * @param {Node<int>?} [levelNode=null] - The level node.
  6979. * @param {Node<float>?} [biasNode=null] - The bias node.
  6980. * @returns {TextureNode}
  6981. */
  6982. const textureLoad = ( ...params ) => texture( ...params ).setSampler( false );
  6983. //export const textureLevel = ( value, uv, level ) => texture( value, uv ).level( level );
  6984. /**
  6985. * Converts a texture or texture node to a sampler.
  6986. *
  6987. * @function
  6988. * @param {TextureNode|Texture} aTexture - The texture or texture node to convert.
  6989. * @returns {Node}
  6990. */
  6991. const sampler = ( aTexture ) => ( aTexture.isNode === true ? aTexture : texture( aTexture ) ).convert( 'sampler' );
  6992. /** @module BufferNode **/
  6993. /**
  6994. * A special type of uniform node which represents array-like data
  6995. * as uniform buffers. The access usually happens via `element()`
  6996. * which returns an instance of {@link ArrayElementNode}. For example:
  6997. *
  6998. * ```js
  6999. * const bufferNode = buffer( array, 'mat4', count );
  7000. * const matrixNode = bufferNode.element( index ); // access a matrix from the buffer
  7001. * ```
  7002. * In general, it is recommended to use the more managed {@link UniformArrayNode}
  7003. * since it handles more input types and automatically cares about buffer paddings.
  7004. *
  7005. * @augments module:UniformNode~UniformNode
  7006. */
  7007. class BufferNode extends UniformNode {
  7008. static get type() {
  7009. return 'BufferNode';
  7010. }
  7011. /**
  7012. * Constructs a new buffer node.
  7013. *
  7014. * @param {Array<Number>} value - Array-like buffer data.
  7015. * @param {String} bufferType - The data type of the buffer.
  7016. * @param {Number} [bufferCount=0] - The count of buffer elements.
  7017. */
  7018. constructor( value, bufferType, bufferCount = 0 ) {
  7019. super( value, bufferType );
  7020. /**
  7021. * This flag can be used for type testing.
  7022. *
  7023. * @type {Boolean}
  7024. * @readonly
  7025. * @default true
  7026. */
  7027. this.isBufferNode = true;
  7028. /**
  7029. * The data type of the buffer.
  7030. *
  7031. * @type {String}
  7032. */
  7033. this.bufferType = bufferType;
  7034. /**
  7035. * The uniform node that holds the value of the reference node.
  7036. *
  7037. * @type {Number}
  7038. * @default 0
  7039. */
  7040. this.bufferCount = bufferCount;
  7041. }
  7042. /**
  7043. * The data type of the buffer elements.
  7044. *
  7045. * @param {NodeBuilder} builder - The current node builder.
  7046. * @return {String} The element type.
  7047. */
  7048. getElementType( builder ) {
  7049. return this.getNodeType( builder );
  7050. }
  7051. /**
  7052. * Overwrites the default implementation to return a fixed value `'buffer'`.
  7053. *
  7054. * @param {NodeBuilder} builder - The current node builder.
  7055. * @return {String} The input type.
  7056. */
  7057. getInputType( /*builder*/ ) {
  7058. return 'buffer';
  7059. }
  7060. }
  7061. /**
  7062. * TSL function for creating a buffer node.
  7063. *
  7064. * @function
  7065. * @param {Array} value - Array-like buffer data.
  7066. * @param {String} type - The data type of a buffer element.
  7067. * @param {Number} count - The count of buffer elements.
  7068. * @returns {BufferNode}
  7069. */
  7070. const buffer = ( value, type, count ) => nodeObject( new BufferNode( value, type, count ) );
  7071. /** @module UniformArrayNode **/
  7072. /**
  7073. * Represents the element access on uniform array nodes.
  7074. *
  7075. * @augments ArrayElementNode
  7076. */
  7077. class UniformArrayElementNode extends ArrayElementNode {
  7078. static get type() {
  7079. return 'UniformArrayElementNode';
  7080. }
  7081. /**
  7082. * Constructs a new buffer node.
  7083. *
  7084. * @param {UniformArrayNode} uniformArrayNode - The uniform array node to access.
  7085. * @param {IndexNode} indexNode - The index data that define the position of the accessed element in the array.
  7086. */
  7087. constructor( uniformArrayNode, indexNode ) {
  7088. super( uniformArrayNode, indexNode );
  7089. /**
  7090. * This flag can be used for type testing.
  7091. *
  7092. * @type {Boolean}
  7093. * @readonly
  7094. * @default true
  7095. */
  7096. this.isArrayBufferElementNode = true;
  7097. }
  7098. generate( builder ) {
  7099. const snippet = super.generate( builder );
  7100. const type = this.getNodeType();
  7101. const paddedType = this.node.getPaddedType();
  7102. return builder.format( snippet, paddedType, type );
  7103. }
  7104. }
  7105. /**
  7106. * Similar to {@link module:BufferNode~BufferNode} this module represents array-like data as
  7107. * uniform buffers. Unlike {@link module:BufferNode~BufferNode}, it can handle more common
  7108. * data types in the array (e.g `three.js` primitives) and automatically
  7109. * manage buffer padding. It should be the first choice when working with
  7110. * uniforms buffers.
  7111. * ```js
  7112. * const tintColors = uniformArray( [
  7113. * new Color( 1, 0, 0 ),
  7114. * new Color( 0, 1, 0 ),
  7115. * new Color( 0, 0, 1 )
  7116. * ], 'color' );
  7117. *
  7118. * const redColor = tintColors.element( 0 );
  7119. *
  7120. * @augments module:BufferNode~BufferNode
  7121. */
  7122. class UniformArrayNode extends BufferNode {
  7123. static get type() {
  7124. return 'UniformArrayNode';
  7125. }
  7126. /**
  7127. * Constructs a new uniform array node.
  7128. *
  7129. * @param {Array<Any>} value - Array holding the buffer data.
  7130. * @param {String?} [elementType=null] - The data type of a buffer element.
  7131. */
  7132. constructor( value, elementType = null ) {
  7133. super( null );
  7134. /**
  7135. * Array holding the buffer data. Unlike {@link module:BufferNode~BufferNode}, the array can
  7136. * hold number primitives as well as three.js objects like vectors, matrices
  7137. * or colors.
  7138. *
  7139. * @type {Array<Any>}
  7140. */
  7141. this.array = value;
  7142. /**
  7143. * The data type of an array element.
  7144. *
  7145. * @type {String}
  7146. */
  7147. this.elementType = elementType === null ? getValueType( value[ 0 ] ) : elementType;
  7148. /**
  7149. * The padded type. Uniform buffers must conform to a certain buffer layout
  7150. * so a separate type is computed to ensure correct buffer size.
  7151. *
  7152. * @type {String}
  7153. */
  7154. this.paddedType = this.getPaddedType();
  7155. /**
  7156. * Overwritten since uniform array nodes are updated per render.
  7157. *
  7158. * @type {String}
  7159. * @default 'render'
  7160. */
  7161. this.updateType = NodeUpdateType.RENDER;
  7162. /**
  7163. * This flag can be used for type testing.
  7164. *
  7165. * @type {Boolean}
  7166. * @readonly
  7167. * @default true
  7168. */
  7169. this.isArrayBufferNode = true;
  7170. }
  7171. /**
  7172. * This method is overwritten since the node type is inferred from the
  7173. * {@link module:UniformArrayNode~UniformArrayNode#paddedType}.
  7174. *
  7175. * @param {NodeBuilder} builder - The current node builder.
  7176. * @return {String} The node type.
  7177. */
  7178. getNodeType( /*builder*/ ) {
  7179. return this.paddedType;
  7180. }
  7181. /**
  7182. * The data type of the array elements.
  7183. *
  7184. * @param {NodeBuilder} builder - The current node builder.
  7185. * @return {String} The element type.
  7186. */
  7187. getElementType() {
  7188. return this.elementType;
  7189. }
  7190. /**
  7191. * Returns the padded type based on the element type.
  7192. *
  7193. * @return {String} The padded type.
  7194. */
  7195. getPaddedType() {
  7196. const elementType = this.elementType;
  7197. let paddedType = 'vec4';
  7198. if ( elementType === 'mat2' ) {
  7199. paddedType = 'mat2';
  7200. } else if ( /mat/.test( elementType ) === true ) {
  7201. paddedType = 'mat4';
  7202. } else if ( elementType.charAt( 0 ) === 'i' ) {
  7203. paddedType = 'ivec4';
  7204. } else if ( elementType.charAt( 0 ) === 'u' ) {
  7205. paddedType = 'uvec4';
  7206. }
  7207. return paddedType;
  7208. }
  7209. /**
  7210. * The update makes sure to correctly transfer the data from the (complex) objects
  7211. * in the array to the internal, correctly padded value buffer.
  7212. *
  7213. * @param {NodeFrame} frame - A reference to the current node frame.
  7214. */
  7215. update( /*frame*/ ) {
  7216. const { array, value } = this;
  7217. const elementType = this.elementType;
  7218. if ( elementType === 'float' || elementType === 'int' || elementType === 'uint' ) {
  7219. for ( let i = 0; i < array.length; i ++ ) {
  7220. const index = i * 4;
  7221. value[ index ] = array[ i ];
  7222. }
  7223. } else if ( elementType === 'color' ) {
  7224. for ( let i = 0; i < array.length; i ++ ) {
  7225. const index = i * 4;
  7226. const vector = array[ i ];
  7227. value[ index ] = vector.r;
  7228. value[ index + 1 ] = vector.g;
  7229. value[ index + 2 ] = vector.b || 0;
  7230. //value[ index + 3 ] = vector.a || 0;
  7231. }
  7232. } else if ( elementType === 'mat2' ) {
  7233. for ( let i = 0; i < array.length; i ++ ) {
  7234. const index = i * 4;
  7235. const matrix = array[ i ];
  7236. value[ index ] = matrix.elements[ 0 ];
  7237. value[ index + 1 ] = matrix.elements[ 1 ];
  7238. value[ index + 2 ] = matrix.elements[ 2 ];
  7239. value[ index + 3 ] = matrix.elements[ 3 ];
  7240. }
  7241. } else if ( elementType === 'mat3' ) {
  7242. for ( let i = 0; i < array.length; i ++ ) {
  7243. const index = i * 16;
  7244. const matrix = array[ i ];
  7245. value[ index ] = matrix.elements[ 0 ];
  7246. value[ index + 1 ] = matrix.elements[ 1 ];
  7247. value[ index + 2 ] = matrix.elements[ 2 ];
  7248. value[ index + 4 ] = matrix.elements[ 3 ];
  7249. value[ index + 5 ] = matrix.elements[ 4 ];
  7250. value[ index + 6 ] = matrix.elements[ 5 ];
  7251. value[ index + 8 ] = matrix.elements[ 6 ];
  7252. value[ index + 9 ] = matrix.elements[ 7 ];
  7253. value[ index + 10 ] = matrix.elements[ 8 ];
  7254. value[ index + 15 ] = 1;
  7255. }
  7256. } else if ( elementType === 'mat4' ) {
  7257. for ( let i = 0; i < array.length; i ++ ) {
  7258. const index = i * 16;
  7259. const matrix = array[ i ];
  7260. for ( let i = 0; i < matrix.elements.length; i ++ ) {
  7261. value[ index + i ] = matrix.elements[ i ];
  7262. }
  7263. }
  7264. } else {
  7265. for ( let i = 0; i < array.length; i ++ ) {
  7266. const index = i * 4;
  7267. const vector = array[ i ];
  7268. value[ index ] = vector.x;
  7269. value[ index + 1 ] = vector.y;
  7270. value[ index + 2 ] = vector.z || 0;
  7271. value[ index + 3 ] = vector.w || 0;
  7272. }
  7273. }
  7274. }
  7275. /**
  7276. * Implement the value buffer creation based on the array data.
  7277. *
  7278. * @param {NodeBuilder} builder - A reference to the current node builder.
  7279. * @return {null}
  7280. */
  7281. setup( builder ) {
  7282. const length = this.array.length;
  7283. const elementType = this.elementType;
  7284. let arrayType = Float32Array;
  7285. const paddedType = this.paddedType;
  7286. const paddedElementLength = builder.getTypeLength( paddedType );
  7287. if ( elementType.charAt( 0 ) === 'i' ) arrayType = Int32Array;
  7288. if ( elementType.charAt( 0 ) === 'u' ) arrayType = Uint32Array;
  7289. this.value = new arrayType( length * paddedElementLength );
  7290. this.bufferCount = length;
  7291. this.bufferType = paddedType;
  7292. return super.setup( builder );
  7293. }
  7294. /**
  7295. * Overwrites the default `element()` method to provide element access
  7296. * based on {@link module:UniformArrayNode~UniformArrayNode}.
  7297. *
  7298. * @param {IndexNode} indexNode - The index node.
  7299. * @return {UniformArrayElementNode}
  7300. */
  7301. element( indexNode ) {
  7302. return nodeObject( new UniformArrayElementNode( this, nodeObject( indexNode ) ) );
  7303. }
  7304. }
  7305. /**
  7306. * TSL function for creating an uniform array node.
  7307. *
  7308. * @function
  7309. * @param {Array<Any>} values - Array-like data.
  7310. * @param {String?} nodeType - The data type of the array elements.
  7311. * @returns {UniformArrayNode}
  7312. */
  7313. const uniformArray = ( values, nodeType ) => nodeObject( new UniformArrayNode( values, nodeType ) );
  7314. /**
  7315. * @function
  7316. * @deprecated since r168. Use {@link uniformArray} instead.
  7317. *
  7318. * @param {Array<Any>} values - Array-like data.
  7319. * @param {String} nodeType - The data type of the array elements.
  7320. * @returns {UniformArrayNode}
  7321. */
  7322. const uniforms = ( values, nodeType ) => { // @deprecated, r168
  7323. console.warn( 'TSL.UniformArrayNode: uniforms() has been renamed to uniformArray().' );
  7324. return nodeObject( new UniformArrayNode( values, nodeType ) );
  7325. };
  7326. /** @module Camera **/
  7327. /**
  7328. * TSL object that represents the current `index` value of the camera if used ArrayCamera.
  7329. *
  7330. * @type {UniformNode<uint>}
  7331. */
  7332. const cameraIndex = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( sharedUniformGroup( 'cameraIndex' ) ).toVarying( 'v_cameraIndex' );
  7333. /**
  7334. * TSL object that represents the `near` value of the camera used for the current render.
  7335. *
  7336. * @type {UniformNode<float>}
  7337. */
  7338. const cameraNear = /*@__PURE__*/ uniform( 'float' ).label( 'cameraNear' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.near );
  7339. /**
  7340. * TSL object that represents the `far` value of the camera used for the current render.
  7341. *
  7342. * @type {UniformNode<float>}
  7343. */
  7344. const cameraFar = /*@__PURE__*/ uniform( 'float' ).label( 'cameraFar' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.far );
  7345. /**
  7346. * TSL object that represents the projection matrix of the camera used for the current render.
  7347. *
  7348. * @type {UniformNode<mat4>}
  7349. */
  7350. const cameraProjectionMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  7351. let cameraProjectionMatrix;
  7352. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  7353. const matrices = [];
  7354. for ( const subCamera of camera.cameras ) {
  7355. matrices.push( subCamera.projectionMatrix );
  7356. }
  7357. const cameraProjectionMatrices = uniformArray( matrices ).setGroup( renderGroup ).label( 'cameraProjectionMatrices' );
  7358. cameraProjectionMatrix = cameraProjectionMatrices.element( cameraIndex ).toVar( 'cameraProjectionMatrix' );
  7359. } else {
  7360. cameraProjectionMatrix = uniform( 'mat4' ).label( 'cameraProjectionMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrix );
  7361. }
  7362. return cameraProjectionMatrix;
  7363. } ).once() )();
  7364. /**
  7365. * TSL object that represents the inverse projection matrix of the camera used for the current render.
  7366. *
  7367. * @type {UniformNode<mat4>}
  7368. */
  7369. const cameraProjectionMatrixInverse = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraProjectionMatrixInverse' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrixInverse );
  7370. /**
  7371. * TSL object that represents the view matrix of the camera used for the current render.
  7372. *
  7373. * @type {UniformNode<mat4>}
  7374. */
  7375. const cameraViewMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  7376. let cameraViewMatrix;
  7377. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  7378. const matrices = [];
  7379. for ( const subCamera of camera.cameras ) {
  7380. matrices.push( subCamera.matrixWorldInverse );
  7381. }
  7382. const cameraViewMatrices = uniformArray( matrices ).setGroup( renderGroup ).label( 'cameraViewMatrices' );
  7383. cameraViewMatrix = cameraViewMatrices.element( cameraIndex ).toVar( 'cameraViewMatrix' );
  7384. } else {
  7385. cameraViewMatrix = uniform( 'mat4' ).label( 'cameraViewMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorldInverse );
  7386. }
  7387. return cameraViewMatrix;
  7388. } ).once() )();
  7389. /**
  7390. * TSL object that represents the world matrix of the camera used for the current render.
  7391. *
  7392. * @type {UniformNode<mat4>}
  7393. */
  7394. const cameraWorldMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraWorldMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorld );
  7395. /**
  7396. * TSL object that represents the normal matrix of the camera used for the current render.
  7397. *
  7398. * @type {UniformNode<mat3>}
  7399. */
  7400. const cameraNormalMatrix = /*@__PURE__*/ uniform( 'mat3' ).label( 'cameraNormalMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.normalMatrix );
  7401. /**
  7402. * TSL object that represents the position in world space of the camera used for the current render.
  7403. *
  7404. * @type {UniformNode<vec3>}
  7405. */
  7406. const cameraPosition = /*@__PURE__*/ uniform( new Vector3() ).label( 'cameraPosition' ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => self.value.setFromMatrixPosition( camera.matrixWorld ) );
  7407. /** @module Object3DNode **/
  7408. /**
  7409. * This node can be used to access transformation related metrics of 3D objects.
  7410. * Depending on the selected scope, a different metric is represented as a uniform
  7411. * in the shader. The following scopes are supported:
  7412. *
  7413. * - `POSITION`: The object's position in world space.
  7414. * - `VIEW_POSITION`: The object's position in view/camera space.
  7415. * - `DIRECTION`: The object's direction in world space.
  7416. * - `SCALE`: The object's scale in world space.
  7417. * - `WORLD_MATRIX`: The object's matrix in world space.
  7418. *
  7419. * @augments Node
  7420. */
  7421. class Object3DNode extends Node {
  7422. static get type() {
  7423. return 'Object3DNode';
  7424. }
  7425. /**
  7426. * Constructs a new object 3D node.
  7427. *
  7428. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  7429. * @param {Object3D?} [object3d=null] - The 3D object.
  7430. */
  7431. constructor( scope, object3d = null ) {
  7432. super();
  7433. /**
  7434. * The node reports a different type of transformation depending on the scope.
  7435. *
  7436. * @type {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')}
  7437. */
  7438. this.scope = scope;
  7439. /**
  7440. * The 3D object.
  7441. *
  7442. * @type {Object3D?}
  7443. * @default null
  7444. */
  7445. this.object3d = object3d;
  7446. /**
  7447. * Overwritten since this type of node is updated per object.
  7448. *
  7449. * @type {String}
  7450. * @default 'object'
  7451. */
  7452. this.updateType = NodeUpdateType.OBJECT;
  7453. /**
  7454. * Holds the value of the node as a uniform.
  7455. *
  7456. * @private
  7457. * @type {UniformNode}
  7458. */
  7459. this._uniformNode = new UniformNode( null );
  7460. }
  7461. /**
  7462. * Overwritten since the node type is inferred from the scope.
  7463. *
  7464. * @return {String} The node type.
  7465. */
  7466. getNodeType() {
  7467. const scope = this.scope;
  7468. if ( scope === Object3DNode.WORLD_MATRIX ) {
  7469. return 'mat4';
  7470. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  7471. return 'vec3';
  7472. }
  7473. }
  7474. /**
  7475. * Updates the uniform value depending on the scope.
  7476. *
  7477. * @param {NodeFrame} frame - The current node frame.
  7478. */
  7479. update( frame ) {
  7480. const object = this.object3d;
  7481. const uniformNode = this._uniformNode;
  7482. const scope = this.scope;
  7483. if ( scope === Object3DNode.WORLD_MATRIX ) {
  7484. uniformNode.value = object.matrixWorld;
  7485. } else if ( scope === Object3DNode.POSITION ) {
  7486. uniformNode.value = uniformNode.value || new Vector3();
  7487. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  7488. } else if ( scope === Object3DNode.SCALE ) {
  7489. uniformNode.value = uniformNode.value || new Vector3();
  7490. uniformNode.value.setFromMatrixScale( object.matrixWorld );
  7491. } else if ( scope === Object3DNode.DIRECTION ) {
  7492. uniformNode.value = uniformNode.value || new Vector3();
  7493. object.getWorldDirection( uniformNode.value );
  7494. } else if ( scope === Object3DNode.VIEW_POSITION ) {
  7495. const camera = frame.camera;
  7496. uniformNode.value = uniformNode.value || new Vector3();
  7497. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  7498. uniformNode.value.applyMatrix4( camera.matrixWorldInverse );
  7499. }
  7500. }
  7501. /**
  7502. * Generates the code snippet of the uniform node. The node type of the uniform
  7503. * node also depends on the selected scope.
  7504. *
  7505. * @param {NodeBuilder} builder - The current node builder.
  7506. * @return {String} The generated code snippet.
  7507. */
  7508. generate( builder ) {
  7509. const scope = this.scope;
  7510. if ( scope === Object3DNode.WORLD_MATRIX ) {
  7511. this._uniformNode.nodeType = 'mat4';
  7512. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  7513. this._uniformNode.nodeType = 'vec3';
  7514. }
  7515. return this._uniformNode.build( builder );
  7516. }
  7517. serialize( data ) {
  7518. super.serialize( data );
  7519. data.scope = this.scope;
  7520. }
  7521. deserialize( data ) {
  7522. super.deserialize( data );
  7523. this.scope = data.scope;
  7524. }
  7525. }
  7526. Object3DNode.WORLD_MATRIX = 'worldMatrix';
  7527. Object3DNode.POSITION = 'position';
  7528. Object3DNode.SCALE = 'scale';
  7529. Object3DNode.VIEW_POSITION = 'viewPosition';
  7530. Object3DNode.DIRECTION = 'direction';
  7531. /**
  7532. * TSL function for creating an object 3D node that represents the object's direction in world space.
  7533. *
  7534. * @function
  7535. * @param {Object3D?} [object3d=null] - The 3D object.
  7536. * @returns {Object3DNode<vec3>}
  7537. */
  7538. const objectDirection = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.DIRECTION );
  7539. /**
  7540. * TSL function for creating an object 3D node that represents the object's world matrix.
  7541. *
  7542. * @function
  7543. * @param {Object3D?} [object3d=null] - The 3D object.
  7544. * @returns {Object3DNode<mat4>}
  7545. */
  7546. const objectWorldMatrix = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX );
  7547. /**
  7548. * TSL function for creating an object 3D node that represents the object's position in world space.
  7549. *
  7550. * @function
  7551. * @param {Object3D?} [object3d=null] - The 3D object.
  7552. * @returns {Object3DNode<vec3>}
  7553. */
  7554. const objectPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.POSITION );
  7555. /**
  7556. * TSL function for creating an object 3D node that represents the object's scale in world space.
  7557. *
  7558. * @function
  7559. * @param {Object3D?} [object3d=null] - The 3D object.
  7560. * @returns {Object3DNode<vec3>}
  7561. */
  7562. const objectScale = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.SCALE );
  7563. /**
  7564. * TSL function for creating an object 3D node that represents the object's position in view/camera space.
  7565. *
  7566. * @function
  7567. * @param {Object3D?} [object3d=null] - The 3D object.
  7568. * @returns {Object3DNode<vec3>}
  7569. */
  7570. const objectViewPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION );
  7571. /** @module ModelNode **/
  7572. /**
  7573. * This type of node is a specialized version of `Object3DNode`
  7574. * with larger set of model related metrics. Unlike `Object3DNode`,
  7575. * `ModelNode` extracts the reference to the 3D object from the
  7576. * current node frame state.
  7577. *
  7578. * @augments module:Object3DNode~Object3DNode
  7579. */
  7580. class ModelNode extends Object3DNode {
  7581. static get type() {
  7582. return 'ModelNode';
  7583. }
  7584. /**
  7585. * Constructs a new object model node.
  7586. *
  7587. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  7588. */
  7589. constructor( scope ) {
  7590. super( scope );
  7591. }
  7592. /**
  7593. * Extracts the model reference from the frame state and then
  7594. * updates the uniform value depending on the scope.
  7595. *
  7596. * @param {NodeFrame} frame - The current node frame.
  7597. */
  7598. update( frame ) {
  7599. this.object3d = frame.object;
  7600. super.update( frame );
  7601. }
  7602. }
  7603. /**
  7604. * TSL object that represents the object's direction in world space.
  7605. *
  7606. * @type {ModelNode<vec3>}
  7607. */
  7608. const modelDirection = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.DIRECTION );
  7609. /**
  7610. * TSL object that represents the object's world matrix.
  7611. *
  7612. * @type {ModelNode<mat4>}
  7613. */
  7614. const modelWorldMatrix = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX );
  7615. /**
  7616. * TSL object that represents the object's position in world space.
  7617. *
  7618. * @type {ModelNode<vec3>}
  7619. */
  7620. const modelPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.POSITION );
  7621. /**
  7622. * TSL object that represents the object's scale in world space.
  7623. *
  7624. * @type {ModelNode<vec3>}
  7625. */
  7626. const modelScale = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.SCALE );
  7627. /**
  7628. * TSL object that represents the object's position in view/camera space.
  7629. *
  7630. * @type {ModelNode<vec3>}
  7631. */
  7632. const modelViewPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.VIEW_POSITION );
  7633. /**
  7634. * TSL object that represents the object's normal matrix.
  7635. *
  7636. * @type {UniformNode<mat3>}
  7637. */
  7638. const modelNormalMatrix = /*@__PURE__*/ uniform( new Matrix3() ).onObjectUpdate( ( { object }, self ) => self.value.getNormalMatrix( object.matrixWorld ) );
  7639. /**
  7640. * TSL object that represents the object's inverse world matrix.
  7641. *
  7642. * @type {UniformNode<mat4>}
  7643. */
  7644. const modelWorldMatrixInverse = /*@__PURE__*/ uniform( new Matrix4() ).onObjectUpdate( ( { object }, self ) => self.value.copy( object.matrixWorld ).invert() );
  7645. /**
  7646. * TSL object that represents the object's model view matrix.
  7647. *
  7648. * @type {Node<mat4>}
  7649. */
  7650. const modelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  7651. return builder.renderer.nodes.modelViewMatrix || mediumpModelViewMatrix;
  7652. } ).once() )().toVar( 'modelViewMatrix' );
  7653. // GPU Precision
  7654. /**
  7655. * TSL object that represents the object's model view in `mediump` precision.
  7656. *
  7657. * @type {Node<mat4>}
  7658. */
  7659. const mediumpModelViewMatrix = /*@__PURE__*/ cameraViewMatrix.mul( modelWorldMatrix );
  7660. // CPU Precision
  7661. /**
  7662. * TSL object that represents the object's model view in `highp` precision
  7663. * which is achieved by computing the matrix in JS and not in the shader.
  7664. *
  7665. * @type {Node<mat4>}
  7666. */
  7667. const highpModelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  7668. builder.context.isHighPrecisionModelViewMatrix = true;
  7669. return uniform( 'mat4' ).onObjectUpdate( ( { object, camera } ) => {
  7670. return object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  7671. } );
  7672. } ).once() )().toVar( 'highpModelViewMatrix' );
  7673. /**
  7674. * TSL object that represents the object's model normal view in `highp` precision
  7675. * which is achieved by computing the matrix in JS and not in the shader.
  7676. *
  7677. * @type {Node<mat3>}
  7678. */
  7679. const highpModelNormalViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  7680. const isHighPrecisionModelViewMatrix = builder.context.isHighPrecisionModelViewMatrix;
  7681. return uniform( 'mat3' ).onObjectUpdate( ( { object, camera } ) => {
  7682. if ( isHighPrecisionModelViewMatrix !== true ) {
  7683. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  7684. }
  7685. return object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  7686. } );
  7687. } ).once() )().toVar( 'highpModelNormalViewMatrix' );
  7688. /** @module Position **/
  7689. /**
  7690. * TSL object that represents the position attribute of the current rendered object.
  7691. *
  7692. * @type {AttributeNode<vec3>}
  7693. */
  7694. const positionGeometry = /*@__PURE__*/ attribute( 'position', 'vec3' );
  7695. /**
  7696. * TSL object that represents the vertex position in local space of the current rendered object.
  7697. *
  7698. * @type {AttributeNode<vec3>}
  7699. */
  7700. const positionLocal = /*@__PURE__*/ positionGeometry.toVarying( 'positionLocal' );
  7701. /**
  7702. * TSL object that represents the previous vertex position in local space of the current rendered object.
  7703. * Used in context of {@link module:VelocityNode~VelocityNode} for rendering motion vectors.
  7704. *
  7705. * @type {AttributeNode<vec3>}
  7706. */
  7707. const positionPrevious = /*@__PURE__*/ positionGeometry.toVarying( 'positionPrevious' );
  7708. /**
  7709. * TSL object that represents the vertex position in world space of the current rendered object.
  7710. *
  7711. * @type {VaryingNode<vec3>}
  7712. */
  7713. const positionWorld = /*@__PURE__*/ modelWorldMatrix.mul( positionLocal ).xyz.toVarying( 'v_positionWorld' ).context( { needsPositionReassign: true } );
  7714. /**
  7715. * TSL object that represents the position world direction of the current rendered object.
  7716. *
  7717. * @type {Node<vec3>}
  7718. */
  7719. const positionWorldDirection = /*@__PURE__*/ positionLocal.transformDirection( modelWorldMatrix ).toVarying( 'v_positionWorldDirection' ).normalize().toVar( 'positionWorldDirection' ).context( { needsPositionReassign: true } );
  7720. /**
  7721. * TSL object that represents the vertex position in view space of the current rendered object.
  7722. *
  7723. * @type {VaryingNode<vec3>}
  7724. */
  7725. const positionView = /*@__PURE__*/ ( Fn( ( builder ) => {
  7726. return builder.context.setupPositionView();
  7727. }, 'vec3' ).once() )().toVarying( 'v_positionView' ).context( { needsPositionReassign: true } );
  7728. /**
  7729. * TSL object that represents the position view direction of the current rendered object.
  7730. *
  7731. * @type {VaryingNode<vec3>}
  7732. */
  7733. const positionViewDirection = /*@__PURE__*/ positionView.negate().toVarying( 'v_positionViewDirection' ).normalize().toVar( 'positionViewDirection' );
  7734. /** @module FrontFacingNode **/
  7735. /**
  7736. * This node can be used to evaluate whether a primitive is front or back facing.
  7737. *
  7738. * @augments Node
  7739. */
  7740. class FrontFacingNode extends Node {
  7741. static get type() {
  7742. return 'FrontFacingNode';
  7743. }
  7744. /**
  7745. * Constructs a new front facing node.
  7746. */
  7747. constructor() {
  7748. super( 'bool' );
  7749. /**
  7750. * This flag can be used for type testing.
  7751. *
  7752. * @type {Boolean}
  7753. * @readonly
  7754. * @default true
  7755. */
  7756. this.isFrontFacingNode = true;
  7757. }
  7758. generate( builder ) {
  7759. const { renderer, material } = builder;
  7760. if ( renderer.coordinateSystem === WebGLCoordinateSystem ) {
  7761. if ( material.side === BackSide ) {
  7762. return 'false';
  7763. }
  7764. }
  7765. return builder.getFrontFacing();
  7766. }
  7767. }
  7768. /**
  7769. * TSL object that represents whether a primitive is front or back facing
  7770. *
  7771. * @type {FrontFacingNode<bool>}
  7772. */
  7773. const frontFacing = /*@__PURE__*/ nodeImmutable( FrontFacingNode );
  7774. /**
  7775. * TSL object that represents the front facing status as a number instead of a bool.
  7776. * `1` means front facing, `-1` means back facing.
  7777. *
  7778. * @type {Node<float>}
  7779. */
  7780. const faceDirection = /*@__PURE__*/ float( frontFacing ).mul( 2.0 ).sub( 1.0 );
  7781. /** @module Normal **/
  7782. /**
  7783. * TSL object that represents the normal attribute of the current rendered object.
  7784. *
  7785. * @type {Node<vec3>}
  7786. */
  7787. const normalGeometry = /*@__PURE__*/ attribute( 'normal', 'vec3' );
  7788. /**
  7789. * TSL object that represents the vertex normal in local space of the current rendered object.
  7790. *
  7791. * @type {Node<vec3>}
  7792. */
  7793. const normalLocal = /*@__PURE__*/ ( Fn( ( builder ) => {
  7794. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  7795. console.warn( 'TSL.NormalNode: Vertex attribute "normal" not found on geometry.' );
  7796. return vec3( 0, 1, 0 );
  7797. }
  7798. return normalGeometry;
  7799. }, 'vec3' ).once() )().toVar( 'normalLocal' );
  7800. /**
  7801. * TSL object that represents the flat vertex normal in view space of the current rendered object.
  7802. *
  7803. * @type {Node<vec3>}
  7804. */
  7805. const normalFlat = /*@__PURE__*/ positionView.dFdx().cross( positionView.dFdy() ).normalize().toVar( 'normalFlat' );
  7806. /**
  7807. * TSL object that represents the vertex normal in view space of the current rendered object.
  7808. *
  7809. * @type {Node<vec3>}
  7810. */
  7811. const normalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  7812. let node;
  7813. if ( builder.material.flatShading === true ) {
  7814. node = normalFlat;
  7815. } else {
  7816. node = varying( transformNormalToView( normalLocal ), 'v_normalView' ).normalize();
  7817. }
  7818. return node;
  7819. }, 'vec3' ).once() )().toVar( 'normalView' );
  7820. /**
  7821. * TSL object that represents the vertex normal in world space of the current rendered object.
  7822. *
  7823. * @type {Node<vec3>}
  7824. */
  7825. const normalWorld = /*@__PURE__*/ varying( normalView.transformDirection( cameraViewMatrix ), 'v_normalWorld' ).normalize().toVar( 'normalWorld' );
  7826. /**
  7827. * TSL object that represents the transformed vertex normal in view space of the current rendered object.
  7828. *
  7829. * @type {Node<vec3>}
  7830. */
  7831. const transformedNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  7832. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  7833. return builder.context.setupNormal().context( { getUV: null } );
  7834. }, 'vec3' ).once() )().mul( faceDirection ).toVar( 'transformedNormalView' );
  7835. /**
  7836. * TSL object that represents the transformed vertex normal in world space of the current rendered object.
  7837. *
  7838. * @type {Node<vec3>}
  7839. */
  7840. const transformedNormalWorld = /*@__PURE__*/ transformedNormalView.transformDirection( cameraViewMatrix ).toVar( 'transformedNormalWorld' );
  7841. /**
  7842. * TSL object that represents the transformed clearcoat vertex normal in view space of the current rendered object.
  7843. *
  7844. * @type {Node<vec3>}
  7845. */
  7846. const transformedClearcoatNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  7847. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  7848. return builder.context.setupClearcoatNormal().context( { getUV: null } );
  7849. }, 'vec3' ).once() )().mul( faceDirection ).toVar( 'transformedClearcoatNormalView' );
  7850. /**
  7851. * Transforms the normal with the given matrix.
  7852. *
  7853. * @function
  7854. * @param {Node<vec3>} normal - The normal.
  7855. * @param {Node<mat3>} [matrix=modelWorldMatrix] - The matrix.
  7856. * @return {Node<vec3>} The transformed normal.
  7857. */
  7858. const transformNormal = /*@__PURE__*/ Fn( ( [ normal, matrix = modelWorldMatrix ] ) => {
  7859. const m = mat3( matrix );
  7860. const transformedNormal = normal.div( vec3( m[ 0 ].dot( m[ 0 ] ), m[ 1 ].dot( m[ 1 ] ), m[ 2 ].dot( m[ 2 ] ) ) );
  7861. return m.mul( transformedNormal ).xyz;
  7862. } );
  7863. /**
  7864. * Transforms the given normal from local to view space.
  7865. *
  7866. * @function
  7867. * @param {Node<vec3>} normal - The normal.
  7868. * @param {NodeBuilder} builder - The current node builder.
  7869. * @return {Node<vec3>} The transformed normal.
  7870. */
  7871. const transformNormalToView = /*@__PURE__*/ Fn( ( [ normal ], builder ) => {
  7872. const modelNormalViewMatrix = builder.renderer.nodes.modelNormalViewMatrix;
  7873. if ( modelNormalViewMatrix !== null ) {
  7874. return modelNormalViewMatrix.transformDirection( normal );
  7875. }
  7876. //
  7877. const transformedNormal = modelNormalMatrix.mul( normal );
  7878. return cameraViewMatrix.transformDirection( transformedNormal );
  7879. } );
  7880. /** @module MaterialProperties **/
  7881. /**
  7882. * TSL object that represents the refraction ratio of the material used for rendering the current object.
  7883. *
  7884. * @type {UniformNode<float>}
  7885. */
  7886. const materialRefractionRatio = /*@__PURE__*/ uniform( 0 ).onReference( ( { material } ) => material ).onRenderUpdate( ( { material } ) => material.refractionRatio );
  7887. /** @module ReflectVector **/
  7888. /**
  7889. * The reflect vector in view space.
  7890. *
  7891. * @type {Node<vec3>}
  7892. */
  7893. const reflectView = /*@__PURE__*/ positionViewDirection.negate().reflect( transformedNormalView );
  7894. /**
  7895. * The refract vector in view space.
  7896. *
  7897. * @type {Node<vec3>}
  7898. */
  7899. const refractView = /*@__PURE__*/ positionViewDirection.negate().refract( transformedNormalView, materialRefractionRatio );
  7900. /**
  7901. * Used for sampling cube maps when using cube reflection mapping.
  7902. *
  7903. * @type {Node<vec3>}
  7904. */
  7905. const reflectVector = /*@__PURE__*/ reflectView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  7906. /**
  7907. * Used for sampling cube maps when using cube refraction mapping.
  7908. *
  7909. * @type {Node<vec3>}
  7910. */
  7911. const refractVector = /*@__PURE__*/ refractView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  7912. /** @module CubeTextureNode **/
  7913. /**
  7914. * This type of uniform node represents a cube texture.
  7915. *
  7916. * @augments module:TextureNode~TextureNode
  7917. */
  7918. class CubeTextureNode extends TextureNode {
  7919. static get type() {
  7920. return 'CubeTextureNode';
  7921. }
  7922. /**
  7923. * Constructs a new cube texture node.
  7924. *
  7925. * @param {CubeTexture} value - The cube texture.
  7926. * @param {Node<vec3>?} [uvNode=null] - The uv node.
  7927. * @param {Node<int>?} [levelNode=null] - The level node.
  7928. * @param {Node<float>?} [biasNode=null] - The bias node.
  7929. */
  7930. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  7931. super( value, uvNode, levelNode, biasNode );
  7932. /**
  7933. * This flag can be used for type testing.
  7934. *
  7935. * @type {Boolean}
  7936. * @readonly
  7937. * @default true
  7938. */
  7939. this.isCubeTextureNode = true;
  7940. }
  7941. /**
  7942. * Overwrites the default implementation to return a fixed value `'cubeTexture'`.
  7943. *
  7944. * @param {NodeBuilder} builder - The current node builder.
  7945. * @return {String} The input type.
  7946. */
  7947. getInputType( /*builder*/ ) {
  7948. return 'cubeTexture';
  7949. }
  7950. /**
  7951. * Returns a default uvs based on the mapping type of the cube texture.
  7952. *
  7953. * @return {Node<vec3>} The default uv attribute.
  7954. */
  7955. getDefaultUV() {
  7956. const texture = this.value;
  7957. if ( texture.mapping === CubeReflectionMapping ) {
  7958. return reflectVector;
  7959. } else if ( texture.mapping === CubeRefractionMapping ) {
  7960. return refractVector;
  7961. } else {
  7962. console.error( 'THREE.CubeTextureNode: Mapping "%s" not supported.', texture.mapping );
  7963. return vec3( 0, 0, 0 );
  7964. }
  7965. }
  7966. /**
  7967. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  7968. * for cube textures. The uv transformation matrix is not applied to cube textures.
  7969. *
  7970. * @param {Boolean} value - The update toggle.
  7971. */
  7972. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for CubeTextureNode
  7973. /**
  7974. * Setups the uv node. Depending on the backend as well as the texture type, it might be necessary
  7975. * to modify the uv node for correct sampling.
  7976. *
  7977. * @param {NodeBuilder} builder - The current node builder.
  7978. * @param {Node} uvNode - The uv node to setup.
  7979. * @return {Node} The updated uv node.
  7980. */
  7981. setupUV( builder, uvNode ) {
  7982. const texture = this.value;
  7983. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem || ! texture.isRenderTargetTexture ) {
  7984. return vec3( uvNode.x.negate(), uvNode.yz );
  7985. } else {
  7986. return uvNode;
  7987. }
  7988. }
  7989. /**
  7990. * Generates the uv code snippet.
  7991. *
  7992. * @param {NodeBuilder} builder - The current node builder.
  7993. * @param {Node} cubeUV - The uv node to generate code for.
  7994. * @return {String} The generated code snippet.
  7995. */
  7996. generateUV( builder, cubeUV ) {
  7997. return cubeUV.build( builder, 'vec3' );
  7998. }
  7999. }
  8000. /**
  8001. * TSL function for creating a cube texture node.
  8002. *
  8003. * @function
  8004. * @param {CubeTexture} value - The cube texture.
  8005. * @param {Node<vec3>?} [uvNode=null] - The uv node.
  8006. * @param {Node<int>?} [levelNode=null] - The level node.
  8007. * @param {Node<float>?} [biasNode=null] - The bias node.
  8008. * @returns {CubeTextureNode}
  8009. */
  8010. const cubeTexture = /*@__PURE__*/ nodeProxy( CubeTextureNode );
  8011. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  8012. /** @module ReferenceNode **/
  8013. /**
  8014. * This class is only relevant if the referenced property is array-like.
  8015. * In this case, `ReferenceElementNode` allows to refer to a specific
  8016. * element inside the data structure via an index.
  8017. *
  8018. * @augments ArrayElementNode
  8019. */
  8020. class ReferenceElementNode extends ArrayElementNode {
  8021. static get type() {
  8022. return 'ReferenceElementNode';
  8023. }
  8024. /**
  8025. * Constructs a new reference element node.
  8026. *
  8027. * @param {ReferenceNode?} referenceNode - The reference node.
  8028. * @param {Node} indexNode - The index node that defines the element access.
  8029. */
  8030. constructor( referenceNode, indexNode ) {
  8031. super( referenceNode, indexNode );
  8032. /**
  8033. * Similar to {@link module:ReferenceNode~ReferenceNode#reference}, an additional
  8034. * property references to the current node.
  8035. *
  8036. * @type {ReferenceNode?}
  8037. * @default null
  8038. */
  8039. this.referenceNode = referenceNode;
  8040. /**
  8041. * This flag can be used for type testing.
  8042. *
  8043. * @type {Boolean}
  8044. * @readonly
  8045. * @default true
  8046. */
  8047. this.isReferenceElementNode = true;
  8048. }
  8049. /**
  8050. * This method is overwritten since the node type is inferred from
  8051. * the uniform type of the reference node.
  8052. *
  8053. * @return {String} The node type.
  8054. */
  8055. getNodeType() {
  8056. return this.referenceNode.uniformType;
  8057. }
  8058. generate( builder ) {
  8059. const snippet = super.generate( builder );
  8060. const arrayType = this.referenceNode.getNodeType();
  8061. const elementType = this.getNodeType();
  8062. return builder.format( snippet, arrayType, elementType );
  8063. }
  8064. }
  8065. /**
  8066. * This type of node establishes a reference to a property of another object.
  8067. * In this way, the value of the node is automatically linked to the value of
  8068. * referenced object. Reference nodes internally represent the linked value
  8069. * as a uniform.
  8070. *
  8071. * @augments Node
  8072. */
  8073. class ReferenceNode extends Node {
  8074. static get type() {
  8075. return 'ReferenceNode';
  8076. }
  8077. /**
  8078. * Constructs a new reference node.
  8079. *
  8080. * @param {String} property - The name of the property the node refers to.
  8081. * @param {String} uniformType - The uniform type that should be used to represent the property value.
  8082. * @param {Object?} [object=null] - The object the property belongs to.
  8083. * @param {Number?} [count=null] - When the linked property is an array-like, this parameter defines its length.
  8084. */
  8085. constructor( property, uniformType, object = null, count = null ) {
  8086. super();
  8087. /**
  8088. * The name of the property the node refers to.
  8089. *
  8090. * @type {String}
  8091. */
  8092. this.property = property;
  8093. /**
  8094. * The uniform type that should be used to represent the property value.
  8095. *
  8096. * @type {String}
  8097. */
  8098. this.uniformType = uniformType;
  8099. /**
  8100. * The object the property belongs to.
  8101. *
  8102. * @type {Object?}
  8103. * @default null
  8104. */
  8105. this.object = object;
  8106. /**
  8107. * When the linked property is an array, this parameter defines its length.
  8108. *
  8109. * @type {Number?}
  8110. * @default null
  8111. */
  8112. this.count = count;
  8113. /**
  8114. * The property name might have dots so nested properties can be referred.
  8115. * The hierarchy of the names is stored inside this array.
  8116. *
  8117. * @type {Array<String>}
  8118. */
  8119. this.properties = property.split( '.' );
  8120. /**
  8121. * Points to the current referred object. This property exists next to {@link module:ReferenceNode~ReferenceNode#object}
  8122. * since the final reference might be updated from calling code.
  8123. *
  8124. * @type {Object?}
  8125. * @default null
  8126. */
  8127. this.reference = object;
  8128. /**
  8129. * The uniform node that holds the value of the reference node.
  8130. *
  8131. * @type {UniformNode}
  8132. * @default null
  8133. */
  8134. this.node = null;
  8135. /**
  8136. * The uniform group of the internal uniform.
  8137. *
  8138. * @type {UniformGroupNode}
  8139. * @default null
  8140. */
  8141. this.group = null;
  8142. /**
  8143. * An optional label of the internal uniform node.
  8144. *
  8145. * @type {String?}
  8146. * @default null
  8147. */
  8148. this.name = null;
  8149. /**
  8150. * Overwritten since reference nodes are updated per object.
  8151. *
  8152. * @type {String}
  8153. * @default 'object'
  8154. */
  8155. this.updateType = NodeUpdateType.OBJECT;
  8156. }
  8157. /**
  8158. * When the referred property is array-like, this method can be used
  8159. * to access elements via an index node.
  8160. *
  8161. * @param {IndexNode} indexNode - indexNode.
  8162. * @return {ReferenceElementNode} A reference to an element.
  8163. */
  8164. element( indexNode ) {
  8165. return nodeObject( new ReferenceElementNode( this, nodeObject( indexNode ) ) );
  8166. }
  8167. /**
  8168. * Sets the uniform group for this reference node.
  8169. *
  8170. * @param {UniformGroupNode} group - The uniform group to set.
  8171. * @return {ReferenceNode} A reference to this node.
  8172. */
  8173. setGroup( group ) {
  8174. this.group = group;
  8175. return this;
  8176. }
  8177. /**
  8178. * Sets the label for the internal uniform.
  8179. *
  8180. * @param {String} name - The label to set.
  8181. * @return {ReferenceNode} A reference to this node.
  8182. */
  8183. label( name ) {
  8184. this.name = name;
  8185. return this;
  8186. }
  8187. /**
  8188. * Sets the node type which automatically defines the internal
  8189. * uniform type.
  8190. *
  8191. * @param {String} uniformType - The type to set.
  8192. */
  8193. setNodeType( uniformType ) {
  8194. let node = null;
  8195. if ( this.count !== null ) {
  8196. node = buffer( null, uniformType, this.count );
  8197. } else if ( Array.isArray( this.getValueFromReference() ) ) {
  8198. node = uniformArray( null, uniformType );
  8199. } else if ( uniformType === 'texture' ) {
  8200. node = texture( null );
  8201. } else if ( uniformType === 'cubeTexture' ) {
  8202. node = cubeTexture( null );
  8203. } else {
  8204. node = uniform( null, uniformType );
  8205. }
  8206. if ( this.group !== null ) {
  8207. node.setGroup( this.group );
  8208. }
  8209. if ( this.name !== null ) node.label( this.name );
  8210. this.node = node.getSelf();
  8211. }
  8212. /**
  8213. * This method is overwritten since the node type is inferred from
  8214. * the type of the reference node.
  8215. *
  8216. * @param {NodeBuilder} builder - The current node builder.
  8217. * @return {String} The node type.
  8218. */
  8219. getNodeType( builder ) {
  8220. if ( this.node === null ) {
  8221. this.updateReference( builder );
  8222. this.updateValue();
  8223. }
  8224. return this.node.getNodeType( builder );
  8225. }
  8226. /**
  8227. * Returns the property value from the given referred object.
  8228. *
  8229. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  8230. * @return {Any} The value.
  8231. */
  8232. getValueFromReference( object = this.reference ) {
  8233. const { properties } = this;
  8234. let value = object[ properties[ 0 ] ];
  8235. for ( let i = 1; i < properties.length; i ++ ) {
  8236. value = value[ properties[ i ] ];
  8237. }
  8238. return value;
  8239. }
  8240. /**
  8241. * Allows to update the reference based on the given state. The state is only
  8242. * evaluated {@link module:ReferenceNode~ReferenceNode#object} is not set.
  8243. *
  8244. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  8245. * @return {Object} The updated reference.
  8246. */
  8247. updateReference( state ) {
  8248. this.reference = this.object !== null ? this.object : state.object;
  8249. return this.reference;
  8250. }
  8251. /**
  8252. * The output of the reference node is the internal uniform node.
  8253. *
  8254. * @param {NodeBuilder} builder - The current node builder.
  8255. * @return {UniformNode} The output node.
  8256. */
  8257. setup( /* builder */ ) {
  8258. this.updateValue();
  8259. return this.node;
  8260. }
  8261. /**
  8262. * Overwritten to to update the internal uniform value.
  8263. *
  8264. * @param {NodeFrame} frame - A reference to the current node frame.
  8265. */
  8266. update( /*frame*/ ) {
  8267. this.updateValue();
  8268. }
  8269. /**
  8270. * Retrieves the value from the referred object property and uses it
  8271. * to updated the internal uniform.
  8272. */
  8273. updateValue() {
  8274. if ( this.node === null ) this.setNodeType( this.uniformType );
  8275. const value = this.getValueFromReference();
  8276. if ( Array.isArray( value ) ) {
  8277. this.node.array = value;
  8278. } else {
  8279. this.node.value = value;
  8280. }
  8281. }
  8282. }
  8283. /**
  8284. * TSL function for creating a reference node.
  8285. *
  8286. * @function
  8287. * @param {String} name - The name of the property the node refers to.
  8288. * @param {String} type - The uniform type that should be used to represent the property value.
  8289. * @param {Object} object - The object the property belongs to.
  8290. * @returns {ReferenceNode}
  8291. */
  8292. const reference = ( name, type, object ) => nodeObject( new ReferenceNode( name, type, object ) );
  8293. /**
  8294. * TSL function for creating a reference node. Use this function if you want need a reference
  8295. * to an array-like property that should be represented as a uniform buffer.
  8296. *
  8297. * @function
  8298. * @param {String} name - The name of the property the node refers to.
  8299. * @param {String} type - The uniform type that should be used to represent the property value.
  8300. * @param {Number} count - The number of value inside the array-like object.
  8301. * @param {Object} object - An array-like object the property belongs to.
  8302. * @returns {ReferenceNode}
  8303. */
  8304. const referenceBuffer = ( name, type, count, object ) => nodeObject( new ReferenceNode( name, type, object, count ) );
  8305. /** @module MaterialReferenceNode **/
  8306. /**
  8307. * This node is a special type of reference node which is intended
  8308. * for linking material properties with node values.
  8309. * ```js
  8310. * const opacityNode = materialReference( 'opacity', 'float', material );
  8311. * ```
  8312. * When changing `material.opacity`, the node value of `opacityNode` will
  8313. * automatically be updated.
  8314. *
  8315. * @augments module:ReferenceNode~ReferenceNode
  8316. */
  8317. class MaterialReferenceNode extends ReferenceNode {
  8318. static get type() {
  8319. return 'MaterialReferenceNode';
  8320. }
  8321. /**
  8322. * Constructs a new material reference node.
  8323. *
  8324. * @param {String} property - The name of the property the node refers to.
  8325. * @param {String} inputType - The uniform type that should be used to represent the property value.
  8326. * @param {Material?} [material=null] - The material the property belongs to. When no material is set,
  8327. * the node refers to the material of the current rendered object.
  8328. */
  8329. constructor( property, inputType, material = null ) {
  8330. super( property, inputType, material );
  8331. /**
  8332. * The material the property belongs to. When no material is set,
  8333. * the node refers to the material of the current rendered object.
  8334. *
  8335. * @type {Material?}
  8336. * @default null
  8337. */
  8338. this.material = material;
  8339. /**
  8340. * This flag can be used for type testing.
  8341. *
  8342. * @type {Boolean}
  8343. * @readonly
  8344. * @default true
  8345. */
  8346. this.isMaterialReferenceNode = true;
  8347. }
  8348. /**
  8349. * Updates the reference based on the given state. The state is only evaluated
  8350. * {@link module:MaterialReferenceNode~MaterialReferenceNode#material} is not set.
  8351. *
  8352. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  8353. * @return {Object} The updated reference.
  8354. */
  8355. updateReference( state ) {
  8356. this.reference = this.material !== null ? this.material : state.material;
  8357. return this.reference;
  8358. }
  8359. }
  8360. /**
  8361. * TSL function for creating a material reference node.
  8362. *
  8363. * @function
  8364. * @param {String} name - The name of the property the node refers to.
  8365. * @param {String} type - The uniform type that should be used to represent the property value.
  8366. * @param {Material?} [material=null] - The material the property belongs to.
  8367. * When no material is set, the node refers to the material of the current rendered object.
  8368. * @returns {MaterialReferenceNode}
  8369. */
  8370. const materialReference = ( name, type, material = null ) => nodeObject( new MaterialReferenceNode( name, type, material ) );
  8371. /** @module Tangent **/
  8372. /**
  8373. * TSL object that represents the tangent attribute of the current rendered object.
  8374. *
  8375. * @type {Node<vec4>}
  8376. */
  8377. const tangentGeometry = /*@__PURE__*/ Fn( ( builder ) => {
  8378. if ( builder.geometry.hasAttribute( 'tangent' ) === false ) {
  8379. builder.geometry.computeTangents();
  8380. }
  8381. return attribute( 'tangent', 'vec4' );
  8382. } )();
  8383. /**
  8384. * TSL object that represents the vertex tangent in local space of the current rendered object.
  8385. *
  8386. * @type {Node<vec3>}
  8387. */
  8388. const tangentLocal = /*@__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' );
  8389. /**
  8390. * TSL object that represents the vertex tangent in view space of the current rendered object.
  8391. *
  8392. * @type {Node<vec3>}
  8393. */
  8394. const tangentView = /*@__PURE__*/ modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz.toVarying( 'v_tangentView' ).normalize().toVar( 'tangentView' );
  8395. /**
  8396. * TSL object that represents the vertex tangent in world space of the current rendered object.
  8397. *
  8398. * @type {Node<vec3>}
  8399. */
  8400. const tangentWorld = /*@__PURE__*/ tangentView.transformDirection( cameraViewMatrix ).toVarying( 'v_tangentWorld' ).normalize().toVar( 'tangentWorld' );
  8401. /**
  8402. * TSL object that represents the transformed vertex tangent in view space of the current rendered object.
  8403. *
  8404. * @type {Node<vec3>}
  8405. */
  8406. const transformedTangentView = /*@__PURE__*/ tangentView.toVar( 'transformedTangentView' );
  8407. /**
  8408. * TSL object that represents the transformed vertex tangent in world space of the current rendered object.
  8409. *
  8410. * @type {Node<vec3>}
  8411. */
  8412. const transformedTangentWorld = /*@__PURE__*/ transformedTangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedTangentWorld' );
  8413. /** @module Bitangent **/
  8414. const getBitangent = ( crossNormalTangent ) => crossNormalTangent.mul( tangentGeometry.w ).xyz;
  8415. /**
  8416. * TSL object that represents the bitangent attribute of the current rendered object.
  8417. *
  8418. * @type {Node<vec3>}
  8419. */
  8420. const bitangentGeometry = /*@__PURE__*/ varying( getBitangent( normalGeometry.cross( tangentGeometry ) ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' );
  8421. /**
  8422. * TSL object that represents the vertex bitangent in local space of the current rendered object.
  8423. *
  8424. * @type {Node<vec3>}
  8425. */
  8426. const bitangentLocal = /*@__PURE__*/ varying( getBitangent( normalLocal.cross( tangentLocal ) ), 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' );
  8427. /**
  8428. * TSL object that represents the vertex bitangent in view space of the current rendered object.
  8429. *
  8430. * @type {Node<vec4>}
  8431. */
  8432. const bitangentView = /*@__PURE__*/ varying( getBitangent( normalView.cross( tangentView ) ), 'v_bitangentView' ).normalize().toVar( 'bitangentView' );
  8433. /**
  8434. * TSL object that represents the vertex bitangent in world space of the current rendered object.
  8435. *
  8436. * @type {Node<vec4>}
  8437. */
  8438. const bitangentWorld = /*@__PURE__*/ varying( getBitangent( normalWorld.cross( tangentWorld ) ), 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' );
  8439. /**
  8440. * TSL object that represents the transformed vertex bitangent in view space of the current rendered object.
  8441. *
  8442. * @type {Node<vec4>}
  8443. */
  8444. const transformedBitangentView = /*@__PURE__*/ getBitangent( transformedNormalView.cross( transformedTangentView ) ).normalize().toVar( 'transformedBitangentView' );
  8445. /**
  8446. * TSL object that represents the transformed vertex bitangent in world space of the current rendered object.
  8447. *
  8448. * @type {Node<vec4>}
  8449. */
  8450. const transformedBitangentWorld = /*@__PURE__*/ transformedBitangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedBitangentWorld' );
  8451. /** @module AccessorsUtils **/
  8452. /**
  8453. * TSL object that represents the TBN matrix in view space.
  8454. *
  8455. * @type {Node<mat3>}
  8456. */
  8457. const TBNViewMatrix = /*@__PURE__*/ mat3( tangentView, bitangentView, normalView );
  8458. /**
  8459. * TSL object that represents the parallax direction.
  8460. *
  8461. * @type {Node<mat3>}
  8462. */
  8463. const parallaxDirection = /*@__PURE__*/ positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/;
  8464. /**
  8465. * TSL function for computing parallax uv coordinates.
  8466. *
  8467. * @function
  8468. * @param {Node<vec2>} uv - A uv node.
  8469. * @param {Node<vec2>} scale - A scale node.
  8470. * @returns {Node<vec2>} Parallax uv coordinates.
  8471. */
  8472. const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) );
  8473. /**
  8474. * TSL function for computing bent normals.
  8475. *
  8476. * @function
  8477. * @returns {Node<vec3>} Bent normals.
  8478. */
  8479. const transformedBentNormalView = /*@__PURE__*/ ( () => {
  8480. // https://google.github.io/filament/Filament.md.html#lighting/imagebasedlights/anisotropy
  8481. let bentNormal = anisotropyB.cross( positionViewDirection );
  8482. bentNormal = bentNormal.cross( anisotropyB ).normalize();
  8483. bentNormal = mix( bentNormal, transformedNormalView, anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2() ).normalize();
  8484. return bentNormal;
  8485. } )();
  8486. /** @module NormalMapNode **/
  8487. // Normal Mapping Without Precomputed Tangents
  8488. // http://www.thetenthplanet.de/archives/1180
  8489. const perturbNormal2Arb = /*@__PURE__*/ Fn( ( inputs ) => {
  8490. const { eye_pos, surf_norm, mapN, uv } = inputs;
  8491. const q0 = eye_pos.dFdx();
  8492. const q1 = eye_pos.dFdy();
  8493. const st0 = uv.dFdx();
  8494. const st1 = uv.dFdy();
  8495. const N = surf_norm; // normalized
  8496. const q1perp = q1.cross( N );
  8497. const q0perp = N.cross( q0 );
  8498. const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) );
  8499. const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) );
  8500. const det = T.dot( T ).max( B.dot( B ) );
  8501. const scale = faceDirection.mul( det.inverseSqrt() );
  8502. return add( T.mul( mapN.x, scale ), B.mul( mapN.y, scale ), N.mul( mapN.z ) ).normalize();
  8503. } );
  8504. /**
  8505. * This class can be used for applying normals maps to materials.
  8506. *
  8507. * ```js
  8508. * material.normalNode = normalMap( texture( normalTex ) );
  8509. * ```
  8510. *
  8511. * @augments TempNode
  8512. */
  8513. class NormalMapNode extends TempNode {
  8514. static get type() {
  8515. return 'NormalMapNode';
  8516. }
  8517. /**
  8518. * Constructs a new normal map node.
  8519. *
  8520. * @param {Node<vec3>} node - Represents the normal map data.
  8521. * @param {Node<vec2>?} [scaleNode=null] - Controls the intensity of the effect.
  8522. */
  8523. constructor( node, scaleNode = null ) {
  8524. super( 'vec3' );
  8525. /**
  8526. * Represents the normal map data.
  8527. *
  8528. * @type {Node<vec3>}
  8529. */
  8530. this.node = node;
  8531. /**
  8532. * Controls the intensity of the effect.
  8533. *
  8534. * @type {Node<vec2>?}
  8535. * @default null
  8536. */
  8537. this.scaleNode = scaleNode;
  8538. /**
  8539. * The normal map type.
  8540. *
  8541. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  8542. * @default TangentSpaceNormalMap
  8543. */
  8544. this.normalMapType = TangentSpaceNormalMap;
  8545. }
  8546. setup( builder ) {
  8547. const { normalMapType, scaleNode } = this;
  8548. let normalMap = this.node.mul( 2.0 ).sub( 1.0 );
  8549. if ( scaleNode !== null ) {
  8550. normalMap = vec3( normalMap.xy.mul( scaleNode ), normalMap.z );
  8551. }
  8552. let outputNode = null;
  8553. if ( normalMapType === ObjectSpaceNormalMap ) {
  8554. outputNode = transformNormalToView( normalMap );
  8555. } else if ( normalMapType === TangentSpaceNormalMap ) {
  8556. const tangent = builder.hasGeometryAttribute( 'tangent' );
  8557. if ( tangent === true ) {
  8558. outputNode = TBNViewMatrix.mul( normalMap ).normalize();
  8559. } else {
  8560. outputNode = perturbNormal2Arb( {
  8561. eye_pos: positionView,
  8562. surf_norm: normalView,
  8563. mapN: normalMap,
  8564. uv: uv()
  8565. } );
  8566. }
  8567. }
  8568. return outputNode;
  8569. }
  8570. }
  8571. /**
  8572. * TSL function for creating a normal map node.
  8573. *
  8574. * @function
  8575. * @param {Node<vec3>} node - Represents the normal map data.
  8576. * @param {Node<vec2>?} [scaleNode=null] - Controls the intensity of the effect.
  8577. * @returns {NormalMapNode}
  8578. */
  8579. const normalMap = /*@__PURE__*/ nodeProxy( NormalMapNode );
  8580. /** @module BumpMapNode **/
  8581. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  8582. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  8583. const dHdxy_fwd = Fn( ( { textureNode, bumpScale } ) => {
  8584. // It's used to preserve the same TextureNode instance
  8585. const sampleTexture = ( callback ) => textureNode.cache().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv() ), forceUVContext: true } );
  8586. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  8587. return vec2(
  8588. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  8589. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  8590. ).mul( bumpScale );
  8591. } );
  8592. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  8593. const perturbNormalArb = Fn( ( inputs ) => {
  8594. const { surf_pos, surf_norm, dHdxy } = inputs;
  8595. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  8596. const vSigmaX = surf_pos.dFdx().normalize();
  8597. const vSigmaY = surf_pos.dFdy().normalize();
  8598. const vN = surf_norm; // normalized
  8599. const R1 = vSigmaY.cross( vN );
  8600. const R2 = vN.cross( vSigmaX );
  8601. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  8602. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  8603. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  8604. } );
  8605. /**
  8606. * This class can be used for applying bump maps to materials.
  8607. *
  8608. * ```js
  8609. * material.normalNode = bumpMap( texture( bumpTex ) );
  8610. * ```
  8611. *
  8612. * @augments TempNode
  8613. */
  8614. class BumpMapNode extends TempNode {
  8615. static get type() {
  8616. return 'BumpMapNode';
  8617. }
  8618. /**
  8619. * Constructs a new bump map node.
  8620. *
  8621. * @param {Node<float>} textureNode - Represents the bump map data.
  8622. * @param {Node<float>?} [scaleNode=null] - Controls the intensity of the bump effect.
  8623. */
  8624. constructor( textureNode, scaleNode = null ) {
  8625. super( 'vec3' );
  8626. /**
  8627. * Represents the bump map data.
  8628. *
  8629. * @type {Node<float>}
  8630. */
  8631. this.textureNode = textureNode;
  8632. /**
  8633. * Controls the intensity of the bump effect.
  8634. *
  8635. * @type {Node<float>?}
  8636. * @default null
  8637. */
  8638. this.scaleNode = scaleNode;
  8639. }
  8640. setup() {
  8641. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  8642. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  8643. return perturbNormalArb( {
  8644. surf_pos: positionView,
  8645. surf_norm: normalView,
  8646. dHdxy
  8647. } );
  8648. }
  8649. }
  8650. /**
  8651. * TSL function for creating a bump map node.
  8652. *
  8653. * @function
  8654. * @param {Node<float>} textureNode - Represents the bump map data.
  8655. * @param {Node<float>?} [scaleNode=null] - Controls the intensity of the bump effect.
  8656. * @returns {BumpMapNode}
  8657. */
  8658. const bumpMap = /*@__PURE__*/ nodeProxy( BumpMapNode );
  8659. /** @module MaterialNode **/
  8660. const _propertyCache = new Map();
  8661. /**
  8662. * This class should simplify the node access to material properties.
  8663. * It internal uses reference nodes to make sure changes to material
  8664. * properties are automatically reflected to predefined TSL objects
  8665. * like e.g. `materialColor`.
  8666. *
  8667. * @augments Node
  8668. */
  8669. class MaterialNode extends Node {
  8670. static get type() {
  8671. return 'MaterialNode';
  8672. }
  8673. /**
  8674. * Constructs a new material node.
  8675. *
  8676. * @param {String} scope - The scope defines what kind of material property is referred by the node.
  8677. */
  8678. constructor( scope ) {
  8679. super();
  8680. /**
  8681. * The scope defines what material property is referred by the node.
  8682. *
  8683. * @type {String}
  8684. */
  8685. this.scope = scope;
  8686. }
  8687. /**
  8688. * Returns a cached reference node for the given property and type.
  8689. *
  8690. * @param {String} property - The name of the material property.
  8691. * @param {String} type - The uniform type of the property.
  8692. * @return {MaterialReferenceNode} A material reference node representing the property access.
  8693. */
  8694. getCache( property, type ) {
  8695. let node = _propertyCache.get( property );
  8696. if ( node === undefined ) {
  8697. node = materialReference( property, type );
  8698. _propertyCache.set( property, node );
  8699. }
  8700. return node;
  8701. }
  8702. /**
  8703. * Returns a float-typed material reference node for the given property name.
  8704. *
  8705. * @param {String} property - The name of the material property.
  8706. * @return {MaterialReferenceNode<float>} A material reference node representing the property access.
  8707. */
  8708. getFloat( property ) {
  8709. return this.getCache( property, 'float' );
  8710. }
  8711. /**
  8712. * Returns a color-typed material reference node for the given property name.
  8713. *
  8714. * @param {String} property - The name of the material property.
  8715. * @return {MaterialReferenceNode<color>} A material reference node representing the property access.
  8716. */
  8717. getColor( property ) {
  8718. return this.getCache( property, 'color' );
  8719. }
  8720. /**
  8721. * Returns a texture-typed material reference node for the given property name.
  8722. *
  8723. * @param {String} property - The name of the material property.
  8724. * @return {MaterialReferenceNode} A material reference node representing the property access.
  8725. */
  8726. getTexture( property ) {
  8727. return this.getCache( property === 'map' ? 'map' : property + 'Map', 'texture' );
  8728. }
  8729. /**
  8730. * The node setup is done depending on the selected scope. Multiple material properties
  8731. * might be grouped into a single node composition if they logically belong together.
  8732. *
  8733. * @param {NodeBuilder} builder - The current node builder.
  8734. * @return {Node} The node representing the selected scope.
  8735. */
  8736. setup( builder ) {
  8737. const material = builder.context.material;
  8738. const scope = this.scope;
  8739. let node = null;
  8740. if ( scope === MaterialNode.COLOR ) {
  8741. const colorNode = material.color !== undefined ? this.getColor( scope ) : vec3();
  8742. if ( material.map && material.map.isTexture === true ) {
  8743. node = colorNode.mul( this.getTexture( 'map' ) );
  8744. } else {
  8745. node = colorNode;
  8746. }
  8747. } else if ( scope === MaterialNode.OPACITY ) {
  8748. const opacityNode = this.getFloat( scope );
  8749. if ( material.alphaMap && material.alphaMap.isTexture === true ) {
  8750. node = opacityNode.mul( this.getTexture( 'alpha' ) );
  8751. } else {
  8752. node = opacityNode;
  8753. }
  8754. } else if ( scope === MaterialNode.SPECULAR_STRENGTH ) {
  8755. if ( material.specularMap && material.specularMap.isTexture === true ) {
  8756. node = this.getTexture( 'specular' ).r;
  8757. } else {
  8758. node = float( 1 );
  8759. }
  8760. } else if ( scope === MaterialNode.SPECULAR_INTENSITY ) {
  8761. const specularIntensityNode = this.getFloat( scope );
  8762. if ( material.specularIntensityMap && material.specularIntensityMap.isTexture === true ) {
  8763. node = specularIntensityNode.mul( this.getTexture( scope ).a );
  8764. } else {
  8765. node = specularIntensityNode;
  8766. }
  8767. } else if ( scope === MaterialNode.SPECULAR_COLOR ) {
  8768. const specularColorNode = this.getColor( scope );
  8769. if ( material.specularColorMap && material.specularColorMap.isTexture === true ) {
  8770. node = specularColorNode.mul( this.getTexture( scope ).rgb );
  8771. } else {
  8772. node = specularColorNode;
  8773. }
  8774. } else if ( scope === MaterialNode.ROUGHNESS ) { // TODO: cleanup similar branches
  8775. const roughnessNode = this.getFloat( scope );
  8776. if ( material.roughnessMap && material.roughnessMap.isTexture === true ) {
  8777. node = roughnessNode.mul( this.getTexture( scope ).g );
  8778. } else {
  8779. node = roughnessNode;
  8780. }
  8781. } else if ( scope === MaterialNode.METALNESS ) {
  8782. const metalnessNode = this.getFloat( scope );
  8783. if ( material.metalnessMap && material.metalnessMap.isTexture === true ) {
  8784. node = metalnessNode.mul( this.getTexture( scope ).b );
  8785. } else {
  8786. node = metalnessNode;
  8787. }
  8788. } else if ( scope === MaterialNode.EMISSIVE ) {
  8789. const emissiveIntensityNode = this.getFloat( 'emissiveIntensity' );
  8790. const emissiveNode = this.getColor( scope ).mul( emissiveIntensityNode );
  8791. if ( material.emissiveMap && material.emissiveMap.isTexture === true ) {
  8792. node = emissiveNode.mul( this.getTexture( scope ) );
  8793. } else {
  8794. node = emissiveNode;
  8795. }
  8796. } else if ( scope === MaterialNode.NORMAL ) {
  8797. if ( material.normalMap ) {
  8798. node = normalMap( this.getTexture( 'normal' ), this.getCache( 'normalScale', 'vec2' ) );
  8799. node.normalMapType = material.normalMapType;
  8800. } else if ( material.bumpMap ) {
  8801. node = bumpMap( this.getTexture( 'bump' ).r, this.getFloat( 'bumpScale' ) );
  8802. } else {
  8803. node = normalView;
  8804. }
  8805. } else if ( scope === MaterialNode.CLEARCOAT ) {
  8806. const clearcoatNode = this.getFloat( scope );
  8807. if ( material.clearcoatMap && material.clearcoatMap.isTexture === true ) {
  8808. node = clearcoatNode.mul( this.getTexture( scope ).r );
  8809. } else {
  8810. node = clearcoatNode;
  8811. }
  8812. } else if ( scope === MaterialNode.CLEARCOAT_ROUGHNESS ) {
  8813. const clearcoatRoughnessNode = this.getFloat( scope );
  8814. if ( material.clearcoatRoughnessMap && material.clearcoatRoughnessMap.isTexture === true ) {
  8815. node = clearcoatRoughnessNode.mul( this.getTexture( scope ).r );
  8816. } else {
  8817. node = clearcoatRoughnessNode;
  8818. }
  8819. } else if ( scope === MaterialNode.CLEARCOAT_NORMAL ) {
  8820. if ( material.clearcoatNormalMap ) {
  8821. node = normalMap( this.getTexture( scope ), this.getCache( scope + 'Scale', 'vec2' ) );
  8822. } else {
  8823. node = normalView;
  8824. }
  8825. } else if ( scope === MaterialNode.SHEEN ) {
  8826. const sheenNode = this.getColor( 'sheenColor' ).mul( this.getFloat( 'sheen' ) ); // Move this mul() to CPU
  8827. if ( material.sheenColorMap && material.sheenColorMap.isTexture === true ) {
  8828. node = sheenNode.mul( this.getTexture( 'sheenColor' ).rgb );
  8829. } else {
  8830. node = sheenNode;
  8831. }
  8832. } else if ( scope === MaterialNode.SHEEN_ROUGHNESS ) {
  8833. const sheenRoughnessNode = this.getFloat( scope );
  8834. if ( material.sheenRoughnessMap && material.sheenRoughnessMap.isTexture === true ) {
  8835. node = sheenRoughnessNode.mul( this.getTexture( scope ).a );
  8836. } else {
  8837. node = sheenRoughnessNode;
  8838. }
  8839. node = node.clamp( 0.07, 1.0 );
  8840. } else if ( scope === MaterialNode.ANISOTROPY ) {
  8841. if ( material.anisotropyMap && material.anisotropyMap.isTexture === true ) {
  8842. const anisotropyPolar = this.getTexture( scope );
  8843. const anisotropyMat = mat2( materialAnisotropyVector.x, materialAnisotropyVector.y, materialAnisotropyVector.y.negate(), materialAnisotropyVector.x );
  8844. node = anisotropyMat.mul( anisotropyPolar.rg.mul( 2.0 ).sub( vec2( 1.0 ) ).normalize().mul( anisotropyPolar.b ) );
  8845. } else {
  8846. node = materialAnisotropyVector;
  8847. }
  8848. } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) {
  8849. const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange );
  8850. if ( material.iridescenceThicknessMap ) {
  8851. const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange );
  8852. node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum );
  8853. } else {
  8854. node = iridescenceThicknessMaximum;
  8855. }
  8856. } else if ( scope === MaterialNode.TRANSMISSION ) {
  8857. const transmissionNode = this.getFloat( scope );
  8858. if ( material.transmissionMap ) {
  8859. node = transmissionNode.mul( this.getTexture( scope ).r );
  8860. } else {
  8861. node = transmissionNode;
  8862. }
  8863. } else if ( scope === MaterialNode.THICKNESS ) {
  8864. const thicknessNode = this.getFloat( scope );
  8865. if ( material.thicknessMap ) {
  8866. node = thicknessNode.mul( this.getTexture( scope ).g );
  8867. } else {
  8868. node = thicknessNode;
  8869. }
  8870. } else if ( scope === MaterialNode.IOR ) {
  8871. node = this.getFloat( scope );
  8872. } else if ( scope === MaterialNode.LIGHT_MAP ) {
  8873. node = this.getTexture( scope ).rgb.mul( this.getFloat( 'lightMapIntensity' ) );
  8874. } else if ( scope === MaterialNode.AO ) {
  8875. node = this.getTexture( scope ).r.sub( 1.0 ).mul( this.getFloat( 'aoMapIntensity' ) ).add( 1.0 );
  8876. } else {
  8877. const outputType = this.getNodeType( builder );
  8878. node = this.getCache( scope, outputType );
  8879. }
  8880. return node;
  8881. }
  8882. }
  8883. MaterialNode.ALPHA_TEST = 'alphaTest';
  8884. MaterialNode.COLOR = 'color';
  8885. MaterialNode.OPACITY = 'opacity';
  8886. MaterialNode.SHININESS = 'shininess';
  8887. MaterialNode.SPECULAR = 'specular';
  8888. MaterialNode.SPECULAR_STRENGTH = 'specularStrength';
  8889. MaterialNode.SPECULAR_INTENSITY = 'specularIntensity';
  8890. MaterialNode.SPECULAR_COLOR = 'specularColor';
  8891. MaterialNode.REFLECTIVITY = 'reflectivity';
  8892. MaterialNode.ROUGHNESS = 'roughness';
  8893. MaterialNode.METALNESS = 'metalness';
  8894. MaterialNode.NORMAL = 'normal';
  8895. MaterialNode.CLEARCOAT = 'clearcoat';
  8896. MaterialNode.CLEARCOAT_ROUGHNESS = 'clearcoatRoughness';
  8897. MaterialNode.CLEARCOAT_NORMAL = 'clearcoatNormal';
  8898. MaterialNode.EMISSIVE = 'emissive';
  8899. MaterialNode.ROTATION = 'rotation';
  8900. MaterialNode.SHEEN = 'sheen';
  8901. MaterialNode.SHEEN_ROUGHNESS = 'sheenRoughness';
  8902. MaterialNode.ANISOTROPY = 'anisotropy';
  8903. MaterialNode.IRIDESCENCE = 'iridescence';
  8904. MaterialNode.IRIDESCENCE_IOR = 'iridescenceIOR';
  8905. MaterialNode.IRIDESCENCE_THICKNESS = 'iridescenceThickness';
  8906. MaterialNode.IOR = 'ior';
  8907. MaterialNode.TRANSMISSION = 'transmission';
  8908. MaterialNode.THICKNESS = 'thickness';
  8909. MaterialNode.ATTENUATION_DISTANCE = 'attenuationDistance';
  8910. MaterialNode.ATTENUATION_COLOR = 'attenuationColor';
  8911. MaterialNode.LINE_SCALE = 'scale';
  8912. MaterialNode.LINE_DASH_SIZE = 'dashSize';
  8913. MaterialNode.LINE_GAP_SIZE = 'gapSize';
  8914. MaterialNode.LINE_WIDTH = 'linewidth';
  8915. MaterialNode.LINE_DASH_OFFSET = 'dashOffset';
  8916. MaterialNode.POINT_SIZE = 'size';
  8917. MaterialNode.DISPERSION = 'dispersion';
  8918. MaterialNode.LIGHT_MAP = 'light';
  8919. MaterialNode.AO = 'ao';
  8920. /**
  8921. * TSL object that represents alpha test of the current material.
  8922. *
  8923. * @type {Node<float>}
  8924. */
  8925. const materialAlphaTest = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ALPHA_TEST );
  8926. /**
  8927. * TSL object that represents the diffuse color of the current material.
  8928. * The value is composed via `color` * `map`.
  8929. *
  8930. * @type {Node<vec3>}
  8931. */
  8932. const materialColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.COLOR );
  8933. /**
  8934. * TSL object that represents the shininess of the current material.
  8935. *
  8936. * @type {Node<float>}
  8937. */
  8938. const materialShininess = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHININESS );
  8939. /**
  8940. * TSL object that represents the emissive color of the current material.
  8941. * The value is composed via `emissive` * `emissiveIntensity` * `emissiveMap`.
  8942. *
  8943. * @type {Node<vec3>}
  8944. */
  8945. const materialEmissive = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.EMISSIVE );
  8946. /**
  8947. * TSL object that represents the opacity of the current material.
  8948. * The value is composed via `opacity` * `alphaMap`.
  8949. *
  8950. * @type {Node<float>}
  8951. */
  8952. const materialOpacity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.OPACITY );
  8953. /**
  8954. * TSL object that represents the specular of the current material.
  8955. *
  8956. * @type {Node<vec3>}
  8957. */
  8958. const materialSpecular = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR );
  8959. /**
  8960. * TSL object that represents the specular intensity of the current material.
  8961. * The value is composed via `specularIntensity` * `specularMap.a`.
  8962. *
  8963. * @type {Node<float>}
  8964. */
  8965. const materialSpecularIntensity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_INTENSITY );
  8966. /**
  8967. * TSL object that represents the specular color of the current material.
  8968. * The value is composed via `specularColor` * `specularMap.rgb`.
  8969. *
  8970. * @type {Node<vec3>}
  8971. */
  8972. const materialSpecularColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_COLOR );
  8973. /**
  8974. * TSL object that represents the specular strength of the current material.
  8975. * The value is composed via `specularMap.r`.
  8976. *
  8977. * @type {Node<float>}
  8978. */
  8979. const materialSpecularStrength = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_STRENGTH );
  8980. /**
  8981. * TSL object that represents the reflectivity of the current material.
  8982. *
  8983. * @type {Node<float>}
  8984. */
  8985. const materialReflectivity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.REFLECTIVITY );
  8986. /**
  8987. * TSL object that represents the roughness of the current material.
  8988. * The value is composed via `roughness` * `roughnessMap.g`.
  8989. *
  8990. * @type {Node<float>}
  8991. */
  8992. const materialRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROUGHNESS );
  8993. /**
  8994. * TSL object that represents the metalness of the current material.
  8995. * The value is composed via `metalness` * `metalnessMap.b`.
  8996. *
  8997. * @type {Node<float>}
  8998. */
  8999. const materialMetalness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.METALNESS );
  9000. /**
  9001. * TSL object that represents the normal of the current material.
  9002. * The value will be either `normalMap` * `normalScale`, `bumpMap` * `bumpScale` or `normalView`.
  9003. *
  9004. * @type {Node<vec3>}
  9005. */
  9006. const materialNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.NORMAL );
  9007. /**
  9008. * TSL object that represents the clearcoat of the current material.
  9009. * The value is composed via `clearcoat` * `clearcoatMap.r`
  9010. *
  9011. * @type {Node<float>}
  9012. */
  9013. const materialClearcoat = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT );
  9014. /**
  9015. * TSL object that represents the clearcoat roughness of the current material.
  9016. * The value is composed via `clearcoatRoughness` * `clearcoatRoughnessMap.r`.
  9017. *
  9018. * @type {Node<float>}
  9019. */
  9020. const materialClearcoatRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_ROUGHNESS );
  9021. /**
  9022. * TSL object that represents the clearcoat normal of the current material.
  9023. * The value will be either `clearcoatNormalMap` or `normalView`.
  9024. *
  9025. * @type {Node<vec3>}
  9026. */
  9027. const materialClearcoatNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_NORMAL );
  9028. /**
  9029. * TSL object that represents the rotation of the current sprite material.
  9030. *
  9031. * @type {Node<float>}
  9032. */
  9033. const materialRotation = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROTATION );
  9034. /**
  9035. * TSL object that represents the sheen color of the current material.
  9036. * The value is composed via `sheen` * `sheenColor` * `sheenColorMap`.
  9037. *
  9038. * @type {Node<vec3>}
  9039. */
  9040. const materialSheen = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN );
  9041. /**
  9042. * TSL object that represents the sheen roughness of the current material.
  9043. * The value is composed via `sheenRoughness` * `sheenRoughnessMap.a`.
  9044. *
  9045. * @type {Node<float>}
  9046. */
  9047. const materialSheenRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN_ROUGHNESS );
  9048. /**
  9049. * TSL object that represents the anisotropy of the current material.
  9050. *
  9051. * @type {Node<vec2>}
  9052. */
  9053. const materialAnisotropy = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ANISOTROPY );
  9054. /**
  9055. * TSL object that represents the iridescence of the current material.
  9056. *
  9057. * @type {Node<float>}
  9058. */
  9059. const materialIridescence = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE );
  9060. /**
  9061. * TSL object that represents the iridescence IOR of the current material.
  9062. *
  9063. * @type {Node<float>}
  9064. */
  9065. const materialIridescenceIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_IOR );
  9066. /**
  9067. * TSL object that represents the iridescence thickness of the current material.
  9068. *
  9069. * @type {Node<float>}
  9070. */
  9071. const materialIridescenceThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_THICKNESS );
  9072. /**
  9073. * TSL object that represents the transmission of the current material.
  9074. * The value is composed via `transmission` * `transmissionMap.r`.
  9075. *
  9076. * @type {Node<float>}
  9077. */
  9078. const materialTransmission = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.TRANSMISSION );
  9079. /**
  9080. * TSL object that represents the thickness of the current material.
  9081. * The value is composed via `thickness` * `thicknessMap.g`.
  9082. *
  9083. * @type {Node<float>}
  9084. */
  9085. const materialThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.THICKNESS );
  9086. /**
  9087. * TSL object that represents the IOR of the current material.
  9088. *
  9089. * @type {Node<float>}
  9090. */
  9091. const materialIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IOR );
  9092. /**
  9093. * TSL object that represents the attenuation distance of the current material.
  9094. *
  9095. * @type {Node<float>}
  9096. */
  9097. const materialAttenuationDistance = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_DISTANCE );
  9098. /**
  9099. * TSL object that represents the attenuation color of the current material.
  9100. *
  9101. * @type {Node<vec3>}
  9102. */
  9103. const materialAttenuationColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_COLOR );
  9104. /**
  9105. * TSL object that represents the scale of the current dashed line material.
  9106. *
  9107. * @type {Node<float>}
  9108. */
  9109. const materialLineScale = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_SCALE );
  9110. /**
  9111. * TSL object that represents the dash size of the current dashed line material.
  9112. *
  9113. * @type {Node<float>}
  9114. */
  9115. const materialLineDashSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_SIZE );
  9116. /**
  9117. * TSL object that represents the gap size of the current dashed line material.
  9118. *
  9119. * @type {Node<float>}
  9120. */
  9121. const materialLineGapSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_GAP_SIZE );
  9122. /**
  9123. * TSL object that represents the line width of the current line material.
  9124. *
  9125. * @type {Node<float>}
  9126. */
  9127. const materialLineWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_WIDTH );
  9128. /**
  9129. * TSL object that represents the dash offset of the current line material.
  9130. *
  9131. * @type {Node<float>}
  9132. */
  9133. const materialLineDashOffset = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_OFFSET );
  9134. /**
  9135. * TSL object that represents the point size of the current points material.
  9136. *
  9137. * @type {Node<float>}
  9138. */
  9139. const materialPointSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.POINT_SIZE );
  9140. /**
  9141. * TSL object that represents the dispersion of the current material.
  9142. *
  9143. * @type {Node<float>}
  9144. */
  9145. const materialDispersion = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.DISPERSION );
  9146. /**
  9147. * TSL object that represents the light map of the current material.
  9148. * The value is composed via `lightMapIntensity` * `lightMap.rgb`.
  9149. *
  9150. * @type {Node<vec3>}
  9151. */
  9152. const materialLightMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LIGHT_MAP );
  9153. /**
  9154. * TSL object that represents the ambient occlusion map of the current material.
  9155. * The value is composed via `aoMap.r` - 1 * `aoMapIntensity` + 1.
  9156. *
  9157. * @type {Node<float>}
  9158. */
  9159. const materialAO = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.AO );
  9160. /**
  9161. * TSL object that represents the anisotropy vector of the current material.
  9162. *
  9163. * @type {Node<vec2>}
  9164. */
  9165. const materialAnisotropyVector = /*@__PURE__*/ uniform( new Vector2() ).onReference( function ( frame ) {
  9166. return frame.material;
  9167. } ).onRenderUpdate( function ( { material } ) {
  9168. this.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  9169. } );
  9170. /** @module ModelViewProjectionNode **/
  9171. /**
  9172. * TSL object that represents the position in clip space after the model-view-projection transform of the current rendered object.
  9173. *
  9174. * @type {VaryingNode<vec4>}
  9175. */
  9176. const modelViewProjection = /*@__PURE__*/ ( Fn( ( builder ) => {
  9177. return builder.context.setupModelViewProjection();
  9178. }, 'vec4' ).once() )().toVarying( 'v_modelViewProjection' );
  9179. /** @module IndexNode **/
  9180. /**
  9181. * This class represents shader indices of different types. The following predefined node
  9182. * objects cover frequent use cases:
  9183. *
  9184. * - `vertexIndex`: The index of a vertex within a mesh.
  9185. * - `instanceIndex`: The index of either a mesh instance or an invocation of a compute shader.
  9186. * - `drawIndex`: The index of a draw call.
  9187. * - `invocationLocalIndex`: The index of a compute invocation within the scope of a workgroup load.
  9188. * - `invocationSubgroupIndex`: The index of a compute invocation within the scope of a subgroup.
  9189. * - `subgroupIndex`: The index of the subgroup the current compute invocation belongs to.
  9190. *
  9191. * @augments Node
  9192. */
  9193. class IndexNode extends Node {
  9194. static get type() {
  9195. return 'IndexNode';
  9196. }
  9197. /**
  9198. * Constructs a new index node.
  9199. *
  9200. * @param {('vertex'|'instance'|'subgroup'|'invocationLocal'|'invocationSubgroup'|'draw')} scope - The scope of the index node.
  9201. */
  9202. constructor( scope ) {
  9203. super( 'uint' );
  9204. /**
  9205. * The scope of the index node.
  9206. *
  9207. * @type {String}
  9208. */
  9209. this.scope = scope;
  9210. /**
  9211. * This flag can be used for type testing.
  9212. *
  9213. * @type {Boolean}
  9214. * @readonly
  9215. * @default true
  9216. */
  9217. this.isIndexNode = true;
  9218. }
  9219. generate( builder ) {
  9220. const nodeType = this.getNodeType( builder );
  9221. const scope = this.scope;
  9222. let propertyName;
  9223. if ( scope === IndexNode.VERTEX ) {
  9224. propertyName = builder.getVertexIndex();
  9225. } else if ( scope === IndexNode.INSTANCE ) {
  9226. propertyName = builder.getInstanceIndex();
  9227. } else if ( scope === IndexNode.DRAW ) {
  9228. propertyName = builder.getDrawIndex();
  9229. } else if ( scope === IndexNode.INVOCATION_LOCAL ) {
  9230. propertyName = builder.getInvocationLocalIndex();
  9231. } else if ( scope === IndexNode.INVOCATION_SUBGROUP ) {
  9232. propertyName = builder.getInvocationSubgroupIndex();
  9233. } else if ( scope === IndexNode.SUBGROUP ) {
  9234. propertyName = builder.getSubgroupIndex();
  9235. } else {
  9236. throw new Error( 'THREE.IndexNode: Unknown scope: ' + scope );
  9237. }
  9238. let output;
  9239. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  9240. output = propertyName;
  9241. } else {
  9242. const nodeVarying = varying( this );
  9243. output = nodeVarying.build( builder, nodeType );
  9244. }
  9245. return output;
  9246. }
  9247. }
  9248. IndexNode.VERTEX = 'vertex';
  9249. IndexNode.INSTANCE = 'instance';
  9250. IndexNode.SUBGROUP = 'subgroup';
  9251. IndexNode.INVOCATION_LOCAL = 'invocationLocal';
  9252. IndexNode.INVOCATION_SUBGROUP = 'invocationSubgroup';
  9253. IndexNode.DRAW = 'draw';
  9254. /**
  9255. * TSL object that represents the index of a vertex within a mesh.
  9256. *
  9257. * @type {IndexNode}
  9258. */
  9259. const vertexIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.VERTEX );
  9260. /**
  9261. * TSL object that represents the index of either a mesh instance or an invocation of a compute shader.
  9262. *
  9263. * @type {IndexNode}
  9264. */
  9265. const instanceIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INSTANCE );
  9266. /**
  9267. * TSL object that represents the index of the subgroup the current compute invocation belongs to.
  9268. *
  9269. * @type {IndexNode}
  9270. */
  9271. const subgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.SUBGROUP );
  9272. /**
  9273. * TSL object that represents the index of a compute invocation within the scope of a subgroup.
  9274. *
  9275. * @type {IndexNode}
  9276. */
  9277. const invocationSubgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_SUBGROUP );
  9278. /**
  9279. * TSL object that represents the index of a compute invocation within the scope of a workgroup load.
  9280. *
  9281. * @type {IndexNode}
  9282. */
  9283. const invocationLocalIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_LOCAL );
  9284. /**
  9285. * TSL object that represents the index of a draw call.
  9286. *
  9287. * @type {IndexNode}
  9288. */
  9289. const drawIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.DRAW );
  9290. /** @module InstanceNode **/
  9291. /**
  9292. * This node implements the vertex shader logic which is required
  9293. * when rendering 3D objects via instancing. The code makes sure
  9294. * vertex positions, normals and colors can be modified via instanced
  9295. * data.
  9296. *
  9297. * @augments Node
  9298. */
  9299. class InstanceNode extends Node {
  9300. static get type() {
  9301. return 'InstanceNode';
  9302. }
  9303. /**
  9304. * Constructs a new instance node.
  9305. *
  9306. * @param {Number} count - The number of instances.
  9307. * @param {InstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  9308. * @param {InstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  9309. */
  9310. constructor( count, instanceMatrix, instanceColor ) {
  9311. super( 'void' );
  9312. /**
  9313. * The number of instances.
  9314. *
  9315. * @type {Number}
  9316. */
  9317. this.count = count;
  9318. /**
  9319. * Instanced buffer attribute representing the transformation of instances.
  9320. *
  9321. * @type {InstancedBufferAttribute}
  9322. */
  9323. this.instanceMatrix = instanceMatrix;
  9324. /**
  9325. * Instanced buffer attribute representing the color of instances.
  9326. *
  9327. * @type {InstancedBufferAttribute}
  9328. */
  9329. this.instanceColor = instanceColor;
  9330. /**
  9331. * The node that represents the instance matrix data.
  9332. *
  9333. * @type {Node}
  9334. */
  9335. this.instanceMatrixNode = null;
  9336. /**
  9337. * The node that represents the instance color data.
  9338. *
  9339. * @type {Node}
  9340. */
  9341. this.instanceColorNode = null;
  9342. /**
  9343. * The update type is set to `frame` since an update
  9344. * of instanced buffer data must be checked per frame.
  9345. *
  9346. * @type {String}
  9347. * @default 'frame'
  9348. */
  9349. this.updateType = NodeUpdateType.FRAME;
  9350. /**
  9351. * A reference to a buffer that is used by `instanceMatrixNode`.
  9352. *
  9353. * @type {InstancedInterleavedBuffer}
  9354. */
  9355. this.buffer = null;
  9356. /**
  9357. * A reference to a buffer that is used by `instanceColorNode`.
  9358. *
  9359. * @type {InstancedBufferAttribute}
  9360. */
  9361. this.bufferColor = null;
  9362. }
  9363. /**
  9364. * Setups the internal buffers and nodes and assigns the transformed vertex data
  9365. * to predefined node variables for accumulation. That follows the same patterns
  9366. * like with morph and skinning nodes.
  9367. *
  9368. * @param {NodeBuilder} builder - The current node builder.
  9369. */
  9370. setup( builder ) {
  9371. const { count, instanceMatrix, instanceColor } = this;
  9372. let { instanceMatrixNode, instanceColorNode } = this;
  9373. if ( instanceMatrixNode === null ) {
  9374. // 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.
  9375. if ( count <= 1000 ) {
  9376. instanceMatrixNode = buffer( instanceMatrix.array, 'mat4', Math.max( count, 1 ) ).element( instanceIndex );
  9377. } else {
  9378. const buffer = new InstancedInterleavedBuffer( instanceMatrix.array, 16, 1 );
  9379. this.buffer = buffer;
  9380. const bufferFn = instanceMatrix.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  9381. const instanceBuffers = [
  9382. // F.Signature -> bufferAttribute( array, type, stride, offset )
  9383. bufferFn( buffer, 'vec4', 16, 0 ),
  9384. bufferFn( buffer, 'vec4', 16, 4 ),
  9385. bufferFn( buffer, 'vec4', 16, 8 ),
  9386. bufferFn( buffer, 'vec4', 16, 12 )
  9387. ];
  9388. instanceMatrixNode = mat4( ...instanceBuffers );
  9389. }
  9390. this.instanceMatrixNode = instanceMatrixNode;
  9391. }
  9392. if ( instanceColor && instanceColorNode === null ) {
  9393. const buffer = new InstancedBufferAttribute( instanceColor.array, 3 );
  9394. const bufferFn = instanceColor.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  9395. this.bufferColor = buffer;
  9396. instanceColorNode = vec3( bufferFn( buffer, 'vec3', 3, 0 ) );
  9397. this.instanceColorNode = instanceColorNode;
  9398. }
  9399. // POSITION
  9400. const instancePosition = instanceMatrixNode.mul( positionLocal ).xyz;
  9401. positionLocal.assign( instancePosition );
  9402. // NORMAL
  9403. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  9404. const instanceNormal = transformNormal( normalLocal, instanceMatrixNode );
  9405. // ASSIGNS
  9406. normalLocal.assign( instanceNormal );
  9407. }
  9408. // COLOR
  9409. if ( this.instanceColorNode !== null ) {
  9410. varyingProperty( 'vec3', 'vInstanceColor' ).assign( this.instanceColorNode );
  9411. }
  9412. }
  9413. /**
  9414. * Checks if the internal buffers required an update.
  9415. *
  9416. * @param {NodeFrame} frame - The current node frame.
  9417. */
  9418. update( /*frame*/ ) {
  9419. if ( this.instanceMatrix.usage !== DynamicDrawUsage && this.buffer !== null && this.instanceMatrix.version !== this.buffer.version ) {
  9420. this.buffer.version = this.instanceMatrix.version;
  9421. }
  9422. if ( this.instanceColor && this.instanceColor.usage !== DynamicDrawUsage && this.bufferColor !== null && this.instanceColor.version !== this.bufferColor.version ) {
  9423. this.bufferColor.version = this.instanceColor.version;
  9424. }
  9425. }
  9426. }
  9427. /**
  9428. * TSL function for creating an instance node.
  9429. *
  9430. * @function
  9431. * @param {Number} count - The number of instances.
  9432. * @param {InstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  9433. * @param {InstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  9434. * @returns {InstanceNode}
  9435. */
  9436. const instance = /*@__PURE__*/ nodeProxy( InstanceNode );
  9437. /** @module InstancedMeshNode **/
  9438. /**
  9439. * This is a special version of `InstanceNode` which requires the usage of {@link InstancedMesh}.
  9440. * It allows an easier setup of the instance node.
  9441. *
  9442. * @augments module:InstanceNode~InstanceNode
  9443. */
  9444. class InstancedMeshNode extends InstanceNode {
  9445. static get type() {
  9446. return 'InstancedMeshNode';
  9447. }
  9448. /**
  9449. * Constructs a new instanced mesh node.
  9450. *
  9451. * @param {InstancedMesh} instancedMesh - The instanced mesh.
  9452. */
  9453. constructor( instancedMesh ) {
  9454. const { count, instanceMatrix, instanceColor } = instancedMesh;
  9455. super( count, instanceMatrix, instanceColor );
  9456. /**
  9457. * A reference to the instanced mesh.
  9458. *
  9459. * @type {InstancedMesh}
  9460. */
  9461. this.instancedMesh = instancedMesh;
  9462. }
  9463. }
  9464. /**
  9465. * TSL function for creating an instanced mesh node.
  9466. *
  9467. * @function
  9468. * @param {InstancedMesh} instancedMesh - The instancedMesh.
  9469. * @returns {InstancedMeshNode}
  9470. */
  9471. const instancedMesh = /*@__PURE__*/ nodeProxy( InstancedMeshNode );
  9472. /** @module BatchNode **/
  9473. /**
  9474. * This node implements the vertex shader logic which is required
  9475. * when rendering 3D objects via batching. `BatchNode` must be used
  9476. * with instances of {@link BatchedMesh}.
  9477. *
  9478. * @augments Node
  9479. */
  9480. class BatchNode extends Node {
  9481. static get type() {
  9482. return 'BatchNode';
  9483. }
  9484. /**
  9485. * Constructs a new batch node.
  9486. *
  9487. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  9488. */
  9489. constructor( batchMesh ) {
  9490. super( 'void' );
  9491. /**
  9492. * A reference to batched mesh.
  9493. *
  9494. * @type {BatchedMesh}
  9495. */
  9496. this.batchMesh = batchMesh;
  9497. /**
  9498. * The batching index node.
  9499. *
  9500. * @type {IndexNode?}
  9501. * @default null
  9502. */
  9503. this.batchingIdNode = null;
  9504. }
  9505. /**
  9506. * Setups the internal buffers and nodes and assigns the transformed vertex data
  9507. * to predefined node variables for accumulation. That follows the same patterns
  9508. * like with morph and skinning nodes.
  9509. *
  9510. * @param {NodeBuilder} builder - The current node builder.
  9511. */
  9512. setup( builder ) {
  9513. if ( this.batchingIdNode === null ) {
  9514. if ( builder.getDrawIndex() === null ) {
  9515. this.batchingIdNode = instanceIndex;
  9516. } else {
  9517. this.batchingIdNode = drawIndex;
  9518. }
  9519. }
  9520. const getIndirectIndex = Fn( ( [ id ] ) => {
  9521. const size = int( textureSize( textureLoad( this.batchMesh._indirectTexture ), 0 ) );
  9522. const x = int( id ).modInt( size );
  9523. const y = int( id ).div( size );
  9524. return textureLoad( this.batchMesh._indirectTexture, ivec2( x, y ) ).x;
  9525. } ).setLayout( {
  9526. name: 'getIndirectIndex',
  9527. type: 'uint',
  9528. inputs: [
  9529. { name: 'id', type: 'int' }
  9530. ]
  9531. } );
  9532. const indirectId = getIndirectIndex( int( this.batchingIdNode ) );
  9533. const matricesTexture = this.batchMesh._matricesTexture;
  9534. const size = textureSize( textureLoad( matricesTexture ), 0 );
  9535. const j = float( indirectId ).mul( 4 ).toInt().toVar();
  9536. const x = j.modInt( size );
  9537. const y = j.div( int( size ) );
  9538. const batchingMatrix = mat4(
  9539. textureLoad( matricesTexture, ivec2( x, y ) ),
  9540. textureLoad( matricesTexture, ivec2( x.add( 1 ), y ) ),
  9541. textureLoad( matricesTexture, ivec2( x.add( 2 ), y ) ),
  9542. textureLoad( matricesTexture, ivec2( x.add( 3 ), y ) )
  9543. );
  9544. const colorsTexture = this.batchMesh._colorsTexture;
  9545. if ( colorsTexture !== null ) {
  9546. const getBatchingColor = Fn( ( [ id ] ) => {
  9547. const size = textureSize( textureLoad( colorsTexture ), 0 ).x;
  9548. const j = id;
  9549. const x = j.modInt( size );
  9550. const y = j.div( size );
  9551. return textureLoad( colorsTexture, ivec2( x, y ) ).rgb;
  9552. } ).setLayout( {
  9553. name: 'getBatchingColor',
  9554. type: 'vec3',
  9555. inputs: [
  9556. { name: 'id', type: 'int' }
  9557. ]
  9558. } );
  9559. const color = getBatchingColor( indirectId );
  9560. varyingProperty( 'vec3', 'vBatchColor' ).assign( color );
  9561. }
  9562. const bm = mat3( batchingMatrix );
  9563. positionLocal.assign( batchingMatrix.mul( positionLocal ) );
  9564. const transformedNormal = normalLocal.div( vec3( bm[ 0 ].dot( bm[ 0 ] ), bm[ 1 ].dot( bm[ 1 ] ), bm[ 2 ].dot( bm[ 2 ] ) ) );
  9565. const batchingNormal = bm.mul( transformedNormal ).xyz;
  9566. normalLocal.assign( batchingNormal );
  9567. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  9568. tangentLocal.mulAssign( bm );
  9569. }
  9570. }
  9571. }
  9572. /**
  9573. * TSL function for creating a batch node.
  9574. *
  9575. * @function
  9576. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  9577. * @returns {BatchNode}
  9578. */
  9579. const batch = /*@__PURE__*/ nodeProxy( BatchNode );
  9580. /** @module SkinningNode **/
  9581. const _frameId = new WeakMap();
  9582. /**
  9583. * This node implements the vertex transformation shader logic which is required
  9584. * for skinning/skeletal animation.
  9585. *
  9586. * @augments Node
  9587. */
  9588. class SkinningNode extends Node {
  9589. static get type() {
  9590. return 'SkinningNode';
  9591. }
  9592. /**
  9593. * Constructs a new skinning node.
  9594. *
  9595. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  9596. * @param {Boolean} [useReference=false] - Whether to use reference nodes for internal skinned mesh related data or not.
  9597. */
  9598. constructor( skinnedMesh, useReference = false ) {
  9599. super( 'void' );
  9600. /**
  9601. * The skinned mesh.
  9602. *
  9603. * @type {SkinnedMesh}
  9604. */
  9605. this.skinnedMesh = skinnedMesh;
  9606. /**
  9607. * Whether to use reference nodes for internal skinned mesh related data or not.
  9608. * TODO: Explain the purpose of the property.
  9609. *
  9610. * @type {Boolean}
  9611. */
  9612. this.useReference = useReference;
  9613. /**
  9614. * The update type overwritten since skinning nodes are updated per object.
  9615. *
  9616. * @type {String}
  9617. */
  9618. this.updateType = NodeUpdateType.OBJECT;
  9619. //
  9620. /**
  9621. * The skin index attribute.
  9622. *
  9623. * @type {AttributeNode}
  9624. */
  9625. this.skinIndexNode = attribute( 'skinIndex', 'uvec4' );
  9626. /**
  9627. * The skin weight attribute.
  9628. *
  9629. * @type {AttributeNode}
  9630. */
  9631. this.skinWeightNode = attribute( 'skinWeight', 'vec4' );
  9632. let bindMatrixNode, bindMatrixInverseNode, boneMatricesNode;
  9633. if ( useReference ) {
  9634. bindMatrixNode = reference( 'bindMatrix', 'mat4' );
  9635. bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' );
  9636. boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  9637. } else {
  9638. bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' );
  9639. bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' );
  9640. boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length );
  9641. }
  9642. /**
  9643. * The bind matrix node.
  9644. *
  9645. * @type {Node<mat4>}
  9646. */
  9647. this.bindMatrixNode = bindMatrixNode;
  9648. /**
  9649. * The bind matrix inverse node.
  9650. *
  9651. * @type {Node<mat4>}
  9652. */
  9653. this.bindMatrixInverseNode = bindMatrixInverseNode;
  9654. /**
  9655. * The bind matrices as a uniform buffer node.
  9656. *
  9657. * @type {Node}
  9658. */
  9659. this.boneMatricesNode = boneMatricesNode;
  9660. /**
  9661. * The previous bind matrices as a uniform buffer node.
  9662. * Required for computing motion vectors.
  9663. *
  9664. * @type {Node?}
  9665. * @default null
  9666. */
  9667. this.previousBoneMatricesNode = null;
  9668. }
  9669. /**
  9670. * Transforms the given vertex position via skinning.
  9671. *
  9672. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  9673. * @param {Node<vec3>} [position=positionLocal] - The vertex position in local space.
  9674. * @return {Node<vec3>} The transformed vertex position.
  9675. */
  9676. getSkinnedPosition( boneMatrices = this.boneMatricesNode, position = positionLocal ) {
  9677. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  9678. const boneMatX = boneMatrices.element( skinIndexNode.x );
  9679. const boneMatY = boneMatrices.element( skinIndexNode.y );
  9680. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  9681. const boneMatW = boneMatrices.element( skinIndexNode.w );
  9682. // POSITION
  9683. const skinVertex = bindMatrixNode.mul( position );
  9684. const skinned = add(
  9685. boneMatX.mul( skinWeightNode.x ).mul( skinVertex ),
  9686. boneMatY.mul( skinWeightNode.y ).mul( skinVertex ),
  9687. boneMatZ.mul( skinWeightNode.z ).mul( skinVertex ),
  9688. boneMatW.mul( skinWeightNode.w ).mul( skinVertex )
  9689. );
  9690. return bindMatrixInverseNode.mul( skinned ).xyz;
  9691. }
  9692. /**
  9693. * Transforms the given vertex normal via skinning.
  9694. *
  9695. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  9696. * @param {Node<vec3>} [normal=normalLocal] - The vertex normal in local space.
  9697. * @return {Node<vec3>} The transformed vertex normal.
  9698. */
  9699. getSkinnedNormal( boneMatrices = this.boneMatricesNode, normal = normalLocal ) {
  9700. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  9701. const boneMatX = boneMatrices.element( skinIndexNode.x );
  9702. const boneMatY = boneMatrices.element( skinIndexNode.y );
  9703. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  9704. const boneMatW = boneMatrices.element( skinIndexNode.w );
  9705. // NORMAL
  9706. let skinMatrix = add(
  9707. skinWeightNode.x.mul( boneMatX ),
  9708. skinWeightNode.y.mul( boneMatY ),
  9709. skinWeightNode.z.mul( boneMatZ ),
  9710. skinWeightNode.w.mul( boneMatW )
  9711. );
  9712. skinMatrix = bindMatrixInverseNode.mul( skinMatrix ).mul( bindMatrixNode );
  9713. return skinMatrix.transformDirection( normal ).xyz;
  9714. }
  9715. /**
  9716. * Transforms the given vertex normal via skinning.
  9717. *
  9718. * @param {NodeBuilder} builder - The current node builder.
  9719. * @return {Node<vec3>} The skinned position from the previous frame.
  9720. */
  9721. getPreviousSkinnedPosition( builder ) {
  9722. const skinnedMesh = builder.object;
  9723. if ( this.previousBoneMatricesNode === null ) {
  9724. skinnedMesh.skeleton.previousBoneMatrices = new Float32Array( skinnedMesh.skeleton.boneMatrices );
  9725. this.previousBoneMatricesNode = referenceBuffer( 'skeleton.previousBoneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  9726. }
  9727. return this.getSkinnedPosition( this.previousBoneMatricesNode, positionPrevious );
  9728. }
  9729. /**
  9730. * Returns `true` if bone matrices from the previous frame are required.
  9731. *
  9732. * @param {NodeBuilder} builder - The current node builder.
  9733. * @return {Boolean} Whether bone matrices from the previous frame are required or not.
  9734. */
  9735. needsPreviousBoneMatrices( builder ) {
  9736. const mrt = builder.renderer.getMRT();
  9737. return ( mrt && mrt.has( 'velocity' ) ) || getDataFromObject( builder.object ).useVelocity === true;
  9738. }
  9739. /**
  9740. * Setups the skinning node by assigning the transformed vertex data to predefined node variables.
  9741. *
  9742. * @param {NodeBuilder} builder - The current node builder.
  9743. */
  9744. setup( builder ) {
  9745. if ( this.needsPreviousBoneMatrices( builder ) ) {
  9746. positionPrevious.assign( this.getPreviousSkinnedPosition( builder ) );
  9747. }
  9748. const skinPosition = this.getSkinnedPosition();
  9749. positionLocal.assign( skinPosition );
  9750. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  9751. const skinNormal = this.getSkinnedNormal();
  9752. normalLocal.assign( skinNormal );
  9753. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  9754. tangentLocal.assign( skinNormal );
  9755. }
  9756. }
  9757. }
  9758. /**
  9759. * Generates the code snippet of the skinning node.
  9760. *
  9761. * @param {NodeBuilder} builder - The current node builder.
  9762. * @param {String} output - The current output.
  9763. * @return {String} The generated code snippet.
  9764. */
  9765. generate( builder, output ) {
  9766. if ( output !== 'void' ) {
  9767. return positionLocal.build( builder, output );
  9768. }
  9769. }
  9770. /**
  9771. * Updates the state of the skinned mesh by updating the skeleton once per frame.
  9772. *
  9773. * @param {NodeFrame} frame - The current node frame.
  9774. */
  9775. update( frame ) {
  9776. const object = this.useReference ? frame.object : this.skinnedMesh;
  9777. const skeleton = object.skeleton;
  9778. if ( _frameId.get( skeleton ) === frame.frameId ) return;
  9779. _frameId.set( skeleton, frame.frameId );
  9780. if ( this.previousBoneMatricesNode !== null ) skeleton.previousBoneMatrices.set( skeleton.boneMatrices );
  9781. skeleton.update();
  9782. }
  9783. }
  9784. /**
  9785. * TSL function for creating a skinning node.
  9786. *
  9787. * @function
  9788. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  9789. * @returns {SkinningNode}
  9790. */
  9791. const skinning = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh ) );
  9792. /**
  9793. * TSL function for creating a skinning node with reference usage.
  9794. *
  9795. * @function
  9796. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  9797. * @returns {SkinningNode}
  9798. */
  9799. const skinningReference = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh, true ) );
  9800. /** @module LoopNode **/
  9801. /**
  9802. * This module offers a variety of ways to implement loops in TSL. In it's basic form it's:
  9803. * ```js
  9804. * Loop( count, ( { i } ) => {
  9805. *
  9806. * } );
  9807. * ```
  9808. * However, it is also possible to define a start and end ranges, data types and loop conditions:
  9809. * ```js
  9810. * Loop( { start: int( 0 ), end: int( 10 ), type: 'int', condition: '<' }, ( { i } ) => {
  9811. *
  9812. * } );
  9813. *```
  9814. * Nested loops can be defined in a compacted form:
  9815. * ```js
  9816. * Loop( 10, 5, ( { i, j } ) => {
  9817. *
  9818. * } );
  9819. * ```
  9820. * Loops that should run backwards can be defined like so:
  9821. * ```js
  9822. * Loop( { start: 10 }, () => {} );
  9823. * ```
  9824. * The module also provides `Break()` and `Continue()` TSL expression for loop control.
  9825. * @augments Node
  9826. */
  9827. class LoopNode extends Node {
  9828. static get type() {
  9829. return 'LoopNode';
  9830. }
  9831. /**
  9832. * Constructs a new loop node.
  9833. *
  9834. * @param {Array<Any>} params - Depending on the loop type, array holds different parameterization values for the loop.
  9835. */
  9836. constructor( params = [] ) {
  9837. super();
  9838. this.params = params;
  9839. }
  9840. /**
  9841. * Returns a loop variable name based on an index. The pattern is
  9842. * `0` = `i`, `1`= `j`, `2`= `k` and so on.
  9843. *
  9844. * @param {Number} index - The index.
  9845. * @return {String} The loop variable name.
  9846. */
  9847. getVarName( index ) {
  9848. return String.fromCharCode( 'i'.charCodeAt( 0 ) + index );
  9849. }
  9850. /**
  9851. * Returns properties about this node.
  9852. *
  9853. * @param {NodeBuilder} builder - The current node builder.
  9854. * @return {Object} The node properties.
  9855. */
  9856. getProperties( builder ) {
  9857. const properties = builder.getNodeProperties( this );
  9858. if ( properties.stackNode !== undefined ) return properties;
  9859. //
  9860. const inputs = {};
  9861. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  9862. const param = this.params[ i ];
  9863. const name = ( param.isNode !== true && param.name ) || this.getVarName( i );
  9864. const type = ( param.isNode !== true && param.type ) || 'int';
  9865. inputs[ name ] = expression( name, type );
  9866. }
  9867. const stack = builder.addStack(); // TODO: cache() it
  9868. properties.returnsNode = this.params[ this.params.length - 1 ]( inputs, stack, builder );
  9869. properties.stackNode = stack;
  9870. builder.removeStack();
  9871. return properties;
  9872. }
  9873. /**
  9874. * This method is overwritten since the node type is inferred based on the loop configuration.
  9875. *
  9876. * @param {NodeBuilder} builder - The current node builder.
  9877. * @return {String} The node type.
  9878. */
  9879. getNodeType( builder ) {
  9880. const { returnsNode } = this.getProperties( builder );
  9881. return returnsNode ? returnsNode.getNodeType( builder ) : 'void';
  9882. }
  9883. setup( builder ) {
  9884. // setup properties
  9885. this.getProperties( builder );
  9886. }
  9887. generate( builder ) {
  9888. const properties = this.getProperties( builder );
  9889. const params = this.params;
  9890. const stackNode = properties.stackNode;
  9891. for ( let i = 0, l = params.length - 1; i < l; i ++ ) {
  9892. const param = params[ i ];
  9893. let start = null, end = null, name = null, type = null, condition = null, update = null;
  9894. if ( param.isNode ) {
  9895. type = 'int';
  9896. name = this.getVarName( i );
  9897. start = '0';
  9898. end = param.build( builder, type );
  9899. condition = '<';
  9900. } else {
  9901. type = param.type || 'int';
  9902. name = param.name || this.getVarName( i );
  9903. start = param.start;
  9904. end = param.end;
  9905. condition = param.condition;
  9906. update = param.update;
  9907. if ( typeof start === 'number' ) start = builder.generateConst( type, start );
  9908. else if ( start && start.isNode ) start = start.build( builder, type );
  9909. if ( typeof end === 'number' ) end = builder.generateConst( type, end );
  9910. else if ( end && end.isNode ) end = end.build( builder, type );
  9911. if ( start !== undefined && end === undefined ) {
  9912. start = start + ' - 1';
  9913. end = '0';
  9914. condition = '>=';
  9915. } else if ( end !== undefined && start === undefined ) {
  9916. start = '0';
  9917. condition = '<';
  9918. }
  9919. if ( condition === undefined ) {
  9920. if ( Number( start ) > Number( end ) ) {
  9921. condition = '>=';
  9922. } else {
  9923. condition = '<';
  9924. }
  9925. }
  9926. }
  9927. const internalParam = { start, end, condition };
  9928. //
  9929. const startSnippet = internalParam.start;
  9930. const endSnippet = internalParam.end;
  9931. let declarationSnippet = '';
  9932. let conditionalSnippet = '';
  9933. let updateSnippet = '';
  9934. if ( ! update ) {
  9935. if ( type === 'int' || type === 'uint' ) {
  9936. if ( condition.includes( '<' ) ) update = '++';
  9937. else update = '--';
  9938. } else {
  9939. if ( condition.includes( '<' ) ) update = '+= 1.';
  9940. else update = '-= 1.';
  9941. }
  9942. }
  9943. declarationSnippet += builder.getVar( type, name ) + ' = ' + startSnippet;
  9944. conditionalSnippet += name + ' ' + condition + ' ' + endSnippet;
  9945. updateSnippet += name + ' ' + update;
  9946. const forSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`;
  9947. builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + forSnippet + ' {\n\n' ).addFlowTab();
  9948. }
  9949. const stackSnippet = stackNode.build( builder, 'void' );
  9950. const returnsSnippet = properties.returnsNode ? properties.returnsNode.build( builder ) : '';
  9951. builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet );
  9952. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  9953. builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab();
  9954. }
  9955. builder.addFlowTab();
  9956. return returnsSnippet;
  9957. }
  9958. }
  9959. /**
  9960. * TSL function for creating a loop node.
  9961. *
  9962. * @function
  9963. * @param {...Any} params - A list of parameters.
  9964. * @returns {LoopNode}
  9965. */
  9966. const Loop = ( ...params ) => nodeObject( new LoopNode( nodeArray( params, 'int' ) ) ).append();
  9967. /**
  9968. * TSL function for creating a `Continue()` expression.
  9969. *
  9970. * @function
  9971. * @returns {ExpressionNode}
  9972. */
  9973. const Continue = () => expression( 'continue' ).append();
  9974. /**
  9975. * TSL function for creating a `Break()` expression.
  9976. *
  9977. * @function
  9978. * @returns {ExpressionNode}
  9979. */
  9980. const Break = () => expression( 'break' ).append();
  9981. // Deprecated
  9982. /**
  9983. * @function
  9984. * @deprecated since r168. Use {@link Loop} instead.
  9985. *
  9986. * @param {...any} params
  9987. * @returns {LoopNode}
  9988. */
  9989. const loop = ( ...params ) => { // @deprecated, r168
  9990. console.warn( 'TSL.LoopNode: loop() has been renamed to Loop().' );
  9991. return Loop( ...params );
  9992. };
  9993. /** @module MorphNode **/
  9994. const _morphTextures = /*@__PURE__*/ new WeakMap();
  9995. const _morphVec4 = /*@__PURE__*/ new Vector4();
  9996. const getMorph = /*@__PURE__*/ Fn( ( { bufferMap, influence, stride, width, depth, offset } ) => {
  9997. const texelIndex = int( vertexIndex ).mul( stride ).add( offset );
  9998. const y = texelIndex.div( width );
  9999. const x = texelIndex.sub( y.mul( width ) );
  10000. const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth );
  10001. return bufferAttrib.mul( influence );
  10002. } );
  10003. function getEntry( geometry ) {
  10004. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  10005. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  10006. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  10007. // instead of using attributes, the WebGL 2 code path encodes morph targets
  10008. // into an array of data textures. Each layer represents a single morph target.
  10009. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  10010. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  10011. let entry = _morphTextures.get( geometry );
  10012. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  10013. if ( entry !== undefined ) entry.texture.dispose();
  10014. const morphTargets = geometry.morphAttributes.position || [];
  10015. const morphNormals = geometry.morphAttributes.normal || [];
  10016. const morphColors = geometry.morphAttributes.color || [];
  10017. let vertexDataCount = 0;
  10018. if ( hasMorphPosition === true ) vertexDataCount = 1;
  10019. if ( hasMorphNormals === true ) vertexDataCount = 2;
  10020. if ( hasMorphColors === true ) vertexDataCount = 3;
  10021. let width = geometry.attributes.position.count * vertexDataCount;
  10022. let height = 1;
  10023. const maxTextureSize = 4096; // @TODO: Use 'capabilities.maxTextureSize'
  10024. if ( width > maxTextureSize ) {
  10025. height = Math.ceil( width / maxTextureSize );
  10026. width = maxTextureSize;
  10027. }
  10028. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  10029. const bufferTexture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  10030. bufferTexture.type = FloatType;
  10031. bufferTexture.needsUpdate = true;
  10032. // fill buffer
  10033. const vertexDataStride = vertexDataCount * 4;
  10034. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  10035. const morphTarget = morphTargets[ i ];
  10036. const morphNormal = morphNormals[ i ];
  10037. const morphColor = morphColors[ i ];
  10038. const offset = width * height * 4 * i;
  10039. for ( let j = 0; j < morphTarget.count; j ++ ) {
  10040. const stride = j * vertexDataStride;
  10041. if ( hasMorphPosition === true ) {
  10042. _morphVec4.fromBufferAttribute( morphTarget, j );
  10043. buffer[ offset + stride + 0 ] = _morphVec4.x;
  10044. buffer[ offset + stride + 1 ] = _morphVec4.y;
  10045. buffer[ offset + stride + 2 ] = _morphVec4.z;
  10046. buffer[ offset + stride + 3 ] = 0;
  10047. }
  10048. if ( hasMorphNormals === true ) {
  10049. _morphVec4.fromBufferAttribute( morphNormal, j );
  10050. buffer[ offset + stride + 4 ] = _morphVec4.x;
  10051. buffer[ offset + stride + 5 ] = _morphVec4.y;
  10052. buffer[ offset + stride + 6 ] = _morphVec4.z;
  10053. buffer[ offset + stride + 7 ] = 0;
  10054. }
  10055. if ( hasMorphColors === true ) {
  10056. _morphVec4.fromBufferAttribute( morphColor, j );
  10057. buffer[ offset + stride + 8 ] = _morphVec4.x;
  10058. buffer[ offset + stride + 9 ] = _morphVec4.y;
  10059. buffer[ offset + stride + 10 ] = _morphVec4.z;
  10060. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? _morphVec4.w : 1;
  10061. }
  10062. }
  10063. }
  10064. entry = {
  10065. count: morphTargetsCount,
  10066. texture: bufferTexture,
  10067. stride: vertexDataCount,
  10068. size: new Vector2( width, height )
  10069. };
  10070. _morphTextures.set( geometry, entry );
  10071. function disposeTexture() {
  10072. bufferTexture.dispose();
  10073. _morphTextures.delete( geometry );
  10074. geometry.removeEventListener( 'dispose', disposeTexture );
  10075. }
  10076. geometry.addEventListener( 'dispose', disposeTexture );
  10077. }
  10078. return entry;
  10079. }
  10080. /**
  10081. * This node implements the vertex transformation shader logic which is required
  10082. * for morph target animation.
  10083. *
  10084. * @augments Node
  10085. */
  10086. class MorphNode extends Node {
  10087. static get type() {
  10088. return 'MorphNode';
  10089. }
  10090. /**
  10091. * Constructs a new morph node.
  10092. *
  10093. * @param {Mesh} mesh - The mesh holding the morph targets.
  10094. */
  10095. constructor( mesh ) {
  10096. super( 'void' );
  10097. /**
  10098. * The mesh holding the morph targets.
  10099. *
  10100. * @type {Mesh}
  10101. */
  10102. this.mesh = mesh;
  10103. /**
  10104. * A uniform node which represents the morph base influence value.
  10105. *
  10106. * @type {UniformNode<float>}
  10107. */
  10108. this.morphBaseInfluence = uniform( 1 );
  10109. /**
  10110. * The update type overwritten since morph nodes are updated per object.
  10111. *
  10112. * @type {String}
  10113. */
  10114. this.updateType = NodeUpdateType.OBJECT;
  10115. }
  10116. /**
  10117. * Setups the morph node by assigning the transformed vertex data to predefined node variables.
  10118. *
  10119. * @param {NodeBuilder} builder - The current node builder.
  10120. */
  10121. setup( builder ) {
  10122. const { geometry } = builder;
  10123. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  10124. const hasMorphNormals = geometry.hasAttribute( 'normal' ) && geometry.morphAttributes.normal !== undefined;
  10125. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  10126. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  10127. // nodes
  10128. const { texture: bufferMap, stride, size } = getEntry( geometry );
  10129. if ( hasMorphPosition === true ) positionLocal.mulAssign( this.morphBaseInfluence );
  10130. if ( hasMorphNormals === true ) normalLocal.mulAssign( this.morphBaseInfluence );
  10131. const width = int( size.width );
  10132. Loop( morphTargetsCount, ( { i } ) => {
  10133. const influence = float( 0 ).toVar();
  10134. if ( this.mesh.count > 1 && ( this.mesh.morphTexture !== null && this.mesh.morphTexture !== undefined ) ) {
  10135. influence.assign( textureLoad( this.mesh.morphTexture, ivec2( int( i ).add( 1 ), int( instanceIndex ) ) ).r );
  10136. } else {
  10137. influence.assign( reference( 'morphTargetInfluences', 'float' ).element( i ).toVar() );
  10138. }
  10139. if ( hasMorphPosition === true ) {
  10140. positionLocal.addAssign( getMorph( {
  10141. bufferMap,
  10142. influence,
  10143. stride,
  10144. width,
  10145. depth: i,
  10146. offset: int( 0 )
  10147. } ) );
  10148. }
  10149. if ( hasMorphNormals === true ) {
  10150. normalLocal.addAssign( getMorph( {
  10151. bufferMap,
  10152. influence,
  10153. stride,
  10154. width,
  10155. depth: i,
  10156. offset: int( 1 )
  10157. } ) );
  10158. }
  10159. } );
  10160. }
  10161. /**
  10162. * Updates the state of the morphed mesh by updating the base influence.
  10163. *
  10164. * @param {NodeFrame} frame - The current node frame.
  10165. */
  10166. update( /*frame*/ ) {
  10167. const morphBaseInfluence = this.morphBaseInfluence;
  10168. if ( this.mesh.geometry.morphTargetsRelative ) {
  10169. morphBaseInfluence.value = 1;
  10170. } else {
  10171. morphBaseInfluence.value = 1 - this.mesh.morphTargetInfluences.reduce( ( a, b ) => a + b, 0 );
  10172. }
  10173. }
  10174. }
  10175. /**
  10176. * TSL function for creating a morph node.
  10177. *
  10178. * @function
  10179. * @param {Mesh} mesh - The mesh holding the morph targets.
  10180. * @returns {MorphNode}
  10181. */
  10182. const morphReference = /*@__PURE__*/ nodeProxy( MorphNode );
  10183. /**
  10184. * Base class for lighting nodes.
  10185. *
  10186. * @augments Node
  10187. */
  10188. class LightingNode extends Node {
  10189. static get type() {
  10190. return 'LightingNode';
  10191. }
  10192. /**
  10193. * Constructs a new lighting node.
  10194. */
  10195. constructor() {
  10196. super( 'vec3' );
  10197. /**
  10198. * This flag can be used for type testing.
  10199. *
  10200. * @type {Boolean}
  10201. * @readonly
  10202. * @default true
  10203. */
  10204. this.isLightingNode = true;
  10205. }
  10206. }
  10207. /**
  10208. * A generic class that can be used by nodes which contribute
  10209. * ambient occlusion to the scene. E.g. an ambient occlusion map
  10210. * node can be used as input for this module. Used in {@link NodeMaterial}.
  10211. *
  10212. * @augments LightingNode
  10213. */
  10214. class AONode extends LightingNode {
  10215. static get type() {
  10216. return 'AONode';
  10217. }
  10218. /**
  10219. * Constructs a new AO node.
  10220. *
  10221. * @param {Node<float>?} [aoNode=null] - The ambient occlusion node.
  10222. */
  10223. constructor( aoNode = null ) {
  10224. super();
  10225. /**
  10226. * The ambient occlusion node.
  10227. *
  10228. * @type {Node<float>?}
  10229. * @default null
  10230. */
  10231. this.aoNode = aoNode;
  10232. }
  10233. setup( builder ) {
  10234. builder.context.ambientOcclusion.mulAssign( this.aoNode );
  10235. }
  10236. }
  10237. /**
  10238. * `LightingContextNode` represents an extension of the {@link module:ContextNode~ContextNode} module
  10239. * by adding lighting specific context data. It represents the runtime context of
  10240. * {@link LightsNode}.
  10241. *
  10242. * @augments ContextNode
  10243. */
  10244. class LightingContextNode extends ContextNode {
  10245. static get type() {
  10246. return 'LightingContextNode';
  10247. }
  10248. /**
  10249. * Constructs a new lighting context node.
  10250. *
  10251. * @param {LightsNode} node - The lights node.
  10252. * @param {LightingModel?} [lightingModel=null] - The current lighting model.
  10253. * @param {Node<vec3>?} [backdropNode=null] - A backdrop node.
  10254. * @param {Node<float>?} [backdropAlphaNode=null] - A backdrop alpha node.
  10255. */
  10256. constructor( node, lightingModel = null, backdropNode = null, backdropAlphaNode = null ) {
  10257. super( node );
  10258. /**
  10259. * The current lighting model.
  10260. *
  10261. * @type {LightingModel?}
  10262. * @default null
  10263. */
  10264. this.lightingModel = lightingModel;
  10265. /**
  10266. * A backdrop node.
  10267. *
  10268. * @type {Node<vec3>?}
  10269. * @default null
  10270. */
  10271. this.backdropNode = backdropNode;
  10272. /**
  10273. * A backdrop alpha node.
  10274. *
  10275. * @type {Node<float>?}
  10276. * @default null
  10277. */
  10278. this.backdropAlphaNode = backdropAlphaNode;
  10279. this._value = null;
  10280. }
  10281. /**
  10282. * Returns a lighting context object.
  10283. *
  10284. * @return {{
  10285. * radiance: Node<vec3>,
  10286. * irradiance: Node<vec3>,
  10287. * iblIrradiance: Node<vec3>,
  10288. * ambientOcclusion: Node<float>,
  10289. * reflectedLight: {directDiffuse: Node<vec3>, directSpecular: Node<vec3>, indirectDiffuse: Node<vec3>, indirectSpecular: Node<vec3>},
  10290. * backdrop: Node<vec3>,
  10291. * backdropAlpha: Node<float>
  10292. * }} The lighting context object.
  10293. */
  10294. getContext() {
  10295. const { backdropNode, backdropAlphaNode } = this;
  10296. const directDiffuse = vec3().toVar( 'directDiffuse' ),
  10297. directSpecular = vec3().toVar( 'directSpecular' ),
  10298. indirectDiffuse = vec3().toVar( 'indirectDiffuse' ),
  10299. indirectSpecular = vec3().toVar( 'indirectSpecular' );
  10300. const reflectedLight = {
  10301. directDiffuse,
  10302. directSpecular,
  10303. indirectDiffuse,
  10304. indirectSpecular
  10305. };
  10306. const context = {
  10307. radiance: vec3().toVar( 'radiance' ),
  10308. irradiance: vec3().toVar( 'irradiance' ),
  10309. iblIrradiance: vec3().toVar( 'iblIrradiance' ),
  10310. ambientOcclusion: float( 1 ).toVar( 'ambientOcclusion' ),
  10311. reflectedLight,
  10312. backdrop: backdropNode,
  10313. backdropAlpha: backdropAlphaNode
  10314. };
  10315. return context;
  10316. }
  10317. setup( builder ) {
  10318. this.value = this._value || ( this._value = this.getContext() );
  10319. this.value.lightingModel = this.lightingModel || builder.context.lightingModel;
  10320. return super.setup( builder );
  10321. }
  10322. }
  10323. const lightingContext = /*@__PURE__*/ nodeProxy( LightingContextNode );
  10324. /**
  10325. * A generic class that can be used by nodes which contribute
  10326. * irradiance to the scene. E.g. a light map node can be used
  10327. * as input for this module. Used in {@link NodeMaterial}.
  10328. *
  10329. * @augments LightingNode
  10330. */
  10331. class IrradianceNode extends LightingNode {
  10332. static get type() {
  10333. return 'IrradianceNode';
  10334. }
  10335. /**
  10336. * Constructs a new irradiance node.
  10337. *
  10338. * @param {Node<vec3>} node - A node contributing irradiance.
  10339. */
  10340. constructor( node ) {
  10341. super();
  10342. /**
  10343. * A node contributing irradiance.
  10344. *
  10345. * @type {Node<vec3>}
  10346. */
  10347. this.node = node;
  10348. }
  10349. setup( builder ) {
  10350. builder.context.irradiance.addAssign( this.node );
  10351. }
  10352. }
  10353. /** @module ScreenNode **/
  10354. let screenSizeVec, viewportVec;
  10355. /**
  10356. * This node provides a collection of screen related metrics.
  10357. * Depending on {@link module:ScreenNode~ScreenNode#scope}, the nodes can represent
  10358. * resolution or viewport data as well as fragment or uv coordinates.
  10359. *
  10360. * @augments Node
  10361. */
  10362. class ScreenNode extends Node {
  10363. static get type() {
  10364. return 'ScreenNode';
  10365. }
  10366. /**
  10367. * Constructs a new screen node.
  10368. *
  10369. * @param {('coordinate'|'viewport'|'size'|'uv')} scope - The node's scope.
  10370. */
  10371. constructor( scope ) {
  10372. super();
  10373. /**
  10374. * The node represents different metric depending on which scope is selected.
  10375. *
  10376. * - `ScreenNode.COORDINATE`: Window-relative coordinates of the current fragment according to WebGPU standards.
  10377. * - `ScreenNode.VIEWPORT`: The current viewport defined as a four-dimensional vector.
  10378. * - `ScreenNode.SIZE`: The dimensions of the current bound framebuffer.
  10379. * - `ScreenNode.UV`: Normalized coordinates.
  10380. *
  10381. * @type {('coordinate'|'viewport'|'size'|'uv')}
  10382. */
  10383. this.scope = scope;
  10384. /**
  10385. * This flag can be used for type testing.
  10386. *
  10387. * @type {Boolean}
  10388. * @readonly
  10389. * @default true
  10390. */
  10391. this.isViewportNode = true;
  10392. }
  10393. /**
  10394. * This method is overwritten since the node type depends on the selected scope.
  10395. *
  10396. * @return {('vec2'|'vec4')} The node type.
  10397. */
  10398. getNodeType() {
  10399. if ( this.scope === ScreenNode.VIEWPORT ) return 'vec4';
  10400. else return 'vec2';
  10401. }
  10402. /**
  10403. * This method is overwritten since the node's update type depends on the selected scope.
  10404. *
  10405. * @return {NodeUpdateType} The update type.
  10406. */
  10407. getUpdateType() {
  10408. let updateType = NodeUpdateType.NONE;
  10409. if ( this.scope === ScreenNode.SIZE || this.scope === ScreenNode.VIEWPORT ) {
  10410. updateType = NodeUpdateType.RENDER;
  10411. }
  10412. this.updateType = updateType;
  10413. return updateType;
  10414. }
  10415. /**
  10416. * `ScreenNode` implements {@link Node#update} to retrieve viewport and size information
  10417. * from the current renderer.
  10418. *
  10419. * @param {NodeFrame} frame - A reference to the current node frame.
  10420. */
  10421. update( { renderer } ) {
  10422. const renderTarget = renderer.getRenderTarget();
  10423. if ( this.scope === ScreenNode.VIEWPORT ) {
  10424. if ( renderTarget !== null ) {
  10425. viewportVec.copy( renderTarget.viewport );
  10426. } else {
  10427. renderer.getViewport( viewportVec );
  10428. viewportVec.multiplyScalar( renderer.getPixelRatio() );
  10429. }
  10430. } else {
  10431. if ( renderTarget !== null ) {
  10432. screenSizeVec.width = renderTarget.width;
  10433. screenSizeVec.height = renderTarget.height;
  10434. } else {
  10435. renderer.getDrawingBufferSize( screenSizeVec );
  10436. }
  10437. }
  10438. }
  10439. setup( /*builder*/ ) {
  10440. const scope = this.scope;
  10441. let output = null;
  10442. if ( scope === ScreenNode.SIZE ) {
  10443. output = uniform( screenSizeVec || ( screenSizeVec = new Vector2() ) );
  10444. } else if ( scope === ScreenNode.VIEWPORT ) {
  10445. output = uniform( viewportVec || ( viewportVec = new Vector4() ) );
  10446. } else {
  10447. output = vec2( screenCoordinate.div( screenSize ) );
  10448. }
  10449. return output;
  10450. }
  10451. generate( builder ) {
  10452. if ( this.scope === ScreenNode.COORDINATE ) {
  10453. let coord = builder.getFragCoord();
  10454. if ( builder.isFlipY() ) {
  10455. // follow webgpu standards
  10456. const size = builder.getNodeProperties( screenSize ).outputNode.build( builder );
  10457. coord = `${ builder.getType( 'vec2' ) }( ${ coord }.x, ${ size }.y - ${ coord }.y )`;
  10458. }
  10459. return coord;
  10460. }
  10461. return super.generate( builder );
  10462. }
  10463. }
  10464. ScreenNode.COORDINATE = 'coordinate';
  10465. ScreenNode.VIEWPORT = 'viewport';
  10466. ScreenNode.SIZE = 'size';
  10467. ScreenNode.UV = 'uv';
  10468. // Screen
  10469. /**
  10470. * TSL object that represents normalized screen coordinates, unitless in `[0, 1]`.
  10471. *
  10472. * @type {ScreenNode<vec2>}
  10473. */
  10474. const screenUV = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.UV );
  10475. /**
  10476. * TSL object that represents the screen resolution in physical pixel units.
  10477. *
  10478. * @type {ScreenNode<vec2>}
  10479. */
  10480. const screenSize = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.SIZE );
  10481. /**
  10482. * TSL object that represents the current `x`/`y` pixel position on the screen in physical pixel units.
  10483. *
  10484. * @type {ScreenNode<vec2>}
  10485. */
  10486. const screenCoordinate = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.COORDINATE );
  10487. // Viewport
  10488. /**
  10489. * TSL object that represents the viewport rectangle as `x`, `y`, `width` and `height` in physical pixel units.
  10490. *
  10491. * @type {ScreenNode<vec4>}
  10492. */
  10493. const viewport = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.VIEWPORT );
  10494. /**
  10495. * TSL object that represents the viewport resolution in physical pixel units.
  10496. *
  10497. * @type {ScreenNode<vec2>}
  10498. */
  10499. const viewportSize = viewport.zw;
  10500. /**
  10501. * TSL object that represents the current `x`/`y` pixel position on the viewport in physical pixel units.
  10502. *
  10503. * @type {ScreenNode<vec2>}
  10504. */
  10505. const viewportCoordinate = /*@__PURE__*/ screenCoordinate.sub( viewport.xy );
  10506. /**
  10507. * TSL object that represents normalized viewport coordinates, unitless in `[0, 1]`.
  10508. *
  10509. * @type {ScreenNode<vec2>}
  10510. */
  10511. const viewportUV = /*@__PURE__*/ viewportCoordinate.div( viewportSize );
  10512. // Deprecated
  10513. /**
  10514. * @deprecated since r169. Use {@link screenSize} instead.
  10515. */
  10516. const viewportResolution = /*@__PURE__*/ ( Fn( () => { // @deprecated, r169
  10517. console.warn( 'TSL.ViewportNode: "viewportResolution" is deprecated. Use "screenSize" instead.' );
  10518. return screenSize;
  10519. }, 'vec2' ).once() )();
  10520. /**
  10521. * @deprecated since r168. Use {@link screenUV} instead.
  10522. */
  10523. const viewportTopLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  10524. console.warn( 'TSL.ViewportNode: "viewportTopLeft" is deprecated. Use "screenUV" instead.' );
  10525. return screenUV;
  10526. }, 'vec2' ).once() )();
  10527. /**
  10528. * @deprecated since r168. Use `screenUV.flipY()` instead.
  10529. */
  10530. const viewportBottomLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  10531. console.warn( 'TSL.ViewportNode: "viewportBottomLeft" is deprecated. Use "screenUV.flipY()" instead.' );
  10532. return screenUV.flipY();
  10533. }, 'vec2' ).once() )();
  10534. /** @module ViewportTextureNode **/
  10535. const _size$4 = /*@__PURE__*/ new Vector2();
  10536. /**
  10537. * A special type of texture node which represents the data of the current viewport
  10538. * as a texture. The module extracts data from the current bound framebuffer with
  10539. * a copy operation so no extra render pass is required to produce the texture data
  10540. * (which is good for performance). `ViewportTextureNode` can be used as an input for a
  10541. * variety of effects like refractive or transmissive materials.
  10542. *
  10543. * @augments module:TextureNode~TextureNode
  10544. */
  10545. class ViewportTextureNode extends TextureNode {
  10546. static get type() {
  10547. return 'ViewportTextureNode';
  10548. }
  10549. /**
  10550. * Constructs a new viewport texture node.
  10551. *
  10552. * @param {Node} [uvNode=screenUV] - The uv node.
  10553. * @param {Node?} [levelNode=null] - The level node.
  10554. * @param {Texture?} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  10555. */
  10556. constructor( uvNode = screenUV, levelNode = null, framebufferTexture = null ) {
  10557. if ( framebufferTexture === null ) {
  10558. framebufferTexture = new FramebufferTexture();
  10559. framebufferTexture.minFilter = LinearMipmapLinearFilter;
  10560. }
  10561. super( framebufferTexture, uvNode, levelNode );
  10562. /**
  10563. * Whether to generate mipmaps or not.
  10564. *
  10565. * @type {Boolean}
  10566. * @default false
  10567. */
  10568. this.generateMipmaps = false;
  10569. /**
  10570. * This flag can be used for type testing.
  10571. *
  10572. * @type {Boolean}
  10573. * @readonly
  10574. * @default true
  10575. */
  10576. this.isOutputTextureNode = true;
  10577. /**
  10578. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  10579. * scene once per frame in its {@link ViewportTextureNode#updateBefore} method.
  10580. *
  10581. * @type {String}
  10582. * @default 'frame'
  10583. */
  10584. this.updateBeforeType = NodeUpdateType.FRAME;
  10585. }
  10586. updateBefore( frame ) {
  10587. const renderer = frame.renderer;
  10588. renderer.getDrawingBufferSize( _size$4 );
  10589. //
  10590. const framebufferTexture = this.value;
  10591. if ( framebufferTexture.image.width !== _size$4.width || framebufferTexture.image.height !== _size$4.height ) {
  10592. framebufferTexture.image.width = _size$4.width;
  10593. framebufferTexture.image.height = _size$4.height;
  10594. framebufferTexture.needsUpdate = true;
  10595. }
  10596. //
  10597. const currentGenerateMipmaps = framebufferTexture.generateMipmaps;
  10598. framebufferTexture.generateMipmaps = this.generateMipmaps;
  10599. renderer.copyFramebufferToTexture( framebufferTexture );
  10600. framebufferTexture.generateMipmaps = currentGenerateMipmaps;
  10601. }
  10602. clone() {
  10603. const viewportTextureNode = new this.constructor( this.uvNode, this.levelNode, this.value );
  10604. viewportTextureNode.generateMipmaps = this.generateMipmaps;
  10605. return viewportTextureNode;
  10606. }
  10607. }
  10608. /**
  10609. * TSL function for creating a viewport texture node.
  10610. *
  10611. * @function
  10612. * @param {Node} [uvNode=screenUV] - The uv node.
  10613. * @param {Node?} [levelNode=null] - The level node.
  10614. * @param {Texture?} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  10615. * @returns {ViewportTextureNode}
  10616. */
  10617. const viewportTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode );
  10618. /**
  10619. * TSL function for creating a viewport texture node with enabled mipmap generation.
  10620. *
  10621. * @function
  10622. * @param {Node} [uvNode=screenUV] - The uv node.
  10623. * @param {Node?} [levelNode=null] - The level node.
  10624. * @param {Texture?} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  10625. * @returns {ViewportTextureNode}
  10626. */
  10627. const viewportMipTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode, null, null, { generateMipmaps: true } );
  10628. /** @module ViewportDepthTextureNode **/
  10629. let sharedDepthbuffer = null;
  10630. /**
  10631. * Represents the depth of the current viewport as a texture. This module
  10632. * can be used in combination with viewport texture to achieve effects
  10633. * that require depth evaluation.
  10634. *
  10635. * @augments module:ViewportTextureNode~ViewportTextureNode
  10636. */
  10637. class ViewportDepthTextureNode extends ViewportTextureNode {
  10638. static get type() {
  10639. return 'ViewportDepthTextureNode';
  10640. }
  10641. /**
  10642. * Constructs a new viewport depth texture node.
  10643. *
  10644. * @param {Node} [uvNode=screenUV] - The uv node.
  10645. * @param {Node?} [levelNode=null] - The level node.
  10646. */
  10647. constructor( uvNode = screenUV, levelNode = null ) {
  10648. if ( sharedDepthbuffer === null ) {
  10649. sharedDepthbuffer = new DepthTexture();
  10650. }
  10651. super( uvNode, levelNode, sharedDepthbuffer );
  10652. }
  10653. }
  10654. /**
  10655. * TSL function for a viewport depth texture node.
  10656. *
  10657. * @function
  10658. * @param {Node} [uvNode=screenUV] - The uv node.
  10659. * @param {Node?} [levelNode=null] - The level node.
  10660. * @returns {ViewportDepthTextureNode}
  10661. */
  10662. const viewportDepthTexture = /*@__PURE__*/ nodeProxy( ViewportDepthTextureNode );
  10663. /** @module ViewportDepthNode **/
  10664. /**
  10665. * This node offers a collection of features in context of the depth logic in the fragment shader.
  10666. * Depending on {@link ViewportDepthNode#scope}, it can be used to define a depth value for the current
  10667. * fragment or for depth evaluation purposes.
  10668. *
  10669. * @augments Node
  10670. */
  10671. class ViewportDepthNode extends Node {
  10672. static get type() {
  10673. return 'ViewportDepthNode';
  10674. }
  10675. /**
  10676. * Constructs a new viewport depth node.
  10677. *
  10678. * @param {('depth'|'depthBase'|'linearDepth')} scope - The node's scope.
  10679. * @param {Node?} [valueNode=null] - The value node.
  10680. */
  10681. constructor( scope, valueNode = null ) {
  10682. super( 'float' );
  10683. /**
  10684. * The node behaves differently depending on which scope is selected.
  10685. *
  10686. * - `ViewportDepthNode.DEPTH_BASE`: Allows to define a value for the current fragment's depth.
  10687. * - `ViewportDepthNode.DEPTH`: Represents the depth value for the current fragment (`valueNode` is ignored).
  10688. * - `ViewportDepthNode.LINEAR_DEPTH`: Represents the linear (orthographic) depth value of the current fragment.
  10689. * If a `valueNode` is set, the scope can be used to convert perspective depth data to linear data.
  10690. *
  10691. * @type {('depth'|'depthBase'|'linearDepth')}
  10692. */
  10693. this.scope = scope;
  10694. /**
  10695. * Can be used to define a custom depth value.
  10696. * The property is ignored in the `ViewportDepthNode.DEPTH` scope.
  10697. *
  10698. * @type {Node?}
  10699. * @default null
  10700. */
  10701. this.valueNode = valueNode;
  10702. /**
  10703. * This flag can be used for type testing.
  10704. *
  10705. * @type {Boolean}
  10706. * @readonly
  10707. * @default true
  10708. */
  10709. this.isViewportDepthNode = true;
  10710. }
  10711. generate( builder ) {
  10712. const { scope } = this;
  10713. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  10714. return builder.getFragDepth();
  10715. }
  10716. return super.generate( builder );
  10717. }
  10718. setup( { camera } ) {
  10719. const { scope } = this;
  10720. const value = this.valueNode;
  10721. let node = null;
  10722. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  10723. if ( value !== null ) {
  10724. node = depthBase().assign( value );
  10725. }
  10726. } else if ( scope === ViewportDepthNode.DEPTH ) {
  10727. if ( camera.isPerspectiveCamera ) {
  10728. node = viewZToPerspectiveDepth( positionView.z, cameraNear, cameraFar );
  10729. } else {
  10730. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  10731. }
  10732. } else if ( scope === ViewportDepthNode.LINEAR_DEPTH ) {
  10733. if ( value !== null ) {
  10734. if ( camera.isPerspectiveCamera ) {
  10735. const viewZ = perspectiveDepthToViewZ( value, cameraNear, cameraFar );
  10736. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  10737. } else {
  10738. node = value;
  10739. }
  10740. } else {
  10741. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  10742. }
  10743. }
  10744. return node;
  10745. }
  10746. }
  10747. ViewportDepthNode.DEPTH_BASE = 'depthBase';
  10748. ViewportDepthNode.DEPTH = 'depth';
  10749. ViewportDepthNode.LINEAR_DEPTH = 'linearDepth';
  10750. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  10751. /**
  10752. * TSL function for converting a viewZ value to an orthographic depth value.
  10753. *
  10754. * @function
  10755. * @param {Node<float>} viewZ - The viewZ node.
  10756. * @param {Node<float>} near - The camera's near value.
  10757. * @param {Node<float>} far - The camera's far value.
  10758. * @returns {Node<float>}
  10759. */
  10760. const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  10761. /**
  10762. * TSL function for converting an orthographic depth value to a viewZ value.
  10763. *
  10764. * @function
  10765. * @param {Node<float>} depth - The orthographic depth.
  10766. * @param {Node<float>} near - The camera's near value.
  10767. * @param {Node<float>} far - The camera's far value.
  10768. * @returns {Node<float>}
  10769. */
  10770. const orthographicDepthToViewZ = ( depth, near, far ) => near.sub( far ).mul( depth ).sub( near );
  10771. /**
  10772. * TSL function for converting a viewZ value to a perspective depth value.
  10773. *
  10774. * Note: {link https://twitter.com/gonnavis/status/1377183786949959682}.
  10775. *
  10776. * @function
  10777. * @param {Node<float>} viewZ - The viewZ node.
  10778. * @param {Node<float>} near - The camera's near value.
  10779. * @param {Node<float>} far - The camera's far value.
  10780. * @returns {Node<float>}
  10781. */
  10782. const viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( far.sub( near ).mul( viewZ ) );
  10783. /**
  10784. * TSL function for converting a perspective depth value to a viewZ value.
  10785. *
  10786. * @function
  10787. * @param {Node<float>} depth - The perspective depth.
  10788. * @param {Node<float>} near - The camera's near value.
  10789. * @param {Node<float>} far - The camera's far value.
  10790. * @returns {Node<float>}
  10791. */
  10792. const perspectiveDepthToViewZ = ( depth, near, far ) => near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  10793. /**
  10794. * TSL function for converting a viewZ value to a logarithmic depth value.
  10795. *
  10796. * @function
  10797. * @param {Node<float>} viewZ - The viewZ node.
  10798. * @param {Node<float>} near - The camera's near value.
  10799. * @param {Node<float>} far - The camera's far value.
  10800. * @returns {Node<float>}
  10801. */
  10802. const viewZToLogarithmicDepth = ( viewZ, near, far ) => {
  10803. // NOTE: viewZ must be negative--see explanation at the end of this comment block.
  10804. // The final logarithmic depth formula used here is adapted from one described in an
  10805. // article by Thatcher Ulrich (see http://tulrich.com/geekstuff/log_depth_buffer.txt),
  10806. // which was an improvement upon an earlier formula one described in an
  10807. // Outerra article (https://outerra.blogspot.com/2009/08/logarithmic-z-buffer.html).
  10808. // Ulrich's formula is the following:
  10809. // z = K * log( w / cameraNear ) / log( cameraFar / cameraNear )
  10810. // where K = 2^k - 1, and k is the number of bits in the depth buffer.
  10811. // The Outerra variant ignored the camera near plane (it assumed it was 0) and instead
  10812. // opted for a "C-constant" for resolution adjustment of objects near the camera.
  10813. // Outerra states: "Notice that the 'C' variant doesn’t use a near plane distance, it has it
  10814. // set at 0" (quote from https://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html).
  10815. // Ulrich's variant has the benefit of constant relative precision over the whole near-far range.
  10816. // It was debated here whether Outerra's "C-constant" or Ulrich's "near plane" variant should
  10817. // be used, and ultimately Ulrich's "near plane" version was chosen.
  10818. // Outerra eventually made another improvement to their original "C-constant" variant,
  10819. // but it still does not incorporate the camera near plane (for this version,
  10820. // see https://outerra.blogspot.com/2013/07/logarithmic-depth-buffer-optimizations.html).
  10821. // Here we make 4 changes to Ulrich's formula:
  10822. // 1. Clamp the camera near plane so we don't divide by 0.
  10823. // 2. Use log2 instead of log to avoid an extra multiply (shaders implement log using log2).
  10824. // 3. Assume K is 1 (K = maximum value in depth buffer; see Ulrich's formula above).
  10825. // 4. To maintain consistency with the functions "viewZToOrthographicDepth" and "viewZToPerspectiveDepth",
  10826. // we modify the formula here to use 'viewZ' instead of 'w'. The other functions expect a negative viewZ,
  10827. // so we do the same here, hence the 'viewZ.negate()' call.
  10828. // For visual representation of this depth curve, see https://www.desmos.com/calculator/uyqk0vex1u
  10829. near = near.max( 1e-6 ).toVar();
  10830. const numerator = log2( viewZ.negate().div( near ) );
  10831. const denominator = log2( far.div( near ) );
  10832. return numerator.div( denominator );
  10833. };
  10834. /**
  10835. * TSL function for converting a logarithmic depth value to a viewZ value.
  10836. *
  10837. * @function
  10838. * @param {Node<float>} depth - The logarithmic depth.
  10839. * @param {Node<float>} near - The camera's near value.
  10840. * @param {Node<float>} far - The camera's far value.
  10841. * @returns {Node<float>}
  10842. */
  10843. const logarithmicDepthToViewZ = ( depth, near, far ) => {
  10844. // NOTE: we add a 'negate()' call to the return value here to maintain consistency with
  10845. // the functions "orthographicDepthToViewZ" and "perspectiveDepthToViewZ" (they return
  10846. // a negative viewZ).
  10847. const exponent = depth.mul( log( far.div( near ) ) );
  10848. return float( Math.E ).pow( exponent ).mul( near ).negate();
  10849. };
  10850. /**
  10851. * TSL function for defining a value for the current fragment's depth.
  10852. *
  10853. * @function
  10854. * @param {Node<float>} value - The depth value to set.
  10855. * @returns {ViewportDepthNode<float>}
  10856. */
  10857. const depthBase = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH_BASE );
  10858. /**
  10859. * TSL object that represents the depth value for the current fragment.
  10860. *
  10861. * @type {ViewportDepthNode}
  10862. */
  10863. const depth = /*@__PURE__*/ nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  10864. /**
  10865. * TSL function for converting a perspective depth value to linear depth.
  10866. *
  10867. * @function
  10868. * @param {Node<float>} value - The perspective depth.
  10869. * @returns {ViewportDepthNode<float>}
  10870. */
  10871. const linearDepth = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.LINEAR_DEPTH );
  10872. /**
  10873. * TSL object that represents the linear (orthographic) depth value of the current fragment
  10874. *
  10875. * @type {ViewportDepthNode}
  10876. */
  10877. const viewportLinearDepth = /*@__PURE__*/ linearDepth( viewportDepthTexture() );
  10878. depth.assign = ( value ) => depthBase( value );
  10879. /** @module BuiltinNode **/
  10880. /**
  10881. * The node allows to set values for built-in shader variables. That is
  10882. * required for features like hardware-accelerated vertex clipping.
  10883. *
  10884. * @augments Node
  10885. */
  10886. class BuiltinNode extends Node {
  10887. /**
  10888. * Constructs a new builtin node.
  10889. *
  10890. * @param {String} name - The name of the built-in shader variable.
  10891. */
  10892. constructor( name ) {
  10893. super( 'float' );
  10894. /**
  10895. * The name of the built-in shader variable.
  10896. *
  10897. * @type {String}
  10898. */
  10899. this.name = name;
  10900. /**
  10901. * This flag can be used for type testing.
  10902. *
  10903. * @type {Boolean}
  10904. * @readonly
  10905. * @default true
  10906. */
  10907. this.isBuiltinNode = true;
  10908. }
  10909. /**
  10910. * Generates the code snippet of the builtin node.
  10911. *
  10912. * @param {NodeBuilder} builder - The current node builder.
  10913. * @return {String} The generated code snippet.
  10914. */
  10915. generate( /* builder */ ) {
  10916. return this.name;
  10917. }
  10918. }
  10919. /**
  10920. * TSL function for creating a builtin node.
  10921. *
  10922. * @function
  10923. * @param {String} name - The name of the built-in shader variable.
  10924. * @returns {BuiltinNode}
  10925. */
  10926. const builtin = nodeProxy( BuiltinNode );
  10927. /** @module ClippingNode **/
  10928. /**
  10929. * ```
  10930. * This node is used in {@link NodeMaterial} to setup the clipping
  10931. * which can happen hardware-accelerated (if supported) and optionally
  10932. * use alpha-to-coverage for anti-aliasing clipped edges.
  10933. * ```
  10934. * @augments Node
  10935. */
  10936. class ClippingNode extends Node {
  10937. static get type() {
  10938. return 'ClippingNode';
  10939. }
  10940. /**
  10941. * Constructs a new clipping node.
  10942. *
  10943. * @param {('default'|'hardware'|'alphaToCoverage')} [scope='default'] - The node's scope. Similar to other nodes,
  10944. * the selected scope influences the behavior of the node and what type of code is generated.
  10945. */
  10946. constructor( scope = ClippingNode.DEFAULT ) {
  10947. super();
  10948. /**
  10949. * The node's scope. Similar to other nodes, the selected scope influences
  10950. * the behavior of the node and what type of code is generated.
  10951. *
  10952. * @type {('default'|'hardware'|'alphaToCoverage')}
  10953. */
  10954. this.scope = scope;
  10955. }
  10956. /**
  10957. * Setups the node depending on the selected scope.
  10958. *
  10959. * @param {NodeBuilder} builder - The current node builder.
  10960. * @return {Node} The result node.
  10961. */
  10962. setup( builder ) {
  10963. super.setup( builder );
  10964. const clippingContext = builder.clippingContext;
  10965. const { intersectionPlanes, unionPlanes } = clippingContext;
  10966. this.hardwareClipping = builder.material.hardwareClipping;
  10967. if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) {
  10968. return this.setupAlphaToCoverage( intersectionPlanes, unionPlanes );
  10969. } else if ( this.scope === ClippingNode.HARDWARE ) {
  10970. return this.setupHardwareClipping( unionPlanes, builder );
  10971. } else {
  10972. return this.setupDefault( intersectionPlanes, unionPlanes );
  10973. }
  10974. }
  10975. /**
  10976. * Setups alpha to coverage.
  10977. *
  10978. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  10979. * @param {Array<Vector4>} unionPlanes - The union planes.
  10980. * @return {Node} The result node.
  10981. */
  10982. setupAlphaToCoverage( intersectionPlanes, unionPlanes ) {
  10983. return Fn( () => {
  10984. const distanceToPlane = float().toVar( 'distanceToPlane' );
  10985. const distanceGradient = float().toVar( 'distanceToGradient' );
  10986. const clipOpacity = float( 1 ).toVar( 'clipOpacity' );
  10987. const numUnionPlanes = unionPlanes.length;
  10988. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  10989. const clippingPlanes = uniformArray( unionPlanes );
  10990. Loop( numUnionPlanes, ( { i } ) => {
  10991. const plane = clippingPlanes.element( i );
  10992. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  10993. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  10994. clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) );
  10995. } );
  10996. }
  10997. const numIntersectionPlanes = intersectionPlanes.length;
  10998. if ( numIntersectionPlanes > 0 ) {
  10999. const clippingPlanes = uniformArray( intersectionPlanes );
  11000. const intersectionClipOpacity = float( 1 ).toVar( 'intersectionClipOpacity' );
  11001. Loop( numIntersectionPlanes, ( { i } ) => {
  11002. const plane = clippingPlanes.element( i );
  11003. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  11004. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  11005. intersectionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() );
  11006. } );
  11007. clipOpacity.mulAssign( intersectionClipOpacity.oneMinus() );
  11008. }
  11009. diffuseColor.a.mulAssign( clipOpacity );
  11010. diffuseColor.a.equal( 0.0 ).discard();
  11011. } )();
  11012. }
  11013. /**
  11014. * Setups the default clipping.
  11015. *
  11016. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  11017. * @param {Array<Vector4>} unionPlanes - The union planes.
  11018. * @return {Node} The result node.
  11019. */
  11020. setupDefault( intersectionPlanes, unionPlanes ) {
  11021. return Fn( () => {
  11022. const numUnionPlanes = unionPlanes.length;
  11023. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  11024. const clippingPlanes = uniformArray( unionPlanes );
  11025. Loop( numUnionPlanes, ( { i } ) => {
  11026. const plane = clippingPlanes.element( i );
  11027. positionView.dot( plane.xyz ).greaterThan( plane.w ).discard();
  11028. } );
  11029. }
  11030. const numIntersectionPlanes = intersectionPlanes.length;
  11031. if ( numIntersectionPlanes > 0 ) {
  11032. const clippingPlanes = uniformArray( intersectionPlanes );
  11033. const clipped = bool( true ).toVar( 'clipped' );
  11034. Loop( numIntersectionPlanes, ( { i } ) => {
  11035. const plane = clippingPlanes.element( i );
  11036. clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) );
  11037. } );
  11038. clipped.discard();
  11039. }
  11040. } )();
  11041. }
  11042. /**
  11043. * Setups hardware clipping.
  11044. *
  11045. * @param {Array<Vector4>} unionPlanes - The union planes.
  11046. * @param {NodeBuilder} builder - The current node builder.
  11047. * @return {Node} The result node.
  11048. */
  11049. setupHardwareClipping( unionPlanes, builder ) {
  11050. const numUnionPlanes = unionPlanes.length;
  11051. builder.enableHardwareClipping( numUnionPlanes );
  11052. return Fn( () => {
  11053. const clippingPlanes = uniformArray( unionPlanes );
  11054. const hw_clip_distances = builtin( builder.getClipDistance() );
  11055. Loop( numUnionPlanes, ( { i } ) => {
  11056. const plane = clippingPlanes.element( i );
  11057. const distance = positionView.dot( plane.xyz ).sub( plane.w ).negate();
  11058. hw_clip_distances.element( i ).assign( distance );
  11059. } );
  11060. } )();
  11061. }
  11062. }
  11063. ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage';
  11064. ClippingNode.DEFAULT = 'default';
  11065. ClippingNode.HARDWARE = 'hardware';
  11066. /**
  11067. * TSL function for setting up the default clipping logic.
  11068. *
  11069. * @function
  11070. * @returns {ClippingNode}
  11071. */
  11072. const clipping = () => nodeObject( new ClippingNode() );
  11073. /**
  11074. * TSL function for setting up alpha to coverage.
  11075. *
  11076. * @function
  11077. * @returns {ClippingNode}
  11078. */
  11079. const clippingAlpha = () => nodeObject( new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE ) );
  11080. /**
  11081. * TSL function for setting up hardware-based clipping.
  11082. *
  11083. * @function
  11084. * @returns {ClippingNode}
  11085. */
  11086. const hardwareClipping = () => nodeObject( new ClippingNode( ClippingNode.HARDWARE ) );
  11087. // See: https://casual-effects.com/research/Wyman2017Hashed/index.html
  11088. const ALPHA_HASH_SCALE = 0.05; // Derived from trials only, and may be changed.
  11089. const hash2D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  11090. 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 ) ) ) ) ) );
  11091. } );
  11092. const hash3D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  11093. return hash2D( vec2( hash2D( value.xy ), value.z ) );
  11094. } );
  11095. const getAlphaHashThreshold = /*@__PURE__*/ Fn( ( [ position ] ) => {
  11096. // Find the discretized derivatives of our coordinates
  11097. const maxDeriv = max$1(
  11098. length( dFdx( position.xyz ) ),
  11099. length( dFdy( position.xyz ) )
  11100. );
  11101. const pixScale = float( 1 ).div( float( ALPHA_HASH_SCALE ).mul( maxDeriv ) ).toVar( 'pixScale' );
  11102. // Find two nearest log-discretized noise scales
  11103. const pixScales = vec2(
  11104. exp2( floor( log2( pixScale ) ) ),
  11105. exp2( ceil( log2( pixScale ) ) )
  11106. );
  11107. // Compute alpha thresholds at our two noise scales
  11108. const alpha = vec2(
  11109. hash3D( floor( pixScales.x.mul( position.xyz ) ) ),
  11110. hash3D( floor( pixScales.y.mul( position.xyz ) ) ),
  11111. );
  11112. // Factor to interpolate lerp with
  11113. const lerpFactor = fract( log2( pixScale ) );
  11114. // Interpolate alpha threshold from noise at two scales
  11115. const x = add( mul( lerpFactor.oneMinus(), alpha.x ), mul( lerpFactor, alpha.y ) );
  11116. // Pass into CDF to compute uniformly distrib threshold
  11117. const a = min$1( lerpFactor, lerpFactor.oneMinus() );
  11118. const cases = vec3(
  11119. x.mul( x ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ),
  11120. x.sub( mul( 0.5, a ) ).div( sub( 1.0, a ) ),
  11121. sub( 1.0, sub( 1.0, x ).mul( sub( 1.0, x ) ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ) ) );
  11122. // Find our final, uniformly distributed alpha threshold (ατ)
  11123. const threshold = x.lessThan( a.oneMinus() ).select( x.lessThan( a ).select( cases.x, cases.y ), cases.z );
  11124. // Avoids ατ == 0. Could also do ατ =1-ατ
  11125. return clamp( threshold, 1.0e-6, 1.0 );
  11126. } ).setLayout( {
  11127. name: 'getAlphaHashThreshold',
  11128. type: 'float',
  11129. inputs: [
  11130. { name: 'position', type: 'vec3' }
  11131. ]
  11132. } );
  11133. /**
  11134. * Base class for all node materials.
  11135. *
  11136. * @augments Material
  11137. */
  11138. class NodeMaterial extends Material {
  11139. static get type() {
  11140. return 'NodeMaterial';
  11141. }
  11142. /**
  11143. * Represents the type of the node material.
  11144. *
  11145. * @type {String}
  11146. */
  11147. get type() {
  11148. return this.constructor.type;
  11149. }
  11150. set type( _value ) { /* */ }
  11151. /**
  11152. * Constructs a new node material.
  11153. */
  11154. constructor() {
  11155. super();
  11156. /**
  11157. * This flag can be used for type testing.
  11158. *
  11159. * @type {Boolean}
  11160. * @readonly
  11161. * @default true
  11162. */
  11163. this.isNodeMaterial = true;
  11164. /**
  11165. * Whether this material is affected by fog or not.
  11166. *
  11167. * @type {Boolean}
  11168. * @default true
  11169. */
  11170. this.fog = true;
  11171. /**
  11172. * Whether this material is affected by lights or not.
  11173. *
  11174. * @type {Boolean}
  11175. * @default false
  11176. */
  11177. this.lights = false;
  11178. /**
  11179. * Whether this material uses hardware clipping or not.
  11180. * This property is managed by the engine and should not be
  11181. * modified by apps.
  11182. *
  11183. * @type {Boolean}
  11184. * @default false
  11185. */
  11186. this.hardwareClipping = false;
  11187. /**
  11188. * Node materials which set their `lights` property to `true`
  11189. * are affected by all lights of the scene. Sometimes selective
  11190. * lighting is wanted which means only _some_ lights in the scene
  11191. * affect a material. This can be achieved by creating an instance
  11192. * of {@link module:LightsNode~LightsNode} with a list of selective
  11193. * lights and assign the node to this property.
  11194. *
  11195. * ```js
  11196. * const customLightsNode = lights( [ light1, light2 ] );
  11197. * material.lightsNode = customLightsNode;
  11198. * ```
  11199. *
  11200. * @type {LightsNode?}
  11201. * @default null
  11202. */
  11203. this.lightsNode = null;
  11204. /**
  11205. * The environment of node materials can be defined by an environment
  11206. * map assigned to the `envMap` property or by `Scene.environment`
  11207. * if the node material is a PBR material. This node property allows to overwrite
  11208. * the default behavior and define the environment with a custom node.
  11209. *
  11210. * ```js
  11211. * material.envNode = pmremTexture( renderTarget.texture );
  11212. * ```
  11213. *
  11214. * @type {Node<vec3>?}
  11215. * @default null
  11216. */
  11217. this.envNode = null;
  11218. /**
  11219. * The lighting of node materials might be influenced by ambient occlusion.
  11220. * The default AO is inferred from an ambient occlusion map assigned to `aoMap`
  11221. * and the respective `aoMapIntensity`. This node property allows to overwrite
  11222. * the default and define the ambient occlusion with a custom node instead.
  11223. *
  11224. * If you don't want to overwrite the diffuse color but modify the existing
  11225. * values instead, use {@link module:MaterialNode.materialAO}.
  11226. *
  11227. * @type {Node<float>?}
  11228. * @default null
  11229. */
  11230. this.aoNode = null;
  11231. /**
  11232. * The diffuse color of node materials is by default inferred from the
  11233. * `color` and `map` properties. This node property allows to overwrite the default
  11234. * and define the diffuse color with a node instead.
  11235. *
  11236. * ```js
  11237. * material.colorNode = color( 0xff0000 ); // define red color
  11238. * ```
  11239. *
  11240. * If you don't want to overwrite the diffuse color but modify the existing
  11241. * values instead, use {@link module:MaterialNode.materialColor}.
  11242. *
  11243. * ```js
  11244. * material.colorNode = materialColor.mul( color( 0xff0000 ) ); // give diffuse colors a red tint
  11245. * ```
  11246. *
  11247. * @type {Node<vec3>?}
  11248. * @default null
  11249. */
  11250. this.colorNode = null;
  11251. /**
  11252. * The normals of node materials are by default inferred from the `normalMap`/`normalScale`
  11253. * or `bumpMap`/`bumpScale` properties. This node property allows to overwrite the default
  11254. * and define the normals with a node instead.
  11255. *
  11256. * If you don't want to overwrite the normals but modify the existing values instead,
  11257. * use {@link module:MaterialNode.materialNormal}.
  11258. *
  11259. * @type {Node<vec3>?}
  11260. * @default null
  11261. */
  11262. this.normalNode = null;
  11263. /**
  11264. * The opacity of node materials is by default inferred from the `opacity`
  11265. * and `alphaMap` properties. This node property allows to overwrite the default
  11266. * and define the opacity with a node instead.
  11267. *
  11268. * If you don't want to overwrite the normals but modify the existing
  11269. * value instead, use {@link module:MaterialNode.materialOpacity}.
  11270. *
  11271. * @type {Node<float>?}
  11272. * @default null
  11273. */
  11274. this.opacityNode = null;
  11275. /**
  11276. * This node can be used to to implement a variety of filter-like effects. The idea is
  11277. * to store the current rendering into a texture e.g. via `viewportSharedTexture()`, use it
  11278. * to create an arbitrary effect and then assign the node composition to this property.
  11279. * Everything behind the object using this material will now be affected by a filter.
  11280. *
  11281. * ```js
  11282. * const material = new NodeMaterial()
  11283. * material.transparent = true;
  11284. *
  11285. * // everything behind the object will be monochromatic
  11286. * material.backdropNode = viewportSharedTexture().rgb.saturation( 0 );
  11287. * ```
  11288. *
  11289. * Backdrop computations are part of the lighting so only lit materials can use this property.
  11290. *
  11291. * @type {Node<vec3>?}
  11292. * @default null
  11293. */
  11294. this.backdropNode = null;
  11295. /**
  11296. * This node allows to modulate the influence of `backdropNode` to the outgoing light.
  11297. *
  11298. * @type {Node<float>?}
  11299. * @default null
  11300. */
  11301. this.backdropAlphaNode = null;
  11302. /**
  11303. * The alpha test of node materials is by default inferred from the `alphaTest`
  11304. * property. This node property allows to overwrite the default and define the
  11305. * alpha test with a node instead.
  11306. *
  11307. * If you don't want to overwrite the alpha test but modify the existing
  11308. * value instead, use {@link module:MaterialNode.materialAlphaTest}.
  11309. *
  11310. * @type {Node<float>?}
  11311. * @default null
  11312. */
  11313. this.alphaTestNode = null;
  11314. /**
  11315. * The local vertex positions are computed based on multiple factors like the
  11316. * attribute data, morphing or skinning. This node property allows to overwrite
  11317. * the default and define local vertex positions with nodes instead.
  11318. *
  11319. * If you don't want to overwrite the vertex positions but modify the existing
  11320. * values instead, use {@link module:Position.positionLocal}.
  11321. *
  11322. *```js
  11323. * material.positionNode = positionLocal.add( displace );
  11324. * ```
  11325. *
  11326. * @type {Node<vec3>?}
  11327. * @default null
  11328. */
  11329. this.positionNode = null;
  11330. /**
  11331. * This node property is intended for logic which modifies geometry data once or per animation step.
  11332. * Apps usually place such logic randomly in initialization routines or in the animation loop.
  11333. * `geometryNode` is intended as a dedicated API so there is an intended spot where geometry modifications
  11334. * can be implemented.
  11335. *
  11336. * The idea is to assign a `Fn` definition that holds the geometry modification logic. A typical example
  11337. * would be a GPU based particle system that provides a node material for usage on app level. The particle
  11338. * simulation would be implemented as compute shaders and managed inside a `Fn` function. This function is
  11339. * eventually assigned to `geometryNode`.
  11340. *
  11341. * @type {Function}
  11342. * @default null
  11343. */
  11344. this.geometryNode = null;
  11345. /**
  11346. * Allows to overwrite depth values in the fragment shader.
  11347. *
  11348. * @type {Node<float>?}
  11349. * @default null
  11350. */
  11351. this.depthNode = null;
  11352. /**
  11353. * Allows to overwrite the position used for shadow map rendering which
  11354. * is by default {@link module:Position.positionWorld}, the vertex position
  11355. * in world space.
  11356. *
  11357. * @type {Node<float>?}
  11358. * @default null
  11359. */
  11360. this.shadowPositionNode = null;
  11361. /**
  11362. * This node can be used to influence how an object using this node material
  11363. * receive shadows.
  11364. *
  11365. * ```js
  11366. * const totalShadows = float( 1 ).toVar();
  11367. * material.receivedShadowNode = Fn( ( [ shadow ] ) => {
  11368. * totalShadows.mulAssign( shadow );
  11369. * //return float( 1 ); // bypass received shadows
  11370. * return shadow.mix( color( 0xff0000 ), 1 ); // modify shadow color
  11371. * } );
  11372. *
  11373. * @type {Node<vec4>?}
  11374. * @default null
  11375. */
  11376. this.receivedShadowNode = null;
  11377. /**
  11378. * This node can be used to influence how an object using this node material
  11379. * casts shadows. To apply a color to shadows, you can simply do:
  11380. *
  11381. * ```js
  11382. * material.castShadowNode = vec4( 1, 0, 0, 1 );
  11383. * ```
  11384. *
  11385. * Which can be nice to fake colored shadows of semi-transparent objects. It
  11386. * is also common to use the property with `Fn` function so checks are performed
  11387. * per fragment.
  11388. *
  11389. * ```js
  11390. * materialCustomShadow.castShadowNode = Fn( () => {
  11391. * hash( vertexIndex ).greaterThan( 0.5 ).discard();
  11392. * return materialColor;
  11393. * } )();
  11394. * ```
  11395. *
  11396. * @type {Node<vec4>?}
  11397. * @default null
  11398. */
  11399. this.castShadowNode = null;
  11400. /**
  11401. * This node can be used to define the final output of the material.
  11402. *
  11403. * TODO: Explain the differences to `fragmentNode`.
  11404. *
  11405. * @type {Node<vec4>?}
  11406. * @default null
  11407. */
  11408. this.outputNode = null;
  11409. /**
  11410. * MRT configuration is done on renderer or pass level. This node allows to
  11411. * overwrite what values are written into MRT targets on material level. This
  11412. * can be useful for implementing selective FX features that should only affect
  11413. * specific objects.
  11414. *
  11415. * @type {MRTNode?}
  11416. * @default null
  11417. */
  11418. this.mrtNode = null;
  11419. /**
  11420. * This node property can be used if you need complete freedom in implementing
  11421. * the fragment shader. Assigning a node will replace the built-in material
  11422. * logic used in the fragment stage.
  11423. *
  11424. * @type {Node<vec4>?}
  11425. * @default null
  11426. */
  11427. this.fragmentNode = null;
  11428. /**
  11429. * This node property can be used if you need complete freedom in implementing
  11430. * the vertex shader. Assigning a node will replace the built-in material logic
  11431. * used in the vertex stage.
  11432. *
  11433. * @type {Node<vec4>?}
  11434. * @default null
  11435. */
  11436. this.vertexNode = null;
  11437. }
  11438. /**
  11439. * Allows to define a custom cache key that influence the material key computation
  11440. * for render objects.
  11441. *
  11442. * @return {String} The custom cache key.
  11443. */
  11444. customProgramCacheKey() {
  11445. return this.type + getCacheKey$1( this );
  11446. }
  11447. /**
  11448. * Builds this material with the given node builder.
  11449. *
  11450. * @param {NodeBuilder} builder - The current node builder.
  11451. */
  11452. build( builder ) {
  11453. this.setup( builder );
  11454. }
  11455. /**
  11456. * Setups a node material observer with the given builder.
  11457. *
  11458. * @param {NodeBuilder} builder - The current node builder.
  11459. * @return {NodeMaterialObserver} The node material observer.
  11460. */
  11461. setupObserver( builder ) {
  11462. return new NodeMaterialObserver( builder );
  11463. }
  11464. /**
  11465. * Setups the vertex and fragment stage of this node material.
  11466. *
  11467. * @param {NodeBuilder} builder - The current node builder.
  11468. */
  11469. setup( builder ) {
  11470. builder.context.setupNormal = () => this.setupNormal( builder );
  11471. builder.context.setupPositionView = () => this.setupPositionView( builder );
  11472. builder.context.setupModelViewProjection = () => this.setupModelViewProjection( builder );
  11473. const renderer = builder.renderer;
  11474. const renderTarget = renderer.getRenderTarget();
  11475. // < VERTEX STAGE >
  11476. builder.addStack();
  11477. const vertexNode = this.vertexNode || this.setupVertex( builder );
  11478. builder.stack.outputNode = vertexNode;
  11479. this.setupHardwareClipping( builder );
  11480. if ( this.geometryNode !== null ) {
  11481. builder.stack.outputNode = builder.stack.outputNode.bypass( this.geometryNode );
  11482. }
  11483. builder.addFlow( 'vertex', builder.removeStack() );
  11484. // < FRAGMENT STAGE >
  11485. builder.addStack();
  11486. let resultNode;
  11487. const clippingNode = this.setupClipping( builder );
  11488. if ( this.depthWrite === true || this.depthTest === true ) {
  11489. // only write depth if depth buffer is configured
  11490. if ( renderTarget !== null ) {
  11491. if ( renderTarget.depthBuffer === true ) this.setupDepth( builder );
  11492. } else {
  11493. if ( renderer.depth === true ) this.setupDepth( builder );
  11494. }
  11495. }
  11496. if ( this.fragmentNode === null ) {
  11497. this.setupDiffuseColor( builder );
  11498. this.setupVariants( builder );
  11499. const outgoingLightNode = this.setupLighting( builder );
  11500. if ( clippingNode !== null ) builder.stack.add( clippingNode );
  11501. // force unsigned floats - useful for RenderTargets
  11502. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  11503. resultNode = this.setupOutput( builder, basicOutput );
  11504. // OUTPUT NODE
  11505. output.assign( resultNode );
  11506. //
  11507. if ( this.outputNode !== null ) resultNode = this.outputNode;
  11508. // MRT
  11509. if ( renderTarget !== null ) {
  11510. const mrt = renderer.getMRT();
  11511. const materialMRT = this.mrtNode;
  11512. if ( mrt !== null ) {
  11513. resultNode = mrt;
  11514. if ( materialMRT !== null ) {
  11515. resultNode = mrt.merge( materialMRT );
  11516. }
  11517. } else if ( materialMRT !== null ) {
  11518. resultNode = materialMRT;
  11519. }
  11520. }
  11521. } else {
  11522. let fragmentNode = this.fragmentNode;
  11523. if ( fragmentNode.isOutputStructNode !== true ) {
  11524. fragmentNode = vec4( fragmentNode );
  11525. }
  11526. resultNode = this.setupOutput( builder, fragmentNode );
  11527. }
  11528. builder.stack.outputNode = resultNode;
  11529. builder.addFlow( 'fragment', builder.removeStack() );
  11530. // < OBSERVER >
  11531. builder.observer = this.setupObserver( builder );
  11532. }
  11533. /**
  11534. * Setups the clipping node.
  11535. *
  11536. * @param {NodeBuilder} builder - The current node builder.
  11537. * @return {ClippingNode} The clipping node.
  11538. */
  11539. setupClipping( builder ) {
  11540. if ( builder.clippingContext === null ) return null;
  11541. const { unionPlanes, intersectionPlanes } = builder.clippingContext;
  11542. let result = null;
  11543. if ( unionPlanes.length > 0 || intersectionPlanes.length > 0 ) {
  11544. const samples = builder.renderer.samples;
  11545. if ( this.alphaToCoverage && samples > 1 ) {
  11546. // to be added to flow when the color/alpha value has been determined
  11547. result = clippingAlpha();
  11548. } else {
  11549. builder.stack.add( clipping() );
  11550. }
  11551. }
  11552. return result;
  11553. }
  11554. /**
  11555. * Setups the hardware clipping if available on the current device.
  11556. *
  11557. * @param {NodeBuilder} builder - The current node builder.
  11558. */
  11559. setupHardwareClipping( builder ) {
  11560. this.hardwareClipping = false;
  11561. if ( builder.clippingContext === null ) return;
  11562. const candidateCount = builder.clippingContext.unionPlanes.length;
  11563. // 8 planes supported by WebGL ANGLE_clip_cull_distance and WebGPU clip-distances
  11564. if ( candidateCount > 0 && candidateCount <= 8 && builder.isAvailable( 'clipDistance' ) ) {
  11565. builder.stack.add( hardwareClipping() );
  11566. this.hardwareClipping = true;
  11567. }
  11568. return;
  11569. }
  11570. /**
  11571. * Setups the depth of this material.
  11572. *
  11573. * @param {NodeBuilder} builder - The current node builder.
  11574. */
  11575. setupDepth( builder ) {
  11576. const { renderer, camera } = builder;
  11577. // Depth
  11578. let depthNode = this.depthNode;
  11579. if ( depthNode === null ) {
  11580. const mrt = renderer.getMRT();
  11581. if ( mrt && mrt.has( 'depth' ) ) {
  11582. depthNode = mrt.get( 'depth' );
  11583. } else if ( renderer.logarithmicDepthBuffer === true ) {
  11584. if ( camera.isPerspectiveCamera ) {
  11585. depthNode = viewZToLogarithmicDepth( positionView.z, cameraNear, cameraFar );
  11586. } else {
  11587. depthNode = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  11588. }
  11589. }
  11590. }
  11591. if ( depthNode !== null ) {
  11592. depth.assign( depthNode ).append();
  11593. }
  11594. }
  11595. /**
  11596. * Setups the position node in view space. This method exists
  11597. * so derived node materials can modify the implementation e.g. sprite materials.
  11598. *
  11599. * @param {NodeBuilder} builder - The current node builder.
  11600. * @return {Node<vec3>} The position in view space.
  11601. */
  11602. setupPositionView( /*builder*/ ) {
  11603. return modelViewMatrix.mul( positionLocal ).xyz;
  11604. }
  11605. /**
  11606. * Setups the position in clip space.
  11607. *
  11608. * @param {NodeBuilder} builder - The current node builder.
  11609. * @return {Node<vec4>} The position in view space.
  11610. */
  11611. setupModelViewProjection( /*builder*/ ) {
  11612. return cameraProjectionMatrix.mul( positionView );
  11613. }
  11614. /**
  11615. * Setups the logic for the vertex stage.
  11616. *
  11617. * @param {NodeBuilder} builder - The current node builder.
  11618. * @return {Node<vec4>} The position in clip space.
  11619. */
  11620. setupVertex( builder ) {
  11621. builder.addStack();
  11622. this.setupPosition( builder );
  11623. builder.context.vertex = builder.removeStack();
  11624. return modelViewProjection;
  11625. }
  11626. /**
  11627. * Setups the computation of the position in local space.
  11628. *
  11629. * @param {NodeBuilder} builder - The current node builder.
  11630. * @return {Node<vec3>} The position in local space.
  11631. */
  11632. setupPosition( builder ) {
  11633. const { object, geometry } = builder;
  11634. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  11635. morphReference( object ).append();
  11636. }
  11637. if ( object.isSkinnedMesh === true ) {
  11638. skinningReference( object ).append();
  11639. }
  11640. if ( this.displacementMap ) {
  11641. const displacementMap = materialReference( 'displacementMap', 'texture' );
  11642. const displacementScale = materialReference( 'displacementScale', 'float' );
  11643. const displacementBias = materialReference( 'displacementBias', 'float' );
  11644. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  11645. }
  11646. if ( object.isBatchedMesh ) {
  11647. batch( object ).append();
  11648. }
  11649. if ( ( object.isInstancedMesh && object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  11650. instancedMesh( object ).append();
  11651. }
  11652. if ( this.positionNode !== null ) {
  11653. positionLocal.assign( this.positionNode.context( { isPositionNodeInput: true } ) );
  11654. }
  11655. return positionLocal;
  11656. }
  11657. /**
  11658. * Setups the computation of the material's diffuse color.
  11659. *
  11660. * @param {NodeBuilder} builder - The current node builder.
  11661. * @param {BufferGeometry} geometry - The geometry.
  11662. */
  11663. setupDiffuseColor( { object, geometry } ) {
  11664. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  11665. // VERTEX COLORS
  11666. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  11667. colorNode = vec4( colorNode.xyz.mul( attribute( 'color', 'vec3' ) ), colorNode.a );
  11668. }
  11669. // Instanced colors
  11670. if ( object.instanceColor ) {
  11671. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  11672. colorNode = instanceColor.mul( colorNode );
  11673. }
  11674. if ( object.isBatchedMesh && object._colorsTexture ) {
  11675. const batchColor = varyingProperty( 'vec3', 'vBatchColor' );
  11676. colorNode = batchColor.mul( colorNode );
  11677. }
  11678. // COLOR
  11679. diffuseColor.assign( colorNode );
  11680. // OPACITY
  11681. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  11682. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  11683. // ALPHA TEST
  11684. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  11685. const alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  11686. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  11687. }
  11688. // ALPHA HASH
  11689. if ( this.alphaHash === true ) {
  11690. diffuseColor.a.lessThan( getAlphaHashThreshold( positionLocal ) ).discard();
  11691. }
  11692. if ( this.transparent === false && this.blending === NormalBlending && this.alphaToCoverage === false ) {
  11693. diffuseColor.a.assign( 1.0 );
  11694. }
  11695. }
  11696. /**
  11697. * Abstract interface method that can be implemented by derived materials
  11698. * to setup material-specific node variables.
  11699. *
  11700. * @abstract
  11701. * @param {NodeBuilder} builder - The current node builder.
  11702. */
  11703. setupVariants( /*builder*/ ) {
  11704. // Interface function.
  11705. }
  11706. /**
  11707. * Setups the outgoing light node variable
  11708. *
  11709. * @return {Node<vec3>} The outgoing light node.
  11710. */
  11711. setupOutgoingLight() {
  11712. return ( this.lights === true ) ? vec3( 0 ) : diffuseColor.rgb;
  11713. }
  11714. /**
  11715. * Setups the normal node from the material.
  11716. *
  11717. * @return {Node<vec3>} The normal node.
  11718. */
  11719. setupNormal() {
  11720. return this.normalNode ? vec3( this.normalNode ) : materialNormal;
  11721. }
  11722. /**
  11723. * Setups the environment node from the material.
  11724. *
  11725. * @param {NodeBuilder} builder - The current node builder.
  11726. * @return {Node<vec4>} The environment node.
  11727. */
  11728. setupEnvironment( /*builder*/ ) {
  11729. let node = null;
  11730. if ( this.envNode ) {
  11731. node = this.envNode;
  11732. } else if ( this.envMap ) {
  11733. node = this.envMap.isCubeTexture ? materialReference( 'envMap', 'cubeTexture' ) : materialReference( 'envMap', 'texture' );
  11734. }
  11735. return node;
  11736. }
  11737. /**
  11738. * Setups the light map node from the material.
  11739. *
  11740. * @param {NodeBuilder} builder - The current node builder.
  11741. * @return {Node<vec3>} The light map node.
  11742. */
  11743. setupLightMap( builder ) {
  11744. let node = null;
  11745. if ( builder.material.lightMap ) {
  11746. node = new IrradianceNode( materialLightMap );
  11747. }
  11748. return node;
  11749. }
  11750. /**
  11751. * Setups the lights node based on the scene, environment and material.
  11752. *
  11753. * @param {NodeBuilder} builder - The current node builder.
  11754. * @return {LightsNode} The lights node.
  11755. */
  11756. setupLights( builder ) {
  11757. const materialLightsNode = [];
  11758. //
  11759. const envNode = this.setupEnvironment( builder );
  11760. if ( envNode && envNode.isLightingNode ) {
  11761. materialLightsNode.push( envNode );
  11762. }
  11763. const lightMapNode = this.setupLightMap( builder );
  11764. if ( lightMapNode && lightMapNode.isLightingNode ) {
  11765. materialLightsNode.push( lightMapNode );
  11766. }
  11767. if ( this.aoNode !== null || builder.material.aoMap ) {
  11768. const aoNode = this.aoNode !== null ? this.aoNode : materialAO;
  11769. materialLightsNode.push( new AONode( aoNode ) );
  11770. }
  11771. let lightsN = this.lightsNode || builder.lightsNode;
  11772. if ( materialLightsNode.length > 0 ) {
  11773. lightsN = builder.renderer.lighting.createNode( [ ...lightsN.getLights(), ...materialLightsNode ] );
  11774. }
  11775. return lightsN;
  11776. }
  11777. /**
  11778. * This method should be implemented by most derived materials
  11779. * since it defines the material's lighting model.
  11780. *
  11781. * @abstract
  11782. * @param {NodeBuilder} builder - The current node builder.
  11783. * @return {LightingModel} The lighting model.
  11784. */
  11785. setupLightingModel( /*builder*/ ) {
  11786. // Interface function.
  11787. }
  11788. /**
  11789. * Setups the outgoing light node.
  11790. *
  11791. * @param {NodeBuilder} builder - The current node builder.
  11792. * @return {Node<vec3>} The outgoing light node.
  11793. */
  11794. setupLighting( builder ) {
  11795. const { material } = builder;
  11796. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  11797. // OUTGOING LIGHT
  11798. const lights = this.lights === true || this.lightsNode !== null;
  11799. const lightsNode = lights ? this.setupLights( builder ) : null;
  11800. let outgoingLightNode = this.setupOutgoingLight( builder );
  11801. if ( lightsNode && lightsNode.getScope().hasLights ) {
  11802. const lightingModel = this.setupLightingModel( builder );
  11803. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  11804. } else if ( backdropNode !== null ) {
  11805. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  11806. }
  11807. // EMISSIVE
  11808. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  11809. emissive.assign( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  11810. outgoingLightNode = outgoingLightNode.add( emissive );
  11811. }
  11812. return outgoingLightNode;
  11813. }
  11814. /**
  11815. * Setups the output node.
  11816. *
  11817. * @param {NodeBuilder} builder - The current node builder.
  11818. * @param {Node<vec4>} outputNode - The existing output node.
  11819. * @return {Node<vec4>} The output node.
  11820. */
  11821. setupOutput( builder, outputNode ) {
  11822. // FOG
  11823. if ( this.fog === true ) {
  11824. const fogNode = builder.fogNode;
  11825. if ( fogNode ) {
  11826. output.assign( outputNode );
  11827. outputNode = vec4( fogNode );
  11828. }
  11829. }
  11830. return outputNode;
  11831. }
  11832. /**
  11833. * Most classic material types have a node pendant e.g. for `MeshBasicMaterial`
  11834. * there is `MeshBasicNodeMaterial`. This utility method is intended for
  11835. * defining all material properties of the classic type in the node type.
  11836. *
  11837. * @param {Material} material - The material to copy properties with their values to this node material.
  11838. */
  11839. setDefaultValues( material ) {
  11840. // This approach is to reuse the native refreshUniforms*
  11841. // and turn available the use of features like transmission and environment in core
  11842. for ( const property in material ) {
  11843. const value = material[ property ];
  11844. if ( this[ property ] === undefined ) {
  11845. this[ property ] = value;
  11846. if ( value && value.clone ) this[ property ] = value.clone();
  11847. }
  11848. }
  11849. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  11850. for ( const key in descriptors ) {
  11851. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  11852. descriptors[ key ].get !== undefined ) {
  11853. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  11854. }
  11855. }
  11856. }
  11857. /**
  11858. * Serializes this material to JSON.
  11859. *
  11860. * @param {(Object|String)?} meta - The meta information for serialization.
  11861. * @return {Object} The serialized node.
  11862. */
  11863. toJSON( meta ) {
  11864. const isRoot = ( meta === undefined || typeof meta === 'string' );
  11865. if ( isRoot ) {
  11866. meta = {
  11867. textures: {},
  11868. images: {},
  11869. nodes: {}
  11870. };
  11871. }
  11872. const data = Material.prototype.toJSON.call( this, meta );
  11873. const nodeChildren = getNodeChildren( this );
  11874. data.inputNodes = {};
  11875. for ( const { property, childNode } of nodeChildren ) {
  11876. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  11877. }
  11878. // TODO: Copied from Object3D.toJSON
  11879. function extractFromCache( cache ) {
  11880. const values = [];
  11881. for ( const key in cache ) {
  11882. const data = cache[ key ];
  11883. delete data.metadata;
  11884. values.push( data );
  11885. }
  11886. return values;
  11887. }
  11888. if ( isRoot ) {
  11889. const textures = extractFromCache( meta.textures );
  11890. const images = extractFromCache( meta.images );
  11891. const nodes = extractFromCache( meta.nodes );
  11892. if ( textures.length > 0 ) data.textures = textures;
  11893. if ( images.length > 0 ) data.images = images;
  11894. if ( nodes.length > 0 ) data.nodes = nodes;
  11895. }
  11896. return data;
  11897. }
  11898. /**
  11899. * Copies the properties of the given node material to this instance.
  11900. *
  11901. * @param {NodeMaterial} source - The material to copy.
  11902. * @return {NodeMaterial} A reference to this node material.
  11903. */
  11904. copy( source ) {
  11905. this.lightsNode = source.lightsNode;
  11906. this.envNode = source.envNode;
  11907. this.colorNode = source.colorNode;
  11908. this.normalNode = source.normalNode;
  11909. this.opacityNode = source.opacityNode;
  11910. this.backdropNode = source.backdropNode;
  11911. this.backdropAlphaNode = source.backdropAlphaNode;
  11912. this.alphaTestNode = source.alphaTestNode;
  11913. this.positionNode = source.positionNode;
  11914. this.geometryNode = source.geometryNode;
  11915. this.depthNode = source.depthNode;
  11916. this.shadowPositionNode = source.shadowPositionNode;
  11917. this.receivedShadowNode = source.receivedShadowNode;
  11918. this.castShadowNode = source.castShadowNode;
  11919. this.outputNode = source.outputNode;
  11920. this.mrtNode = source.mrtNode;
  11921. this.fragmentNode = source.fragmentNode;
  11922. this.vertexNode = source.vertexNode;
  11923. return super.copy( source );
  11924. }
  11925. }
  11926. const _defaultValues$d = /*@__PURE__*/ new LineBasicMaterial();
  11927. /**
  11928. * Node material version of `LineBasicMaterial`.
  11929. *
  11930. * @augments NodeMaterial
  11931. */
  11932. class LineBasicNodeMaterial extends NodeMaterial {
  11933. static get type() {
  11934. return 'LineBasicNodeMaterial';
  11935. }
  11936. /**
  11937. * Constructs a new line basic node material.
  11938. *
  11939. * @param {Object?} parameters - The configuration parameter.
  11940. */
  11941. constructor( parameters ) {
  11942. super();
  11943. /**
  11944. * This flag can be used for type testing.
  11945. *
  11946. * @type {Boolean}
  11947. * @readonly
  11948. * @default true
  11949. */
  11950. this.isLineBasicNodeMaterial = true;
  11951. this.setDefaultValues( _defaultValues$d );
  11952. this.setValues( parameters );
  11953. }
  11954. }
  11955. const _defaultValues$c = /*@__PURE__*/ new LineDashedMaterial();
  11956. /**
  11957. * Node material version of `LineDashedMaterial`.
  11958. *
  11959. * @augments NodeMaterial
  11960. */
  11961. class LineDashedNodeMaterial extends NodeMaterial {
  11962. static get type() {
  11963. return 'LineDashedNodeMaterial';
  11964. }
  11965. /**
  11966. * Constructs a new line dashed node material.
  11967. *
  11968. * @param {Object?} parameters - The configuration parameter.
  11969. */
  11970. constructor( parameters ) {
  11971. super();
  11972. /**
  11973. * This flag can be used for type testing.
  11974. *
  11975. * @type {Boolean}
  11976. * @readonly
  11977. * @default true
  11978. */
  11979. this.isLineDashedNodeMaterial = true;
  11980. this.setDefaultValues( _defaultValues$c );
  11981. /**
  11982. * The dash offset.
  11983. *
  11984. * @type {Number}
  11985. * @default 0
  11986. */
  11987. this.dashOffset = 0;
  11988. /**
  11989. * The offset of dash materials is by default inferred from the `dashOffset`
  11990. * property. This node property allows to overwrite the default
  11991. * and define the offset with a node instead.
  11992. *
  11993. * If you don't want to overwrite the offset but modify the existing
  11994. * value instead, use {@link module:MaterialNode.materialLineDashOffset}.
  11995. *
  11996. * @type {Node<float>?}
  11997. * @default null
  11998. */
  11999. this.offsetNode = null;
  12000. /**
  12001. * The scale of dash materials is by default inferred from the `scale`
  12002. * property. This node property allows to overwrite the default
  12003. * and define the scale with a node instead.
  12004. *
  12005. * If you don't want to overwrite the scale but modify the existing
  12006. * value instead, use {@link module:MaterialNode.materialLineScale}.
  12007. *
  12008. * @type {Node<float>?}
  12009. * @default null
  12010. */
  12011. this.dashScaleNode = null;
  12012. /**
  12013. * The dash size of dash materials is by default inferred from the `dashSize`
  12014. * property. This node property allows to overwrite the default
  12015. * and define the dash size with a node instead.
  12016. *
  12017. * If you don't want to overwrite the dash size but modify the existing
  12018. * value instead, use {@link module:MaterialNode.materialLineDashSize}.
  12019. *
  12020. * @type {Node<float>?}
  12021. * @default null
  12022. */
  12023. this.dashSizeNode = null;
  12024. /**
  12025. * The gap size of dash materials is by default inferred from the `gapSize`
  12026. * property. This node property allows to overwrite the default
  12027. * and define the gap size with a node instead.
  12028. *
  12029. * If you don't want to overwrite the gap size but modify the existing
  12030. * value instead, use {@link module:MaterialNode.materialLineGapSize}.
  12031. *
  12032. * @type {Node<float>?}
  12033. * @default null
  12034. */
  12035. this.gapSizeNode = null;
  12036. this.setValues( parameters );
  12037. }
  12038. /**
  12039. * Setups the dash specific node variables.
  12040. *
  12041. * @param {NodeBuilder} builder - The current node builder.
  12042. */
  12043. setupVariants( /* builder */ ) {
  12044. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  12045. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  12046. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  12047. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  12048. dashSize.assign( dashSizeNode );
  12049. gapSize.assign( gapSizeNode );
  12050. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  12051. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  12052. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  12053. }
  12054. }
  12055. /** @module ViewportSharedTextureNode **/
  12056. let _sharedFramebuffer = null;
  12057. /**
  12058. * `ViewportTextureNode` creates an internal texture for each node instance. This module
  12059. * shares a texture across all instances of `ViewportSharedTextureNode`. It should
  12060. * be the first choice when using data of the default/screen framebuffer for performance reasons.
  12061. *
  12062. * @augments module:ViewportTextureNode~ViewportTextureNode
  12063. */
  12064. class ViewportSharedTextureNode extends ViewportTextureNode {
  12065. static get type() {
  12066. return 'ViewportSharedTextureNode';
  12067. }
  12068. /**
  12069. * Constructs a new viewport shared texture node.
  12070. *
  12071. * @param {Node} [uvNode=screenUV] - The uv node.
  12072. * @param {Node?} [levelNode=null] - The level node.
  12073. */
  12074. constructor( uvNode = screenUV, levelNode = null ) {
  12075. if ( _sharedFramebuffer === null ) {
  12076. _sharedFramebuffer = new FramebufferTexture();
  12077. }
  12078. super( uvNode, levelNode, _sharedFramebuffer );
  12079. }
  12080. updateReference() {
  12081. return this;
  12082. }
  12083. }
  12084. /**
  12085. * TSL function for creating a shared viewport texture node.
  12086. *
  12087. * @function
  12088. * @param {Node} [uvNode=screenUV] - The uv node.
  12089. * @param {Node?} [levelNode=null] - The level node.
  12090. * @returns {ViewportSharedTextureNode}
  12091. */
  12092. const viewportSharedTexture = /*@__PURE__*/ nodeProxy( ViewportSharedTextureNode );
  12093. const _defaultValues$b = /*@__PURE__*/ new LineDashedMaterial();
  12094. /**
  12095. * This node material can be used to render lines with a size larger than one
  12096. * by representing them as instanced meshes.
  12097. *
  12098. * @augments NodeMaterial
  12099. */
  12100. class Line2NodeMaterial extends NodeMaterial {
  12101. static get type() {
  12102. return 'Line2NodeMaterial';
  12103. }
  12104. /**
  12105. * Constructs a new node material for wide line rendering.
  12106. *
  12107. * @param {Object?} parameters - The configuration parameter.
  12108. */
  12109. constructor( parameters = {} ) {
  12110. super();
  12111. /**
  12112. * This flag can be used for type testing.
  12113. *
  12114. * @type {Boolean}
  12115. * @readonly
  12116. * @default true
  12117. */
  12118. this.isLine2NodeMaterial = true;
  12119. this.setDefaultValues( _defaultValues$b );
  12120. /**
  12121. * Whether vertex colors should be used or not.
  12122. *
  12123. * @type {Boolean}
  12124. * @default false
  12125. */
  12126. this.useColor = parameters.vertexColors;
  12127. /**
  12128. * The dash offset.
  12129. *
  12130. * @type {Number}
  12131. * @default 0
  12132. */
  12133. this.dashOffset = 0;
  12134. /**
  12135. * The line width.
  12136. *
  12137. * @type {Number}
  12138. * @default 0
  12139. */
  12140. this.lineWidth = 1;
  12141. /**
  12142. * Defines the lines color.
  12143. *
  12144. * @type {Node<vec3>?}
  12145. * @default null
  12146. */
  12147. this.lineColorNode = null;
  12148. /**
  12149. * Defines the offset.
  12150. *
  12151. * @type {Node<float>?}
  12152. * @default null
  12153. */
  12154. this.offsetNode = null;
  12155. /**
  12156. * Defines the dash scale.
  12157. *
  12158. * @type {Node<float>?}
  12159. * @default null
  12160. */
  12161. this.dashScaleNode = null;
  12162. /**
  12163. * Defines the dash size.
  12164. *
  12165. * @type {Node<float>?}
  12166. * @default null
  12167. */
  12168. this.dashSizeNode = null;
  12169. /**
  12170. * Defines the gap size.
  12171. *
  12172. * @type {Node<float>?}
  12173. * @default null
  12174. */
  12175. this.gapSizeNode = null;
  12176. /**
  12177. * Blending is set to `NoBlending` since transparency
  12178. * is not supported, yet.
  12179. *
  12180. * @type {Number}
  12181. * @default 0
  12182. */
  12183. this.blending = NoBlending;
  12184. this._useDash = parameters.dashed;
  12185. this._useAlphaToCoverage = true;
  12186. this._useWorldUnits = false;
  12187. this.setValues( parameters );
  12188. }
  12189. /**
  12190. * Setups the vertex and fragment stage of this node material.
  12191. *
  12192. * @param {NodeBuilder} builder - The current node builder.
  12193. */
  12194. setup( builder ) {
  12195. const { renderer } = builder;
  12196. const useAlphaToCoverage = this._useAlphaToCoverage;
  12197. const useColor = this.useColor;
  12198. const useDash = this._useDash;
  12199. const useWorldUnits = this._useWorldUnits;
  12200. const trimSegment = Fn( ( { start, end } ) => {
  12201. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  12202. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  12203. const nearEstimate = b.mul( -0.5 ).div( a );
  12204. const alpha = nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  12205. return vec4( mix( start.xyz, end.xyz, alpha ), end.w );
  12206. } ).setLayout( {
  12207. name: 'trimSegment',
  12208. type: 'vec4',
  12209. inputs: [
  12210. { name: 'start', type: 'vec4' },
  12211. { name: 'end', type: 'vec4' }
  12212. ]
  12213. } );
  12214. this.vertexNode = Fn( () => {
  12215. const instanceStart = attribute( 'instanceStart' );
  12216. const instanceEnd = attribute( 'instanceEnd' );
  12217. // camera space
  12218. const start = vec4( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ).toVar( 'start' );
  12219. const end = vec4( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) ).toVar( 'end' );
  12220. if ( useDash ) {
  12221. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  12222. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  12223. const instanceDistanceStart = attribute( 'instanceDistanceStart' );
  12224. const instanceDistanceEnd = attribute( 'instanceDistanceEnd' );
  12225. let lineDistance = positionGeometry.y.lessThan( 0.5 ).select( dashScaleNode.mul( instanceDistanceStart ), dashScaleNode.mul( instanceDistanceEnd ) );
  12226. lineDistance = lineDistance.add( offsetNode );
  12227. varyingProperty( 'float', 'lineDistance' ).assign( lineDistance );
  12228. }
  12229. if ( useWorldUnits ) {
  12230. varyingProperty( 'vec3', 'worldStart' ).assign( start.xyz );
  12231. varyingProperty( 'vec3', 'worldEnd' ).assign( end.xyz );
  12232. }
  12233. const aspect = viewport.z.div( viewport.w );
  12234. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  12235. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  12236. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  12237. // perhaps there is a more elegant solution -- WestLangley
  12238. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( -1 ); // 4th entry in the 3rd column
  12239. If( perspective, () => {
  12240. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  12241. end.assign( trimSegment( { start: start, end: end } ) );
  12242. } ).ElseIf( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  12243. start.assign( trimSegment( { start: end, end: start } ) );
  12244. } );
  12245. } );
  12246. // clip space
  12247. const clipStart = cameraProjectionMatrix.mul( start );
  12248. const clipEnd = cameraProjectionMatrix.mul( end );
  12249. // ndc space
  12250. const ndcStart = clipStart.xyz.div( clipStart.w );
  12251. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  12252. // direction
  12253. const dir = ndcEnd.xy.sub( ndcStart.xy ).toVar();
  12254. // account for clip-space aspect ratio
  12255. dir.x.assign( dir.x.mul( aspect ) );
  12256. dir.assign( dir.normalize() );
  12257. const clip = vec4().toVar();
  12258. if ( useWorldUnits ) {
  12259. // get the offset direction as perpendicular to the view vector
  12260. const worldDir = end.xyz.sub( start.xyz ).normalize();
  12261. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  12262. const worldUp = worldDir.cross( tmpFwd ).normalize();
  12263. const worldFwd = worldDir.cross( worldUp );
  12264. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  12265. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).select( start, end ) );
  12266. // height offset
  12267. const hw = materialLineWidth.mul( 0.5 );
  12268. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).select( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  12269. // don't extend the line if we're rendering dashes because we
  12270. // won't be rendering the endcaps
  12271. if ( ! useDash ) {
  12272. // cap extension
  12273. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).select( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  12274. // add width to the box
  12275. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  12276. // endcaps
  12277. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  12278. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  12279. } );
  12280. }
  12281. // project the worldpos
  12282. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  12283. // shift the depth of the projected points so the line
  12284. // segments overlap neatly
  12285. const clipPose = vec3().toVar();
  12286. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).select( ndcStart, ndcEnd ) );
  12287. clip.z.assign( clipPose.z.mul( clip.w ) );
  12288. } else {
  12289. const offset = vec2( dir.y, dir.x.negate() ).toVar( 'offset' );
  12290. // undo aspect ratio adjustment
  12291. dir.x.assign( dir.x.div( aspect ) );
  12292. offset.x.assign( offset.x.div( aspect ) );
  12293. // sign flip
  12294. offset.assign( positionGeometry.x.lessThan( 0.0 ).select( offset.negate(), offset ) );
  12295. // endcaps
  12296. If( positionGeometry.y.lessThan( 0.0 ), () => {
  12297. offset.assign( offset.sub( dir ) );
  12298. } ).ElseIf( positionGeometry.y.greaterThan( 1.0 ), () => {
  12299. offset.assign( offset.add( dir ) );
  12300. } );
  12301. // adjust for linewidth
  12302. offset.assign( offset.mul( materialLineWidth ) );
  12303. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  12304. offset.assign( offset.div( viewport.w ) );
  12305. // select end
  12306. clip.assign( positionGeometry.y.lessThan( 0.5 ).select( clipStart, clipEnd ) );
  12307. // back to clip space
  12308. offset.assign( offset.mul( clip.w ) );
  12309. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  12310. }
  12311. return clip;
  12312. } )();
  12313. const closestLineToLine = Fn( ( { p1, p2, p3, p4 } ) => {
  12314. const p13 = p1.sub( p3 );
  12315. const p43 = p4.sub( p3 );
  12316. const p21 = p2.sub( p1 );
  12317. const d1343 = p13.dot( p43 );
  12318. const d4321 = p43.dot( p21 );
  12319. const d1321 = p13.dot( p21 );
  12320. const d4343 = p43.dot( p43 );
  12321. const d2121 = p21.dot( p21 );
  12322. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  12323. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  12324. const mua = numer.div( denom ).clamp();
  12325. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  12326. return vec2( mua, mub );
  12327. } );
  12328. this.colorNode = Fn( () => {
  12329. const vUv = uv();
  12330. if ( useDash ) {
  12331. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  12332. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  12333. dashSize.assign( dashSizeNode );
  12334. gapSize.assign( gapSizeNode );
  12335. const vLineDistance = varyingProperty( 'float', 'lineDistance' );
  12336. vUv.y.lessThan( -1 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  12337. vLineDistance.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  12338. }
  12339. const alpha = float( 1 ).toVar( 'alpha' );
  12340. if ( useWorldUnits ) {
  12341. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  12342. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  12343. // Find the closest points on the view ray and the line segment
  12344. const rayEnd = varyingProperty( 'vec4', 'worldPos' ).xyz.normalize().mul( 1e5 );
  12345. const lineDir = worldEnd.sub( worldStart );
  12346. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  12347. const p1 = worldStart.add( lineDir.mul( params.x ) );
  12348. const p2 = rayEnd.mul( params.y );
  12349. const delta = p1.sub( p2 );
  12350. const len = delta.length();
  12351. const norm = len.div( materialLineWidth );
  12352. if ( ! useDash ) {
  12353. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  12354. const dnorm = norm.fwidth();
  12355. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  12356. } else {
  12357. norm.greaterThan( 0.5 ).discard();
  12358. }
  12359. }
  12360. } else {
  12361. // round endcaps
  12362. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  12363. const a = vUv.x;
  12364. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  12365. const len2 = a.mul( a ).add( b.mul( b ) );
  12366. const dlen = float( len2.fwidth() ).toVar( 'dlen' );
  12367. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  12368. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  12369. } );
  12370. } else {
  12371. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  12372. const a = vUv.x;
  12373. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  12374. const len2 = a.mul( a ).add( b.mul( b ) );
  12375. len2.greaterThan( 1.0 ).discard();
  12376. } );
  12377. }
  12378. }
  12379. let lineColorNode;
  12380. if ( this.lineColorNode ) {
  12381. lineColorNode = this.lineColorNode;
  12382. } else {
  12383. if ( useColor ) {
  12384. const instanceColorStart = attribute( 'instanceColorStart' );
  12385. const instanceColorEnd = attribute( 'instanceColorEnd' );
  12386. const instanceColor = positionGeometry.y.lessThan( 0.5 ).select( instanceColorStart, instanceColorEnd );
  12387. lineColorNode = instanceColor.mul( materialColor );
  12388. } else {
  12389. lineColorNode = materialColor;
  12390. }
  12391. }
  12392. return vec4( lineColorNode, alpha );
  12393. } )();
  12394. if ( this.transparent ) {
  12395. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  12396. this.outputNode = vec4( this.colorNode.rgb.mul( opacityNode ).add( viewportSharedTexture().rgb.mul( opacityNode.oneMinus() ) ), this.colorNode.a );
  12397. }
  12398. super.setup( builder );
  12399. }
  12400. /**
  12401. * Whether the lines should sized in world units or not.
  12402. * When set to `false` the unit is pixel.
  12403. *
  12404. * @type {Boolean}
  12405. * @default false
  12406. */
  12407. get worldUnits() {
  12408. return this._useWorldUnits;
  12409. }
  12410. set worldUnits( value ) {
  12411. if ( this._useWorldUnits !== value ) {
  12412. this._useWorldUnits = value;
  12413. this.needsUpdate = true;
  12414. }
  12415. }
  12416. /**
  12417. * Whether the lines should be dashed or not.
  12418. *
  12419. * @type {Boolean}
  12420. * @default false
  12421. */
  12422. get dashed() {
  12423. return this._useDash;
  12424. }
  12425. set dashed( value ) {
  12426. if ( this._useDash !== value ) {
  12427. this._useDash = value;
  12428. this.needsUpdate = true;
  12429. }
  12430. }
  12431. /**
  12432. * Whether alpha to coverage should be used or not.
  12433. *
  12434. * @type {Boolean}
  12435. * @default true
  12436. */
  12437. get alphaToCoverage() {
  12438. return this._useAlphaToCoverage;
  12439. }
  12440. set alphaToCoverage( value ) {
  12441. if ( this._useAlphaToCoverage !== value ) {
  12442. this._useAlphaToCoverage = value;
  12443. this.needsUpdate = true;
  12444. }
  12445. }
  12446. }
  12447. /** @module Packing **/
  12448. /**
  12449. * Packs a direction vector into a color value.
  12450. *
  12451. * @method
  12452. * @param {Node<vec3>} node - The direction to pack.
  12453. * @return {Node<vec3>} The color.
  12454. */
  12455. const directionToColor = ( node ) => nodeObject( node ).mul( 0.5 ).add( 0.5 );
  12456. /**
  12457. * Unpacks a color value into a direction vector.
  12458. *
  12459. * @method
  12460. * @param {Node<vec3>} node - The color to unpack.
  12461. * @return {Node<vec3>} The direction.
  12462. */
  12463. const colorToDirection = ( node ) => nodeObject( node ).mul( 2.0 ).sub( 1 );
  12464. const _defaultValues$a = /*@__PURE__*/ new MeshNormalMaterial();
  12465. /**
  12466. * Node material version of `MeshNormalMaterial`.
  12467. *
  12468. * @augments NodeMaterial
  12469. */
  12470. class MeshNormalNodeMaterial extends NodeMaterial {
  12471. static get type() {
  12472. return 'MeshNormalNodeMaterial';
  12473. }
  12474. /**
  12475. * Constructs a new mesh normal node material.
  12476. *
  12477. * @param {Object?} parameters - The configuration parameter.
  12478. */
  12479. constructor( parameters ) {
  12480. super();
  12481. /**
  12482. * This flag can be used for type testing.
  12483. *
  12484. * @type {Boolean}
  12485. * @readonly
  12486. * @default true
  12487. */
  12488. this.isMeshNormalNodeMaterial = true;
  12489. this.setDefaultValues( _defaultValues$a );
  12490. this.setValues( parameters );
  12491. }
  12492. /**
  12493. * Overwrites the default implementation by computing the diffuse color
  12494. * based on the normal data.
  12495. */
  12496. setupDiffuseColor() {
  12497. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  12498. diffuseColor.assign( vec4( directionToColor( transformedNormalView ), opacityNode ) );
  12499. }
  12500. }
  12501. /** @module EquirectUVNode **/
  12502. /**
  12503. * Can be used to compute texture coordinates for projecting an
  12504. * equirectangular texture onto a mesh for using it as the scene's
  12505. * background.
  12506. *
  12507. * ```js
  12508. * scene.backgroundNode = texture( equirectTexture, equirectUV() );
  12509. * ```
  12510. *
  12511. * @augments TempNode
  12512. */
  12513. class EquirectUVNode extends TempNode {
  12514. static get type() {
  12515. return 'EquirectUVNode';
  12516. }
  12517. /**
  12518. * Constructs a new equirect uv node.
  12519. *
  12520. * @param {Node<vec3>} [dirNode=positionWorldDirection] - A direction vector for sampling which is by default `positionWorldDirection`.
  12521. */
  12522. constructor( dirNode = positionWorldDirection ) {
  12523. super( 'vec2' );
  12524. /**
  12525. * A direction vector for sampling why is by default `positionWorldDirection`.
  12526. *
  12527. * @type {Node<vec3>}
  12528. */
  12529. this.dirNode = dirNode;
  12530. }
  12531. setup() {
  12532. const dir = this.dirNode;
  12533. const u = dir.z.atan( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  12534. const v = dir.y.clamp( -1, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  12535. return vec2( u, v );
  12536. }
  12537. }
  12538. /**
  12539. * TSL function for creating an equirect uv node.
  12540. *
  12541. * @function
  12542. * @param {Node<vec3>} [dirNode=positionWorldDirection] - A direction vector for sampling which is by default `positionWorldDirection`.
  12543. * @returns {EquirectUVNode}
  12544. */
  12545. const equirectUV = /*@__PURE__*/ nodeProxy( EquirectUVNode );
  12546. // @TODO: Consider rename WebGLCubeRenderTarget to just CubeRenderTarget
  12547. /**
  12548. * This class represents a cube render target. It is a special version
  12549. * of `WebGLCubeRenderTarget` which is compatible with `WebGPURenderer`.
  12550. *
  12551. * @augments WebGLCubeRenderTarget
  12552. */
  12553. class CubeRenderTarget extends WebGLCubeRenderTarget {
  12554. constructor( size = 1, options = {} ) {
  12555. super( size, options );
  12556. this.isCubeRenderTarget = true;
  12557. }
  12558. /**
  12559. * Converts the given equirectangular texture to a cube map.
  12560. *
  12561. * @param {Renderer} renderer - The renderer.
  12562. * @param {Texture} texture - The equirectangular texture.
  12563. * @return {CubeRenderTarget} A reference to this cube render target.
  12564. */
  12565. fromEquirectangularTexture( renderer, texture$1 ) {
  12566. const currentMinFilter = texture$1.minFilter;
  12567. const currentGenerateMipmaps = texture$1.generateMipmaps;
  12568. texture$1.generateMipmaps = true;
  12569. this.texture.type = texture$1.type;
  12570. this.texture.colorSpace = texture$1.colorSpace;
  12571. this.texture.generateMipmaps = texture$1.generateMipmaps;
  12572. this.texture.minFilter = texture$1.minFilter;
  12573. this.texture.magFilter = texture$1.magFilter;
  12574. const geometry = new BoxGeometry( 5, 5, 5 );
  12575. const uvNode = equirectUV( positionWorldDirection );
  12576. const material = new NodeMaterial();
  12577. material.colorNode = texture( texture$1, uvNode, 0 );
  12578. material.side = BackSide;
  12579. material.blending = NoBlending;
  12580. const mesh = new Mesh( geometry, material );
  12581. const scene = new Scene();
  12582. scene.add( mesh );
  12583. // Avoid blurred poles
  12584. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  12585. const camera = new CubeCamera( 1, 10, this );
  12586. const currentMRT = renderer.getMRT();
  12587. renderer.setMRT( null );
  12588. camera.update( renderer, scene );
  12589. renderer.setMRT( currentMRT );
  12590. texture$1.minFilter = currentMinFilter;
  12591. texture$1.currentGenerateMipmaps = currentGenerateMipmaps;
  12592. mesh.geometry.dispose();
  12593. mesh.material.dispose();
  12594. return this;
  12595. }
  12596. }
  12597. /** @module CubeMapNode **/
  12598. const _cache$1 = new WeakMap();
  12599. /**
  12600. * This node can be used to automatically convert environment maps in the
  12601. * equirectangular format into the cube map format.
  12602. *
  12603. * @augments TempNode
  12604. */
  12605. class CubeMapNode extends TempNode {
  12606. static get type() {
  12607. return 'CubeMapNode';
  12608. }
  12609. /**
  12610. * Constructs a new cube map node.
  12611. *
  12612. * @param {Node} envNode - The node representing the environment map.
  12613. */
  12614. constructor( envNode ) {
  12615. super( 'vec3' );
  12616. /**
  12617. * The node representing the environment map.
  12618. *
  12619. * @type {Node}
  12620. */
  12621. this.envNode = envNode;
  12622. /**
  12623. * A reference to the internal cube texture.
  12624. *
  12625. * @private
  12626. * @type {CubeTexture}
  12627. * @default null
  12628. */
  12629. this._cubeTexture = null;
  12630. /**
  12631. * A reference to the internal cube texture node.
  12632. *
  12633. * @private
  12634. * @type {CubeTextureNode}
  12635. */
  12636. this._cubeTextureNode = cubeTexture();
  12637. const defaultTexture = new CubeTexture();
  12638. defaultTexture.isRenderTargetTexture = true;
  12639. /**
  12640. * A default cube texture that acts as a placeholder.
  12641. * It is used when the conversion from equirectangular to cube
  12642. * map has not finished yet for a given texture.
  12643. *
  12644. * @private
  12645. * @type {CubeTexture}
  12646. */
  12647. this._defaultTexture = defaultTexture;
  12648. /**
  12649. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  12650. * the texture once per render in its {@link CubeMapNode#updateBefore} method.
  12651. *
  12652. * @type {String}
  12653. * @default 'render'
  12654. */
  12655. this.updateBeforeType = NodeUpdateType.RENDER;
  12656. }
  12657. updateBefore( frame ) {
  12658. const { renderer, material } = frame;
  12659. const envNode = this.envNode;
  12660. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  12661. const texture = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  12662. if ( texture && texture.isTexture ) {
  12663. const mapping = texture.mapping;
  12664. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  12665. // check for converted cubemap map
  12666. if ( _cache$1.has( texture ) ) {
  12667. const cubeMap = _cache$1.get( texture );
  12668. mapTextureMapping( cubeMap, texture.mapping );
  12669. this._cubeTexture = cubeMap;
  12670. } else {
  12671. // create cube map from equirectangular map
  12672. const image = texture.image;
  12673. if ( isEquirectangularMapReady$1( image ) ) {
  12674. const renderTarget = new CubeRenderTarget( image.height );
  12675. renderTarget.fromEquirectangularTexture( renderer, texture );
  12676. mapTextureMapping( renderTarget.texture, texture.mapping );
  12677. this._cubeTexture = renderTarget.texture;
  12678. _cache$1.set( texture, renderTarget.texture );
  12679. texture.addEventListener( 'dispose', onTextureDispose );
  12680. } else {
  12681. // default cube texture as fallback when equirectangular texture is not yet loaded
  12682. this._cubeTexture = this._defaultTexture;
  12683. }
  12684. }
  12685. //
  12686. this._cubeTextureNode.value = this._cubeTexture;
  12687. } else {
  12688. // envNode already refers to a cube map
  12689. this._cubeTextureNode = this.envNode;
  12690. }
  12691. }
  12692. }
  12693. }
  12694. setup( builder ) {
  12695. this.updateBefore( builder );
  12696. return this._cubeTextureNode;
  12697. }
  12698. }
  12699. /**
  12700. * Returns true if the given equirectangular image has been fully loaded
  12701. * and is ready for further processing.
  12702. *
  12703. * @private
  12704. * @param {Image} image - The equirectangular image to check.
  12705. * @return {Boolean} Whether the image is ready or not.
  12706. */
  12707. function isEquirectangularMapReady$1( image ) {
  12708. if ( image === null || image === undefined ) return false;
  12709. return image.height > 0;
  12710. }
  12711. /**
  12712. * This function is executed when `dispose()` is called on the equirectangular
  12713. * texture. In this case, the generated cube map with its render target
  12714. * is deleted as well.
  12715. *
  12716. * @private
  12717. * @param {Object} event - The event object.
  12718. */
  12719. function onTextureDispose( event ) {
  12720. const texture = event.target;
  12721. texture.removeEventListener( 'dispose', onTextureDispose );
  12722. const renderTarget = _cache$1.get( texture );
  12723. if ( renderTarget !== undefined ) {
  12724. _cache$1.delete( texture );
  12725. renderTarget.dispose();
  12726. }
  12727. }
  12728. /**
  12729. * This function makes sure the generated cube map uses the correct
  12730. * texture mapping that corresponds to the equirectangular original.
  12731. *
  12732. * @private
  12733. * @param {Texture} texture - The cube texture.
  12734. * @param {Number} mapping - The original texture mapping.
  12735. */
  12736. function mapTextureMapping( texture, mapping ) {
  12737. if ( mapping === EquirectangularReflectionMapping ) {
  12738. texture.mapping = CubeReflectionMapping;
  12739. } else if ( mapping === EquirectangularRefractionMapping ) {
  12740. texture.mapping = CubeRefractionMapping;
  12741. }
  12742. }
  12743. /**
  12744. * TSL function for creating a cube map node.
  12745. *
  12746. * @function
  12747. * @param {Node} envNode - The node representing the environment map.
  12748. * @returns {CubeMapNode}
  12749. */
  12750. const cubeMapNode = /*@__PURE__*/ nodeProxy( CubeMapNode );
  12751. /**
  12752. * Represents a basic model for Image-based lighting (IBL). The environment
  12753. * is defined via environment maps in the equirectangular or cube map format.
  12754. * `BasicEnvironmentNode` is intended for non-PBR materials like {@link MeshBasicNodeMaterial}
  12755. * or {@link MeshPhongNodeMaterial}.
  12756. *
  12757. * @augments LightingNode
  12758. */
  12759. class BasicEnvironmentNode extends LightingNode {
  12760. static get type() {
  12761. return 'BasicEnvironmentNode';
  12762. }
  12763. /**
  12764. * Constructs a new basic environment node.
  12765. *
  12766. * @param {Node} [envNode=null] - A node representing the environment.
  12767. */
  12768. constructor( envNode = null ) {
  12769. super();
  12770. /**
  12771. * A node representing the environment.
  12772. *
  12773. * @type {Node}
  12774. * @default null
  12775. */
  12776. this.envNode = envNode;
  12777. }
  12778. setup( builder ) {
  12779. // environment property is used in the finish() method of BasicLightingModel
  12780. builder.context.environment = cubeMapNode( this.envNode );
  12781. }
  12782. }
  12783. /**
  12784. * A specific version of {@link IrradianceNode} that is only relevant
  12785. * for {@link MeshBasicNodeMaterial}. Since the material is unlit, it
  12786. * requires a special scaling factor for the light map.
  12787. *
  12788. * @augments LightingNode
  12789. */
  12790. class BasicLightMapNode extends LightingNode {
  12791. static get type() {
  12792. return 'BasicLightMapNode';
  12793. }
  12794. /**
  12795. * Constructs a new basic light map node.
  12796. *
  12797. * @param {Node<vec3>?} [lightMapNode=null] - The light map node.
  12798. */
  12799. constructor( lightMapNode = null ) {
  12800. super();
  12801. /**
  12802. * The light map node.
  12803. *
  12804. * @type {Node<vec3>?}
  12805. */
  12806. this.lightMapNode = lightMapNode;
  12807. }
  12808. setup( builder ) {
  12809. // irradianceLightMap property is used in the indirectDiffuse() method of BasicLightingModel
  12810. const RECIPROCAL_PI = float( 1 / Math.PI );
  12811. builder.context.irradianceLightMap = this.lightMapNode.mul( RECIPROCAL_PI );
  12812. }
  12813. }
  12814. /**
  12815. * Abstract class for implementing lighting models. The module defines
  12816. * multiple methods that concrete lighting models can implement. These
  12817. * methods are executed at different points during the light evaluation
  12818. * process.
  12819. */
  12820. class LightingModel {
  12821. /**
  12822. * This method is intended for setting up lighting model and context data
  12823. * which are later used in the evaluation process.
  12824. *
  12825. * @abstract
  12826. * @param {ContextNode} input - The current node context.
  12827. * @param {StackNode} stack - The current stack.
  12828. * @param {NodeBuilder} builder - The current node builder.
  12829. */
  12830. start( /*input, stack, builder*/ ) { }
  12831. /**
  12832. * This method is intended for executing final tasks like final updates
  12833. * to the outgoing light.
  12834. *
  12835. * @abstract
  12836. * @param {ContextNode} input - The current node context.
  12837. * @param {StackNode} stack - The current stack.
  12838. * @param {NodeBuilder} builder - The current node builder.
  12839. */
  12840. finish( /*input, stack, builder*/ ) { }
  12841. /**
  12842. * This method is intended for implementing the direct light term and
  12843. * executed during the build process of directional, point and spot light nodes.
  12844. *
  12845. * @abstract
  12846. * @param {Object} input - The input data.
  12847. * @param {StackNode} stack - The current stack.
  12848. * @param {NodeBuilder} builder - The current node builder.
  12849. */
  12850. direct( /*input, stack, builder*/ ) { }
  12851. /**
  12852. * This method is intended for implementing the direct light term for
  12853. * rect area light nodes.
  12854. *
  12855. * @abstract
  12856. * @param {Object} input - The input data.
  12857. * @param {StackNode} stack - The current stack.
  12858. * @param {NodeBuilder} builder - The current node builder.
  12859. */
  12860. directRectArea( /*input, stack, builder*/ ) {}
  12861. /**
  12862. * This method is intended for implementing the indirect light term.
  12863. *
  12864. * @abstract
  12865. * @param {ContextNode} input - The current node context.
  12866. * @param {StackNode} stack - The current stack.
  12867. * @param {NodeBuilder} builder - The current node builder.
  12868. */
  12869. indirect( /*input, stack, builder*/ ) { }
  12870. /**
  12871. * This method is intended for implementing the ambient occlusion term.
  12872. * Unlike other methods, this method must be called manually by the lighting
  12873. * model in its indirect term.
  12874. *
  12875. * @abstract
  12876. * @param {ContextNode} input - The current node context.
  12877. * @param {StackNode} stack - The current stack.
  12878. * @param {NodeBuilder} builder - The current node builder.
  12879. */
  12880. ambientOcclusion( /*input, stack, builder*/ ) { }
  12881. }
  12882. /**
  12883. * Represents the lighting model for unlit materials. The only light contribution
  12884. * is baked indirect lighting modulated with ambient occlusion and the material's
  12885. * diffuse color. Environment mapping is supported. Used in {@link MeshBasicNodeMaterial}.
  12886. *
  12887. * @augments LightingModel
  12888. */
  12889. class BasicLightingModel extends LightingModel {
  12890. /**
  12891. * Constructs a new basic lighting model.
  12892. */
  12893. constructor() {
  12894. super();
  12895. }
  12896. /**
  12897. * Implements the baked indirect lighting with its modulation.
  12898. *
  12899. * @param {ContextNode} context - The current node context.
  12900. * @param {StackNode} stack - The current stack.
  12901. * @param {NodeBuilder} builder - The current node builder.
  12902. */
  12903. indirect( context, stack, builder ) {
  12904. const ambientOcclusion = context.ambientOcclusion;
  12905. const reflectedLight = context.reflectedLight;
  12906. const irradianceLightMap = builder.context.irradianceLightMap;
  12907. reflectedLight.indirectDiffuse.assign( vec4( 0.0 ) );
  12908. // accumulation (baked indirect lighting only)
  12909. if ( irradianceLightMap ) {
  12910. reflectedLight.indirectDiffuse.addAssign( irradianceLightMap );
  12911. } else {
  12912. reflectedLight.indirectDiffuse.addAssign( vec4( 1.0, 1.0, 1.0, 0.0 ) );
  12913. }
  12914. // modulation
  12915. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  12916. reflectedLight.indirectDiffuse.mulAssign( diffuseColor.rgb );
  12917. }
  12918. /**
  12919. * Implements the environment mapping.
  12920. *
  12921. * @param {ContextNode} context - The current node context.
  12922. * @param {StackNode} stack - The current stack.
  12923. * @param {NodeBuilder} builder - The current node builder.
  12924. */
  12925. finish( context, stack, builder ) {
  12926. const material = builder.material;
  12927. const outgoingLight = context.outgoingLight;
  12928. const envNode = builder.context.environment;
  12929. if ( envNode ) {
  12930. switch ( material.combine ) {
  12931. case MultiplyOperation:
  12932. outgoingLight.rgb.assign( mix( outgoingLight.rgb, outgoingLight.rgb.mul( envNode.rgb ), materialSpecularStrength.mul( materialReflectivity ) ) );
  12933. break;
  12934. case MixOperation:
  12935. outgoingLight.rgb.assign( mix( outgoingLight.rgb, envNode.rgb, materialSpecularStrength.mul( materialReflectivity ) ) );
  12936. break;
  12937. case AddOperation:
  12938. outgoingLight.rgb.addAssign( envNode.rgb.mul( materialSpecularStrength.mul( materialReflectivity ) ) );
  12939. break;
  12940. default:
  12941. console.warn( 'THREE.BasicLightingModel: Unsupported .combine value:', material.combine );
  12942. break;
  12943. }
  12944. }
  12945. }
  12946. }
  12947. const _defaultValues$9 = /*@__PURE__*/ new MeshBasicMaterial();
  12948. /**
  12949. * Node material version of `MeshBasicMaterial`.
  12950. *
  12951. * @augments NodeMaterial
  12952. */
  12953. class MeshBasicNodeMaterial extends NodeMaterial {
  12954. static get type() {
  12955. return 'MeshBasicNodeMaterial';
  12956. }
  12957. /**
  12958. * Constructs a new mesh basic node material.
  12959. *
  12960. * @param {Object?} parameters - The configuration parameter.
  12961. */
  12962. constructor( parameters ) {
  12963. super();
  12964. /**
  12965. * This flag can be used for type testing.
  12966. *
  12967. * @type {Boolean}
  12968. * @readonly
  12969. * @default true
  12970. */
  12971. this.isMeshBasicNodeMaterial = true;
  12972. /**
  12973. * Although the basic material is by definition unlit, we set
  12974. * this property to `true` since we use a lighting model to compute
  12975. * the outgoing light of the fragment shader.
  12976. *
  12977. * @type {Boolean}
  12978. * @default true
  12979. */
  12980. this.lights = true;
  12981. this.setDefaultValues( _defaultValues$9 );
  12982. this.setValues( parameters );
  12983. }
  12984. /**
  12985. * Basic materials are not affected by normal and bump maps so we
  12986. * return by default {@link module:Normal.normalView}.
  12987. *
  12988. * @return {Node<vec3>} The normal node.
  12989. */
  12990. setupNormal() {
  12991. return normalView; // see #28839
  12992. }
  12993. /**
  12994. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  12995. * to implement the default environment mapping.
  12996. *
  12997. * @param {NodeBuilder} builder - The current node builder.
  12998. * @return {BasicEnvironmentNode<vec3>?} The environment node.
  12999. */
  13000. setupEnvironment( builder ) {
  13001. const envNode = super.setupEnvironment( builder );
  13002. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  13003. }
  13004. /**
  13005. * This method must be overwritten since light maps are evaluated
  13006. * with a special scaling factor for basic materials.
  13007. *
  13008. * @param {NodeBuilder} builder - The current node builder.
  13009. * @return {BasicLightMapNode<vec3>?} The light map node.
  13010. */
  13011. setupLightMap( builder ) {
  13012. let node = null;
  13013. if ( builder.material.lightMap ) {
  13014. node = new BasicLightMapNode( materialLightMap );
  13015. }
  13016. return node;
  13017. }
  13018. /**
  13019. * The material overwrites this method because `lights` is set to `true` but
  13020. * we still want to return the diffuse color as the outgoing light.
  13021. *
  13022. * @return {Node<vec3>} The outgoing light node.
  13023. */
  13024. setupOutgoingLight() {
  13025. return diffuseColor.rgb;
  13026. }
  13027. /**
  13028. * Setups the lighting model.
  13029. *
  13030. * @return {BasicLightingModel} The lighting model.
  13031. */
  13032. setupLightingModel() {
  13033. return new BasicLightingModel();
  13034. }
  13035. }
  13036. const F_Schlick = /*@__PURE__*/ Fn( ( { f0, f90, dotVH } ) => {
  13037. // Original approximation by Christophe Schlick '94
  13038. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  13039. // Optimized variant (presented by Epic at SIGGRAPH '13)
  13040. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  13041. const fresnel = dotVH.mul( -5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  13042. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  13043. } ); // validated
  13044. const BRDF_Lambert = /*@__PURE__*/ Fn( ( inputs ) => {
  13045. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  13046. } ); // validated
  13047. const G_BlinnPhong_Implicit = () => float( 0.25 );
  13048. const D_BlinnPhong = /*@__PURE__*/ Fn( ( { dotNH } ) => {
  13049. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  13050. } );
  13051. const BRDF_BlinnPhong = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  13052. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  13053. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  13054. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  13055. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  13056. const G = G_BlinnPhong_Implicit();
  13057. const D = D_BlinnPhong( { dotNH } );
  13058. return F.mul( G ).mul( D );
  13059. } );
  13060. /**
  13061. * Represents the lighting model for a phong material. Used in {@link MeshPhongNodeMaterial}.
  13062. *
  13063. * @augments BasicLightingModel
  13064. */
  13065. class PhongLightingModel extends BasicLightingModel {
  13066. /**
  13067. * Constructs a new phong lighting model.
  13068. *
  13069. * @param {Boolean} [specular=true] - Whether specular is supported or not.
  13070. */
  13071. constructor( specular = true ) {
  13072. super();
  13073. /**
  13074. * Whether specular is supported or not. Set this to `false` if you are
  13075. * looking for a Lambert-like material meaning a material for non-shiny
  13076. * surfaces, without specular highlights.
  13077. *
  13078. * @type {Boolean}
  13079. * @default true
  13080. */
  13081. this.specular = specular;
  13082. }
  13083. /**
  13084. * Implements the direct lighting. The specular portion is optional an can be controlled
  13085. * with the {@link PhongLightingModel#specular} flag.
  13086. *
  13087. * @param {Object} input - The input data.
  13088. * @param {StackNode} stack - The current stack.
  13089. * @param {NodeBuilder} builder - The current node builder.
  13090. */
  13091. direct( { lightDirection, lightColor, reflectedLight } ) {
  13092. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  13093. const irradiance = dotNL.mul( lightColor );
  13094. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  13095. if ( this.specular === true ) {
  13096. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  13097. }
  13098. }
  13099. /**
  13100. * Implements the indirect lighting.
  13101. *
  13102. * @param {ContextNode} input - The current node context.
  13103. * @param {StackNode} stack - The current stack.
  13104. * @param {NodeBuilder} builder - The current node builder.
  13105. */
  13106. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  13107. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  13108. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  13109. }
  13110. }
  13111. const _defaultValues$8 = /*@__PURE__*/ new MeshLambertMaterial();
  13112. /**
  13113. * Node material version of `MeshLambertMaterial`.
  13114. *
  13115. * @augments NodeMaterial
  13116. */
  13117. class MeshLambertNodeMaterial extends NodeMaterial {
  13118. static get type() {
  13119. return 'MeshLambertNodeMaterial';
  13120. }
  13121. /**
  13122. * Constructs a new mesh lambert node material.
  13123. *
  13124. * @param {Object?} parameters - The configuration parameter.
  13125. */
  13126. constructor( parameters ) {
  13127. super();
  13128. /**
  13129. * This flag can be used for type testing.
  13130. *
  13131. * @type {Boolean}
  13132. * @readonly
  13133. * @default true
  13134. */
  13135. this.isMeshLambertNodeMaterial = true;
  13136. /**
  13137. * Set to `true` because lambert materials react on lights.
  13138. *
  13139. * @type {Boolean}
  13140. * @default true
  13141. */
  13142. this.lights = true;
  13143. this.setDefaultValues( _defaultValues$8 );
  13144. this.setValues( parameters );
  13145. }
  13146. /**
  13147. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  13148. * to implement the default environment mapping.
  13149. *
  13150. * @param {NodeBuilder} builder - The current node builder.
  13151. * @return {BasicEnvironmentNode<vec3>?} The environment node.
  13152. */
  13153. setupEnvironment( builder ) {
  13154. const envNode = super.setupEnvironment( builder );
  13155. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  13156. }
  13157. /**
  13158. * Setups the lighting model.
  13159. *
  13160. * @return {PhongLightingModel} The lighting model.
  13161. */
  13162. setupLightingModel( /*builder*/ ) {
  13163. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  13164. }
  13165. }
  13166. const _defaultValues$7 = /*@__PURE__*/ new MeshPhongMaterial();
  13167. /**
  13168. * Node material version of `MeshPhongMaterial`.
  13169. *
  13170. * @augments NodeMaterial
  13171. */
  13172. class MeshPhongNodeMaterial extends NodeMaterial {
  13173. static get type() {
  13174. return 'MeshPhongNodeMaterial';
  13175. }
  13176. /**
  13177. * Constructs a new mesh lambert node material.
  13178. *
  13179. * @param {Object?} parameters - The configuration parameter.
  13180. */
  13181. constructor( parameters ) {
  13182. super();
  13183. /**
  13184. * This flag can be used for type testing.
  13185. *
  13186. * @type {Boolean}
  13187. * @readonly
  13188. * @default true
  13189. */
  13190. this.isMeshPhongNodeMaterial = true;
  13191. /**
  13192. * Set to `true` because phong materials react on lights.
  13193. *
  13194. * @type {Boolean}
  13195. * @default true
  13196. */
  13197. this.lights = true;
  13198. /**
  13199. * The shininess of phong materials is by default inferred from the `shininess`
  13200. * property. This node property allows to overwrite the default
  13201. * and define the shininess with a node instead.
  13202. *
  13203. * If you don't want to overwrite the shininess but modify the existing
  13204. * value instead, use {@link module:MaterialNode.materialShininess}.
  13205. *
  13206. * @type {Node<float>?}
  13207. * @default null
  13208. */
  13209. this.shininessNode = null;
  13210. /**
  13211. * The specular color of phong materials is by default inferred from the
  13212. * `specular` property. This node property allows to overwrite the default
  13213. * and define the specular color with a node instead.
  13214. *
  13215. * If you don't want to overwrite the specular color but modify the existing
  13216. * value instead, use {@link module:MaterialNode.materialSpecular}.
  13217. *
  13218. * @type {Node<vec3>?}
  13219. * @default null
  13220. */
  13221. this.specularNode = null;
  13222. this.setDefaultValues( _defaultValues$7 );
  13223. this.setValues( parameters );
  13224. }
  13225. /**
  13226. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  13227. * to implement the default environment mapping.
  13228. *
  13229. * @param {NodeBuilder} builder - The current node builder.
  13230. * @return {BasicEnvironmentNode<vec3>?} The environment node.
  13231. */
  13232. setupEnvironment( builder ) {
  13233. const envNode = super.setupEnvironment( builder );
  13234. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  13235. }
  13236. /**
  13237. * Setups the lighting model.
  13238. *
  13239. * @return {PhongLightingModel} The lighting model.
  13240. */
  13241. setupLightingModel( /*builder*/ ) {
  13242. return new PhongLightingModel();
  13243. }
  13244. /**
  13245. * Setups the phong specific node variables.
  13246. *
  13247. * @param {NodeBuilder} builder - The current node builder.
  13248. */
  13249. setupVariants( /*builder*/ ) {
  13250. // SHININESS
  13251. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  13252. shininess.assign( shininessNode );
  13253. // SPECULAR COLOR
  13254. const specularNode = this.specularNode || materialSpecular;
  13255. specularColor.assign( specularNode );
  13256. }
  13257. copy( source ) {
  13258. this.shininessNode = source.shininessNode;
  13259. this.specularNode = source.specularNode;
  13260. return super.copy( source );
  13261. }
  13262. }
  13263. const getGeometryRoughness = /*@__PURE__*/ Fn( ( builder ) => {
  13264. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  13265. return float( 0 );
  13266. }
  13267. const dxy = normalView.dFdx().abs().max( normalView.dFdy().abs() );
  13268. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  13269. return geometryRoughness;
  13270. } );
  13271. const getRoughness = /*@__PURE__*/ Fn( ( inputs ) => {
  13272. const { roughness } = inputs;
  13273. const geometryRoughness = getGeometryRoughness();
  13274. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  13275. roughnessFactor = roughnessFactor.add( geometryRoughness );
  13276. roughnessFactor = roughnessFactor.min( 1.0 );
  13277. return roughnessFactor;
  13278. } );
  13279. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  13280. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  13281. const V_GGX_SmithCorrelated = /*@__PURE__*/ Fn( ( { alpha, dotNL, dotNV } ) => {
  13282. const a2 = alpha.pow2();
  13283. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  13284. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  13285. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  13286. } ).setLayout( {
  13287. name: 'V_GGX_SmithCorrelated',
  13288. type: 'float',
  13289. inputs: [
  13290. { name: 'alpha', type: 'float' },
  13291. { name: 'dotNL', type: 'float' },
  13292. { name: 'dotNV', type: 'float' }
  13293. ]
  13294. } ); // validated
  13295. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  13296. const V_GGX_SmithCorrelated_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  13297. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  13298. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  13299. const v = div( 0.5, gv.add( gl ) );
  13300. return v.saturate();
  13301. } ).setLayout( {
  13302. name: 'V_GGX_SmithCorrelated_Anisotropic',
  13303. type: 'float',
  13304. inputs: [
  13305. { name: 'alphaT', type: 'float', qualifier: 'in' },
  13306. { name: 'alphaB', type: 'float', qualifier: 'in' },
  13307. { name: 'dotTV', type: 'float', qualifier: 'in' },
  13308. { name: 'dotBV', type: 'float', qualifier: 'in' },
  13309. { name: 'dotTL', type: 'float', qualifier: 'in' },
  13310. { name: 'dotBL', type: 'float', qualifier: 'in' },
  13311. { name: 'dotNV', type: 'float', qualifier: 'in' },
  13312. { name: 'dotNL', type: 'float', qualifier: 'in' }
  13313. ]
  13314. } );
  13315. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  13316. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  13317. // alpha is "roughness squared" in Disney’s reparameterization
  13318. const D_GGX = /*@__PURE__*/ Fn( ( { alpha, dotNH } ) => {
  13319. const a2 = alpha.pow2();
  13320. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  13321. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  13322. } ).setLayout( {
  13323. name: 'D_GGX',
  13324. type: 'float',
  13325. inputs: [
  13326. { name: 'alpha', type: 'float' },
  13327. { name: 'dotNH', type: 'float' }
  13328. ]
  13329. } ); // validated
  13330. const RECIPROCAL_PI = /*@__PURE__*/ float( 1 / Math.PI );
  13331. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  13332. const D_GGX_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  13333. const a2 = alphaT.mul( alphaB );
  13334. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  13335. const v2 = v.dot( v );
  13336. const w2 = a2.div( v2 );
  13337. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  13338. } ).setLayout( {
  13339. name: 'D_GGX_Anisotropic',
  13340. type: 'float',
  13341. inputs: [
  13342. { name: 'alphaT', type: 'float', qualifier: 'in' },
  13343. { name: 'alphaB', type: 'float', qualifier: 'in' },
  13344. { name: 'dotNH', type: 'float', qualifier: 'in' },
  13345. { name: 'dotTH', type: 'float', qualifier: 'in' },
  13346. { name: 'dotBH', type: 'float', qualifier: 'in' }
  13347. ]
  13348. } );
  13349. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  13350. const BRDF_GGX = /*@__PURE__*/ Fn( ( inputs ) => {
  13351. const { lightDirection, f0, f90, roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } = inputs;
  13352. const normalView = inputs.normalView || transformedNormalView;
  13353. const alpha = roughness.pow2(); // UE4's roughness
  13354. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  13355. const dotNL = normalView.dot( lightDirection ).clamp();
  13356. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  13357. const dotNH = normalView.dot( halfDir ).clamp();
  13358. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  13359. let F = F_Schlick( { f0, f90, dotVH } );
  13360. let V, D;
  13361. if ( defined( USE_IRIDESCENCE ) ) {
  13362. F = iridescence.mix( F, f );
  13363. }
  13364. if ( defined( USE_ANISOTROPY ) ) {
  13365. const dotTL = anisotropyT.dot( lightDirection );
  13366. const dotTV = anisotropyT.dot( positionViewDirection );
  13367. const dotTH = anisotropyT.dot( halfDir );
  13368. const dotBL = anisotropyB.dot( lightDirection );
  13369. const dotBV = anisotropyB.dot( positionViewDirection );
  13370. const dotBH = anisotropyB.dot( halfDir );
  13371. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  13372. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  13373. } else {
  13374. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  13375. D = D_GGX( { alpha, dotNH } );
  13376. }
  13377. return F.mul( V ).mul( D );
  13378. } ); // validated
  13379. // Analytical approximation of the DFG LUT, one half of the
  13380. // split-sum approximation used in indirect specular lighting.
  13381. // via 'environmentBRDF' from "Physically Based Shading on Mobile"
  13382. // https://www.unrealengine.com/blog/physically-based-shading-on-mobile
  13383. const DFGApprox = /*@__PURE__*/ Fn( ( { roughness, dotNV } ) => {
  13384. const c0 = vec4( -1, -0.0275, -0.572, 0.022 );
  13385. const c1 = vec4( 1, 0.0425, 1.04, -0.04 );
  13386. const r = roughness.mul( c0 ).add( c1 );
  13387. const a004 = r.x.mul( r.x ).min( dotNV.mul( -9.28 ).exp2() ).mul( r.x ).add( r.y );
  13388. const fab = vec2( -1.04, 1.04 ).mul( a004 ).add( r.zw );
  13389. return fab;
  13390. } ).setLayout( {
  13391. name: 'DFGApprox',
  13392. type: 'vec2',
  13393. inputs: [
  13394. { name: 'roughness', type: 'float' },
  13395. { name: 'dotNV', type: 'vec3' }
  13396. ]
  13397. } );
  13398. const EnvironmentBRDF = /*@__PURE__*/ Fn( ( inputs ) => {
  13399. const { dotNV, specularColor, specularF90, roughness } = inputs;
  13400. const fab = DFGApprox( { dotNV, roughness } );
  13401. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  13402. } );
  13403. const Schlick_to_F0 = /*@__PURE__*/ Fn( ( { f, f90, dotVH } ) => {
  13404. const x = dotVH.oneMinus().saturate();
  13405. const x2 = x.mul( x );
  13406. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  13407. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  13408. } ).setLayout( {
  13409. name: 'Schlick_to_F0',
  13410. type: 'vec3',
  13411. inputs: [
  13412. { name: 'f', type: 'vec3' },
  13413. { name: 'f90', type: 'float' },
  13414. { name: 'dotVH', type: 'float' }
  13415. ]
  13416. } );
  13417. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  13418. const D_Charlie = /*@__PURE__*/ Fn( ( { roughness, dotNH } ) => {
  13419. const alpha = roughness.pow2();
  13420. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  13421. const invAlpha = float( 1.0 ).div( alpha );
  13422. const cos2h = dotNH.pow2();
  13423. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  13424. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  13425. } ).setLayout( {
  13426. name: 'D_Charlie',
  13427. type: 'float',
  13428. inputs: [
  13429. { name: 'roughness', type: 'float' },
  13430. { name: 'dotNH', type: 'float' }
  13431. ]
  13432. } );
  13433. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  13434. const V_Neubelt = /*@__PURE__*/ Fn( ( { dotNV, dotNL } ) => {
  13435. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  13436. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  13437. } ).setLayout( {
  13438. name: 'V_Neubelt',
  13439. type: 'float',
  13440. inputs: [
  13441. { name: 'dotNV', type: 'float' },
  13442. { name: 'dotNL', type: 'float' }
  13443. ]
  13444. } );
  13445. const BRDF_Sheen = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  13446. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  13447. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  13448. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp();
  13449. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  13450. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  13451. const V = V_Neubelt( { dotNV, dotNL } );
  13452. return sheen.mul( D ).mul( V );
  13453. } );
  13454. // Rect Area Light
  13455. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  13456. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  13457. // code: https://github.com/selfshadow/ltc_code/
  13458. const LTC_Uv = /*@__PURE__*/ Fn( ( { N, V, roughness } ) => {
  13459. const LUT_SIZE = 64.0;
  13460. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  13461. const LUT_BIAS = 0.5 / LUT_SIZE;
  13462. const dotNV = N.dot( V ).saturate();
  13463. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  13464. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  13465. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  13466. return uv;
  13467. } ).setLayout( {
  13468. name: 'LTC_Uv',
  13469. type: 'vec2',
  13470. inputs: [
  13471. { name: 'N', type: 'vec3' },
  13472. { name: 'V', type: 'vec3' },
  13473. { name: 'roughness', type: 'float' }
  13474. ]
  13475. } );
  13476. const LTC_ClippedSphereFormFactor = /*@__PURE__*/ Fn( ( { f } ) => {
  13477. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  13478. // An approximation of the form factor of a horizon-clipped rectangle.
  13479. const l = f.length();
  13480. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  13481. } ).setLayout( {
  13482. name: 'LTC_ClippedSphereFormFactor',
  13483. type: 'float',
  13484. inputs: [
  13485. { name: 'f', type: 'vec3' }
  13486. ]
  13487. } );
  13488. const LTC_EdgeVectorFormFactor = /*@__PURE__*/ Fn( ( { v1, v2 } ) => {
  13489. const x = v1.dot( v2 );
  13490. const y = x.abs().toVar();
  13491. // rational polynomial approximation to theta / sin( theta ) / 2PI
  13492. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  13493. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  13494. const v = a.div( b );
  13495. const theta_sintheta = x.greaterThan( 0.0 ).select( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  13496. return v1.cross( v2 ).mul( theta_sintheta );
  13497. } ).setLayout( {
  13498. name: 'LTC_EdgeVectorFormFactor',
  13499. type: 'vec3',
  13500. inputs: [
  13501. { name: 'v1', type: 'vec3' },
  13502. { name: 'v2', type: 'vec3' }
  13503. ]
  13504. } );
  13505. const LTC_Evaluate = /*@__PURE__*/ Fn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  13506. // bail if point is on back side of plane of light
  13507. // assumes ccw winding order of light vertices
  13508. const v1 = p1.sub( p0 ).toVar();
  13509. const v2 = p3.sub( p0 ).toVar();
  13510. const lightNormal = v1.cross( v2 );
  13511. const result = vec3().toVar();
  13512. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  13513. // construct orthonormal basis around N
  13514. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  13515. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  13516. // compute transform
  13517. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  13518. // transform rect
  13519. // & project rect onto sphere
  13520. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  13521. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  13522. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  13523. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  13524. // calculate vector form factor
  13525. const vectorFormFactor = vec3( 0 ).toVar();
  13526. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  13527. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  13528. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  13529. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  13530. // adjust for horizon clipping
  13531. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  13532. } );
  13533. return result;
  13534. } ).setLayout( {
  13535. name: 'LTC_Evaluate',
  13536. type: 'vec3',
  13537. inputs: [
  13538. { name: 'N', type: 'vec3' },
  13539. { name: 'V', type: 'vec3' },
  13540. { name: 'P', type: 'vec3' },
  13541. { name: 'mInv', type: 'mat3' },
  13542. { name: 'p0', type: 'vec3' },
  13543. { name: 'p1', type: 'vec3' },
  13544. { name: 'p2', type: 'vec3' },
  13545. { name: 'p3', type: 'vec3' }
  13546. ]
  13547. } );
  13548. /** @module TextureBicubic **/
  13549. // Mipped Bicubic Texture Filtering by N8
  13550. // https://www.shadertoy.com/view/Dl2SDW
  13551. const bC = 1.0 / 6.0;
  13552. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  13553. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  13554. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( -3, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  13555. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  13556. const g0 = ( a ) => w0( a ).add( w1( a ) );
  13557. const g1 = ( a ) => w2( a ).add( w3( a ) );
  13558. // h0 and h1 are the two offset functions
  13559. const h0 = ( a ) => add( -1, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  13560. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  13561. const bicubic = ( textureNode, texelSize, lod ) => {
  13562. const uv = textureNode.uvNode;
  13563. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  13564. const iuv = floor( uvScaled );
  13565. const fuv = fract( uvScaled );
  13566. const g0x = g0( fuv.x );
  13567. const g1x = g1( fuv.x );
  13568. const h0x = h0( fuv.x );
  13569. const h1x = h1( fuv.x );
  13570. const h0y = h0( fuv.y );
  13571. const h1y = h1( fuv.y );
  13572. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  13573. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  13574. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  13575. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  13576. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.sample( p0 ).level( lod ) ), g1x.mul( textureNode.sample( p1 ).level( lod ) ) ) );
  13577. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.sample( p2 ).level( lod ) ), g1x.mul( textureNode.sample( p3 ).level( lod ) ) ) );
  13578. return a.add( b );
  13579. };
  13580. /**
  13581. * Applies mipped bicubic texture filtering to the given texture node.
  13582. *
  13583. * @method
  13584. * @param {TextureNode} textureNode - The texture node that should be filtered.
  13585. * @param {Node<float>} [lodNode=float(3)] - Defines the LOD to sample from.
  13586. * @return {Node} The filtered texture sample.
  13587. */
  13588. const textureBicubic = /*@__PURE__*/ Fn( ( [ textureNode, lodNode = float( 3 ) ] ) => {
  13589. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  13590. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  13591. const fLodSizeInv = div( 1.0, fLodSize );
  13592. const cLodSizeInv = div( 1.0, cLodSize );
  13593. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  13594. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  13595. return fract( lodNode ).mix( fSample, cSample );
  13596. } );
  13597. //
  13598. // Transmission
  13599. //
  13600. const getVolumeTransmissionRay = /*@__PURE__*/ Fn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  13601. // Direction of refracted light.
  13602. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  13603. // Compute rotation-independent scaling of the model matrix.
  13604. const modelScale = vec3(
  13605. length( modelMatrix[ 0 ].xyz ),
  13606. length( modelMatrix[ 1 ].xyz ),
  13607. length( modelMatrix[ 2 ].xyz )
  13608. );
  13609. // The thickness is specified in local space.
  13610. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  13611. } ).setLayout( {
  13612. name: 'getVolumeTransmissionRay',
  13613. type: 'vec3',
  13614. inputs: [
  13615. { name: 'n', type: 'vec3' },
  13616. { name: 'v', type: 'vec3' },
  13617. { name: 'thickness', type: 'float' },
  13618. { name: 'ior', type: 'float' },
  13619. { name: 'modelMatrix', type: 'mat4' }
  13620. ]
  13621. } );
  13622. const applyIorToRoughness = /*@__PURE__*/ Fn( ( [ roughness, ior ] ) => {
  13623. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  13624. // an IOR of 1.5 results in the default amount of microfacet refraction.
  13625. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  13626. } ).setLayout( {
  13627. name: 'applyIorToRoughness',
  13628. type: 'float',
  13629. inputs: [
  13630. { name: 'roughness', type: 'float' },
  13631. { name: 'ior', type: 'float' }
  13632. ]
  13633. } );
  13634. const viewportBackSideTexture = /*@__PURE__*/ viewportMipTexture();
  13635. const viewportFrontSideTexture = /*@__PURE__*/ viewportMipTexture();
  13636. const getTransmissionSample = /*@__PURE__*/ Fn( ( [ fragCoord, roughness, ior ], { material } ) => {
  13637. const vTexture = material.side === BackSide ? viewportBackSideTexture : viewportFrontSideTexture;
  13638. const transmissionSample = vTexture.sample( fragCoord );
  13639. //const transmissionSample = viewportMipTexture( fragCoord );
  13640. const lod = log2( screenSize.x ).mul( applyIorToRoughness( roughness, ior ) );
  13641. return textureBicubic( transmissionSample, lod );
  13642. } );
  13643. const volumeAttenuation = /*@__PURE__*/ Fn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  13644. If( attenuationDistance.notEqual( 0 ), () => {
  13645. // Compute light attenuation using Beer's law.
  13646. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  13647. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  13648. return transmittance;
  13649. } );
  13650. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  13651. return vec3( 1.0 );
  13652. } ).setLayout( {
  13653. name: 'volumeAttenuation',
  13654. type: 'vec3',
  13655. inputs: [
  13656. { name: 'transmissionDistance', type: 'float' },
  13657. { name: 'attenuationColor', type: 'vec3' },
  13658. { name: 'attenuationDistance', type: 'float' }
  13659. ]
  13660. } );
  13661. const getIBLVolumeRefraction = /*@__PURE__*/ Fn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  13662. let transmittedLight, transmittance;
  13663. if ( dispersion ) {
  13664. transmittedLight = vec4().toVar();
  13665. transmittance = vec3().toVar();
  13666. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  13667. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  13668. Loop( { start: 0, end: 3 }, ( { i } ) => {
  13669. const ior = iors.element( i );
  13670. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  13671. const refractedRayExit = position.add( transmissionRay );
  13672. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  13673. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  13674. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  13675. refractionCoords.addAssign( 1.0 );
  13676. refractionCoords.divAssign( 2.0 );
  13677. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  13678. // Sample framebuffer to get pixel the refracted ray hits.
  13679. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  13680. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  13681. transmittedLight.a.addAssign( transmissionSample.a );
  13682. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  13683. } );
  13684. transmittedLight.a.divAssign( 3.0 );
  13685. } else {
  13686. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  13687. const refractedRayExit = position.add( transmissionRay );
  13688. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  13689. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  13690. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  13691. refractionCoords.addAssign( 1.0 );
  13692. refractionCoords.divAssign( 2.0 );
  13693. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  13694. // Sample framebuffer to get pixel the refracted ray hits.
  13695. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  13696. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  13697. }
  13698. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  13699. const dotNV = n.dot( v ).clamp();
  13700. // Get the specular component.
  13701. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  13702. dotNV,
  13703. specularColor,
  13704. specularF90,
  13705. roughness
  13706. } ) );
  13707. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  13708. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  13709. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  13710. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  13711. } );
  13712. //
  13713. // Iridescence
  13714. //
  13715. // XYZ to linear-sRGB color space
  13716. const XYZ_TO_REC709 = /*@__PURE__*/ mat3(
  13717. 3.2404542, -0.969266, 0.0556434,
  13718. -1.5371385, 1.8760108, -0.2040259,
  13719. -0.4985314, 0.0415560, 1.0572252
  13720. );
  13721. // Assume air interface for top
  13722. // Note: We don't handle the case fresnel0 == 1
  13723. const Fresnel0ToIor = ( fresnel0 ) => {
  13724. const sqrtF0 = fresnel0.sqrt();
  13725. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  13726. };
  13727. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  13728. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  13729. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  13730. };
  13731. // Fresnel equations for dielectric/dielectric interfaces.
  13732. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  13733. // Evaluation XYZ sensitivity curves in Fourier space
  13734. const evalSensitivity = ( OPD, shift ) => {
  13735. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  13736. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  13737. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  13738. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  13739. 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() );
  13740. 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() );
  13741. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  13742. const rgb = XYZ_TO_REC709.mul( xyz );
  13743. return rgb;
  13744. };
  13745. const evalIridescence = /*@__PURE__*/ Fn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  13746. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  13747. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  13748. // Evaluate the cosTheta on the base layer (Snell law)
  13749. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( cosTheta1.pow2().oneMinus() );
  13750. // Handle TIR:
  13751. const cosTheta2Sq = sinTheta2Sq.oneMinus();
  13752. If( cosTheta2Sq.lessThan( 0 ), () => {
  13753. return vec3( 1.0 );
  13754. } );
  13755. const cosTheta2 = cosTheta2Sq.sqrt();
  13756. // First interface
  13757. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  13758. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  13759. //const R21 = R12;
  13760. const T121 = R12.oneMinus();
  13761. const phi12 = iridescenceIOR.lessThan( outsideIOR ).select( Math.PI, 0.0 );
  13762. const phi21 = float( Math.PI ).sub( phi12 );
  13763. // Second interface
  13764. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  13765. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  13766. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  13767. const phi23 = vec3(
  13768. baseIOR.x.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  13769. baseIOR.y.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  13770. baseIOR.z.lessThan( iridescenceIOR ).select( Math.PI, 0.0 )
  13771. );
  13772. // Phase shift
  13773. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  13774. const phi = vec3( phi21 ).add( phi23 );
  13775. // Compound terms
  13776. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  13777. const r123 = R123.sqrt();
  13778. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  13779. // Reflectance term for m = 0 (DC term amplitude)
  13780. const C0 = R12.add( Rs );
  13781. const I = C0.toVar();
  13782. // Reflectance term for m > 0 (pairs of diracs)
  13783. const Cm = Rs.sub( T121 ).toVar();
  13784. Loop( { start: 1, end: 2, condition: '<=', name: 'm' }, ( { m } ) => {
  13785. Cm.mulAssign( r123 );
  13786. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  13787. I.addAssign( Cm.mul( Sm ) );
  13788. } );
  13789. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  13790. return I.max( vec3( 0.0 ) );
  13791. } ).setLayout( {
  13792. name: 'evalIridescence',
  13793. type: 'vec3',
  13794. inputs: [
  13795. { name: 'outsideIOR', type: 'float' },
  13796. { name: 'eta2', type: 'float' },
  13797. { name: 'cosTheta1', type: 'float' },
  13798. { name: 'thinFilmThickness', type: 'float' },
  13799. { name: 'baseF0', type: 'vec3' }
  13800. ]
  13801. } );
  13802. //
  13803. // Sheen
  13804. //
  13805. // This is a curve-fit approximation to the "Charlie sheen" BRDF integrated over the hemisphere from
  13806. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF". The analysis can be found
  13807. // in the Sheen section of https://drive.google.com/file/d/1T0D1VSyR4AllqIJTQAraEIzjlb5h4FKH/view?usp=sharing
  13808. const IBLSheenBRDF = /*@__PURE__*/ Fn( ( { normal, viewDir, roughness } ) => {
  13809. const dotNV = normal.dot( viewDir ).saturate();
  13810. const r2 = roughness.pow2();
  13811. const a = select(
  13812. roughness.lessThan( 0.25 ),
  13813. float( -339.2 ).mul( r2 ).add( float( 161.4 ).mul( roughness ) ).sub( 25.9 ),
  13814. float( -8.48 ).mul( r2 ).add( float( 14.3 ).mul( roughness ) ).sub( 9.95 )
  13815. );
  13816. const b = select(
  13817. roughness.lessThan( 0.25 ),
  13818. float( 44.0 ).mul( r2 ).sub( float( 23.7 ).mul( roughness ) ).add( 3.26 ),
  13819. float( 1.97 ).mul( r2 ).sub( float( 3.27 ).mul( roughness ) ).add( 0.72 )
  13820. );
  13821. const DG = select( roughness.lessThan( 0.25 ), 0.0, float( 0.1 ).mul( roughness ).sub( 0.025 ) ).add( a.mul( dotNV ).add( b ).exp() );
  13822. return DG.mul( 1.0 / Math.PI ).saturate();
  13823. } );
  13824. const clearcoatF0 = vec3( 0.04 );
  13825. const clearcoatF90 = float( 1 );
  13826. /**
  13827. * Represents the lighting model for a PBR material.
  13828. *
  13829. * @augments LightingModel
  13830. */
  13831. class PhysicalLightingModel extends LightingModel {
  13832. /**
  13833. * Constructs a new physical lighting model.
  13834. *
  13835. * @param {Boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  13836. * @param {Boolean} [sheen=false] - Whether sheen is supported or not.
  13837. * @param {Boolean} [iridescence=false] - Whether iridescence is supported or not.
  13838. * @param {Boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  13839. * @param {Boolean} [transmission=false] - Whether transmission is supported or not.
  13840. * @param {Boolean} [dispersion=false] - Whether dispersion is supported or not.
  13841. */
  13842. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  13843. super();
  13844. /**
  13845. * Whether clearcoat is supported or not.
  13846. *
  13847. * @type {Boolean}
  13848. * @default false
  13849. */
  13850. this.clearcoat = clearcoat;
  13851. /**
  13852. * Whether sheen is supported or not.
  13853. *
  13854. * @type {Boolean}
  13855. * @default false
  13856. */
  13857. this.sheen = sheen;
  13858. /**
  13859. * Whether iridescence is supported or not.
  13860. *
  13861. * @type {Boolean}
  13862. * @default false
  13863. */
  13864. this.iridescence = iridescence;
  13865. /**
  13866. * Whether anisotropy is supported or not.
  13867. *
  13868. * @type {Boolean}
  13869. * @default false
  13870. */
  13871. this.anisotropy = anisotropy;
  13872. /**
  13873. * Whether transmission is supported or not.
  13874. *
  13875. * @type {Boolean}
  13876. * @default false
  13877. */
  13878. this.transmission = transmission;
  13879. /**
  13880. * Whether dispersion is supported or not.
  13881. *
  13882. * @type {Boolean}
  13883. * @default false
  13884. */
  13885. this.dispersion = dispersion;
  13886. /**
  13887. * The clear coat radiance.
  13888. *
  13889. * @type {Node?}
  13890. * @default null
  13891. */
  13892. this.clearcoatRadiance = null;
  13893. /**
  13894. * The clear coat specular direct.
  13895. *
  13896. * @type {Node?}
  13897. * @default null
  13898. */
  13899. this.clearcoatSpecularDirect = null;
  13900. /**
  13901. * The clear coat specular indirect.
  13902. *
  13903. * @type {Node?}
  13904. * @default null
  13905. */
  13906. this.clearcoatSpecularIndirect = null;
  13907. /**
  13908. * The sheen specular direct.
  13909. *
  13910. * @type {Node?}
  13911. * @default null
  13912. */
  13913. this.sheenSpecularDirect = null;
  13914. /**
  13915. * The sheen specular indirect.
  13916. *
  13917. * @type {Node?}
  13918. * @default null
  13919. */
  13920. this.sheenSpecularIndirect = null;
  13921. /**
  13922. * The iridescence Fresnel.
  13923. *
  13924. * @type {Node?}
  13925. * @default null
  13926. */
  13927. this.iridescenceFresnel = null;
  13928. /**
  13929. * The iridescence F0.
  13930. *
  13931. * @type {Node?}
  13932. * @default null
  13933. */
  13934. this.iridescenceF0 = null;
  13935. }
  13936. /**
  13937. * Depending on what features are requested, the method prepares certain node variables
  13938. * which are later used for lighting computations.
  13939. *
  13940. * @param {ContextNode} context - The current node context.
  13941. */
  13942. start( context ) {
  13943. if ( this.clearcoat === true ) {
  13944. this.clearcoatRadiance = vec3().toVar( 'clearcoatRadiance' );
  13945. this.clearcoatSpecularDirect = vec3().toVar( 'clearcoatSpecularDirect' );
  13946. this.clearcoatSpecularIndirect = vec3().toVar( 'clearcoatSpecularIndirect' );
  13947. }
  13948. if ( this.sheen === true ) {
  13949. this.sheenSpecularDirect = vec3().toVar( 'sheenSpecularDirect' );
  13950. this.sheenSpecularIndirect = vec3().toVar( 'sheenSpecularIndirect' );
  13951. }
  13952. if ( this.iridescence === true ) {
  13953. const dotNVi = transformedNormalView.dot( positionViewDirection ).clamp();
  13954. this.iridescenceFresnel = evalIridescence( {
  13955. outsideIOR: float( 1.0 ),
  13956. eta2: iridescenceIOR,
  13957. cosTheta1: dotNVi,
  13958. thinFilmThickness: iridescenceThickness,
  13959. baseF0: specularColor
  13960. } );
  13961. this.iridescenceF0 = Schlick_to_F0( { f: this.iridescenceFresnel, f90: 1.0, dotVH: dotNVi } );
  13962. }
  13963. if ( this.transmission === true ) {
  13964. const position = positionWorld;
  13965. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  13966. const n = transformedNormalWorld;
  13967. context.backdrop = getIBLVolumeRefraction(
  13968. n,
  13969. v,
  13970. roughness,
  13971. diffuseColor,
  13972. specularColor,
  13973. specularF90, // specularF90
  13974. position, // positionWorld
  13975. modelWorldMatrix, // modelMatrix
  13976. cameraViewMatrix, // viewMatrix
  13977. cameraProjectionMatrix, // projMatrix
  13978. ior,
  13979. thickness,
  13980. attenuationColor,
  13981. attenuationDistance,
  13982. this.dispersion ? dispersion : null
  13983. );
  13984. context.backdropAlpha = transmission;
  13985. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  13986. }
  13987. }
  13988. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  13989. // Approximates multi-scattering in order to preserve energy.
  13990. // http://www.jcgt.org/published/0008/01/03/
  13991. computeMultiscattering( singleScatter, multiScatter, specularF90 ) {
  13992. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  13993. const fab = DFGApprox( { roughness, dotNV } );
  13994. const Fr = this.iridescenceF0 ? iridescence.mix( specularColor, this.iridescenceF0 ) : specularColor;
  13995. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  13996. const Ess = fab.x.add( fab.y );
  13997. const Ems = Ess.oneMinus();
  13998. const Favg = specularColor.add( specularColor.oneMinus().mul( 0.047619 ) ); // 1/21
  13999. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  14000. singleScatter.addAssign( FssEss );
  14001. multiScatter.addAssign( Fms.mul( Ems ) );
  14002. }
  14003. /**
  14004. * Implements the direct light.
  14005. *
  14006. * @param {Object} input - The input data.
  14007. * @param {StackNode} stack - The current stack.
  14008. * @param {NodeBuilder} builder - The current node builder.
  14009. */
  14010. direct( { lightDirection, lightColor, reflectedLight } ) {
  14011. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  14012. const irradiance = dotNL.mul( lightColor );
  14013. if ( this.sheen === true ) {
  14014. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  14015. }
  14016. if ( this.clearcoat === true ) {
  14017. const dotNLcc = transformedClearcoatNormalView.dot( lightDirection ).clamp();
  14018. const ccIrradiance = dotNLcc.mul( lightColor );
  14019. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: transformedClearcoatNormalView } ) ) );
  14020. }
  14021. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  14022. 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 } ) ) );
  14023. }
  14024. /**
  14025. * This method is intended for implementing the direct light term for
  14026. * rect area light nodes.
  14027. *
  14028. * @param {Object} input - The input data.
  14029. * @param {StackNode} stack - The current stack.
  14030. * @param {NodeBuilder} builder - The current node builder.
  14031. */
  14032. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 } ) {
  14033. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  14034. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  14035. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  14036. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  14037. const N = transformedNormalView;
  14038. const V = positionViewDirection;
  14039. const P = positionView.toVar();
  14040. const uv = LTC_Uv( { N, V, roughness } );
  14041. const t1 = ltc_1.sample( uv ).toVar();
  14042. const t2 = ltc_2.sample( uv ).toVar();
  14043. const mInv = mat3(
  14044. vec3( t1.x, 0, t1.y ),
  14045. vec3( 0, 1, 0 ),
  14046. vec3( t1.z, 0, t1.w )
  14047. ).toVar();
  14048. // LTC Fresnel Approximation by Stephen Hill
  14049. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  14050. const fresnel = specularColor.mul( t2.x ).add( specularColor.oneMinus().mul( t2.y ) ).toVar();
  14051. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  14052. 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 } ) ) );
  14053. }
  14054. /**
  14055. * Implements the indirect lighting.
  14056. *
  14057. * @param {ContextNode} context - The current node context.
  14058. * @param {StackNode} stack - The current stack.
  14059. * @param {NodeBuilder} builder - The current node builder.
  14060. */
  14061. indirect( context, stack, builder ) {
  14062. this.indirectDiffuse( context, stack, builder );
  14063. this.indirectSpecular( context, stack, builder );
  14064. this.ambientOcclusion( context, stack, builder );
  14065. }
  14066. /**
  14067. * Implements the indirect diffuse term.
  14068. *
  14069. * @param {ContextNode} input - The current node context.
  14070. * @param {StackNode} stack - The current stack.
  14071. * @param {NodeBuilder} builder - The current node builder.
  14072. */
  14073. indirectDiffuse( { irradiance, reflectedLight } ) {
  14074. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  14075. }
  14076. /**
  14077. * Implements the indirect specular term.
  14078. *
  14079. * @param {ContextNode} input - The current node context.
  14080. * @param {StackNode} stack - The current stack.
  14081. * @param {NodeBuilder} builder - The current node builder.
  14082. */
  14083. indirectSpecular( { radiance, iblIrradiance, reflectedLight } ) {
  14084. if ( this.sheen === true ) {
  14085. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  14086. sheen,
  14087. IBLSheenBRDF( {
  14088. normal: transformedNormalView,
  14089. viewDir: positionViewDirection,
  14090. roughness: sheenRoughness
  14091. } )
  14092. ) );
  14093. }
  14094. if ( this.clearcoat === true ) {
  14095. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  14096. const clearcoatEnv = EnvironmentBRDF( {
  14097. dotNV: dotNVcc,
  14098. specularColor: clearcoatF0,
  14099. specularF90: clearcoatF90,
  14100. roughness: clearcoatRoughness
  14101. } );
  14102. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  14103. }
  14104. // Both indirect specular and indirect diffuse light accumulate here
  14105. const singleScattering = vec3().toVar( 'singleScattering' );
  14106. const multiScattering = vec3().toVar( 'multiScattering' );
  14107. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  14108. this.computeMultiscattering( singleScattering, multiScattering, specularF90 );
  14109. const totalScattering = singleScattering.add( multiScattering );
  14110. const diffuse = diffuseColor.mul( totalScattering.r.max( totalScattering.g ).max( totalScattering.b ).oneMinus() );
  14111. reflectedLight.indirectSpecular.addAssign( radiance.mul( singleScattering ) );
  14112. reflectedLight.indirectSpecular.addAssign( multiScattering.mul( cosineWeightedIrradiance ) );
  14113. reflectedLight.indirectDiffuse.addAssign( diffuse.mul( cosineWeightedIrradiance ) );
  14114. }
  14115. /**
  14116. * Implements the ambient occlusion term.
  14117. *
  14118. * @param {ContextNode} input - The current node context.
  14119. * @param {StackNode} stack - The current stack.
  14120. * @param {NodeBuilder} builder - The current node builder.
  14121. */
  14122. ambientOcclusion( { ambientOcclusion, reflectedLight } ) {
  14123. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  14124. const aoNV = dotNV.add( ambientOcclusion );
  14125. const aoExp = roughness.mul( -16 ).oneMinus().negate().exp2();
  14126. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  14127. if ( this.clearcoat === true ) {
  14128. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  14129. }
  14130. if ( this.sheen === true ) {
  14131. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  14132. }
  14133. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  14134. reflectedLight.indirectSpecular.mulAssign( aoNode );
  14135. }
  14136. /**
  14137. * Used for final lighting accumulations depending on the requested features.
  14138. *
  14139. * @param {ContextNode} context - The current node context.
  14140. * @param {StackNode} stack - The current stack.
  14141. * @param {NodeBuilder} builder - The current node builder.
  14142. */
  14143. finish( context ) {
  14144. const { outgoingLight } = context;
  14145. if ( this.clearcoat === true ) {
  14146. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  14147. const Fcc = F_Schlick( {
  14148. dotVH: dotNVcc,
  14149. f0: clearcoatF0,
  14150. f90: clearcoatF90
  14151. } );
  14152. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  14153. outgoingLight.assign( clearcoatLight );
  14154. }
  14155. if ( this.sheen === true ) {
  14156. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( 0.157 ).oneMinus();
  14157. const sheenLight = outgoingLight.mul( sheenEnergyComp ).add( this.sheenSpecularDirect, this.sheenSpecularIndirect );
  14158. outgoingLight.assign( sheenLight );
  14159. }
  14160. }
  14161. }
  14162. // These defines must match with PMREMGenerator
  14163. const cubeUV_r0 = /*@__PURE__*/ float( 1.0 );
  14164. const cubeUV_m0 = /*@__PURE__*/ float( -2 );
  14165. const cubeUV_r1 = /*@__PURE__*/ float( 0.8 );
  14166. const cubeUV_m1 = /*@__PURE__*/ float( -1 );
  14167. const cubeUV_r4 = /*@__PURE__*/ float( 0.4 );
  14168. const cubeUV_m4 = /*@__PURE__*/ float( 2.0 );
  14169. const cubeUV_r5 = /*@__PURE__*/ float( 0.305 );
  14170. const cubeUV_m5 = /*@__PURE__*/ float( 3.0 );
  14171. const cubeUV_r6 = /*@__PURE__*/ float( 0.21 );
  14172. const cubeUV_m6 = /*@__PURE__*/ float( 4.0 );
  14173. const cubeUV_minMipLevel = /*@__PURE__*/ float( 4.0 );
  14174. const cubeUV_minTileSize = /*@__PURE__*/ float( 16.0 );
  14175. // These shader functions convert between the UV coordinates of a single face of
  14176. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  14177. // sampling a textureCube (not generally normalized ).
  14178. const getFace = /*@__PURE__*/ Fn( ( [ direction ] ) => {
  14179. const absDirection = vec3( abs( direction ) ).toVar();
  14180. const face = float( -1 ).toVar();
  14181. If( absDirection.x.greaterThan( absDirection.z ), () => {
  14182. If( absDirection.x.greaterThan( absDirection.y ), () => {
  14183. face.assign( select( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  14184. } ).Else( () => {
  14185. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  14186. } );
  14187. } ).Else( () => {
  14188. If( absDirection.z.greaterThan( absDirection.y ), () => {
  14189. face.assign( select( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  14190. } ).Else( () => {
  14191. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  14192. } );
  14193. } );
  14194. return face;
  14195. } ).setLayout( {
  14196. name: 'getFace',
  14197. type: 'float',
  14198. inputs: [
  14199. { name: 'direction', type: 'vec3' }
  14200. ]
  14201. } );
  14202. // RH coordinate system; PMREM face-indexing convention
  14203. const getUV = /*@__PURE__*/ Fn( ( [ direction, face ] ) => {
  14204. const uv = vec2().toVar();
  14205. If( face.equal( 0.0 ), () => {
  14206. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  14207. } ).ElseIf( face.equal( 1.0 ), () => {
  14208. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  14209. } ).ElseIf( face.equal( 2.0 ), () => {
  14210. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  14211. } ).ElseIf( face.equal( 3.0 ), () => {
  14212. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  14213. } ).ElseIf( face.equal( 4.0 ), () => {
  14214. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  14215. } ).Else( () => {
  14216. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  14217. } );
  14218. return mul( 0.5, uv.add( 1.0 ) );
  14219. } ).setLayout( {
  14220. name: 'getUV',
  14221. type: 'vec2',
  14222. inputs: [
  14223. { name: 'direction', type: 'vec3' },
  14224. { name: 'face', type: 'float' }
  14225. ]
  14226. } );
  14227. const roughnessToMip = /*@__PURE__*/ Fn( ( [ roughness ] ) => {
  14228. const mip = float( 0.0 ).toVar();
  14229. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  14230. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  14231. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  14232. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  14233. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  14234. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  14235. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  14236. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  14237. } ).Else( () => {
  14238. mip.assign( float( -2 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  14239. } );
  14240. return mip;
  14241. } ).setLayout( {
  14242. name: 'roughnessToMip',
  14243. type: 'float',
  14244. inputs: [
  14245. { name: 'roughness', type: 'float' }
  14246. ]
  14247. } );
  14248. // RH coordinate system; PMREM face-indexing convention
  14249. const getDirection = /*@__PURE__*/ Fn( ( [ uv_immutable, face ] ) => {
  14250. const uv = uv_immutable.toVar();
  14251. uv.assign( mul( 2.0, uv ).sub( 1.0 ) );
  14252. const direction = vec3( uv, 1.0 ).toVar();
  14253. If( face.equal( 0.0 ), () => {
  14254. direction.assign( direction.zyx ); // ( 1, v, u ) pos x
  14255. } ).ElseIf( face.equal( 1.0 ), () => {
  14256. direction.assign( direction.xzy );
  14257. direction.xz.mulAssign( -1 ); // ( -u, 1, -v ) pos y
  14258. } ).ElseIf( face.equal( 2.0 ), () => {
  14259. direction.x.mulAssign( -1 ); // ( -u, v, 1 ) pos z
  14260. } ).ElseIf( face.equal( 3.0 ), () => {
  14261. direction.assign( direction.zyx );
  14262. direction.xz.mulAssign( -1 ); // ( -1, v, -u ) neg x
  14263. } ).ElseIf( face.equal( 4.0 ), () => {
  14264. direction.assign( direction.xzy );
  14265. direction.xy.mulAssign( -1 ); // ( -u, -1, v ) neg y
  14266. } ).ElseIf( face.equal( 5.0 ), () => {
  14267. direction.z.mulAssign( -1 ); // ( u, v, -1 ) neg zS
  14268. } );
  14269. return direction;
  14270. } ).setLayout( {
  14271. name: 'getDirection',
  14272. type: 'vec3',
  14273. inputs: [
  14274. { name: 'uv', type: 'vec2' },
  14275. { name: 'face', type: 'float' }
  14276. ]
  14277. } );
  14278. //
  14279. const textureCubeUV = /*@__PURE__*/ Fn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  14280. const roughness = float( roughness_immutable );
  14281. const sampleDir = vec3( sampleDir_immutable );
  14282. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  14283. const mipF = fract( mip );
  14284. const mipInt = floor( mip );
  14285. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  14286. If( mipF.notEqual( 0.0 ), () => {
  14287. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  14288. color0.assign( mix( color0, color1, mipF ) );
  14289. } );
  14290. return color0;
  14291. } );
  14292. const bilinearCubeUV = /*@__PURE__*/ Fn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  14293. const mipInt = float( mipInt_immutable ).toVar();
  14294. const direction = vec3( direction_immutable );
  14295. const face = float( getFace( direction ) ).toVar();
  14296. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  14297. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  14298. const faceSize = float( exp2( mipInt ) ).toVar();
  14299. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  14300. If( face.greaterThan( 2.0 ), () => {
  14301. uv.y.addAssign( faceSize );
  14302. face.subAssign( 3.0 );
  14303. } );
  14304. uv.x.addAssign( face.mul( faceSize ) );
  14305. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  14306. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  14307. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  14308. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  14309. return envMap.sample( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  14310. } );
  14311. const getSample = /*@__PURE__*/ Fn( ( { envMap, mipInt, outputDirection, theta, axis, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  14312. const cosTheta = cos( theta );
  14313. // Rodrigues' axis-angle rotation
  14314. const sampleDirection = outputDirection.mul( cosTheta )
  14315. .add( axis.cross( outputDirection ).mul( sin( theta ) ) )
  14316. .add( axis.mul( axis.dot( outputDirection ).mul( cosTheta.oneMinus() ) ) );
  14317. return bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  14318. } );
  14319. const blur = /*@__PURE__*/ Fn( ( { n, latitudinal, poleAxis, outputDirection, weights, samples, dTheta, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  14320. const axis = vec3( select( latitudinal, poleAxis, cross( poleAxis, outputDirection ) ) ).toVar();
  14321. If( all( axis.equals( vec3( 0.0 ) ) ), () => {
  14322. axis.assign( vec3( outputDirection.z, 0.0, outputDirection.x.negate() ) );
  14323. } );
  14324. axis.assign( normalize( axis ) );
  14325. const gl_FragColor = vec3().toVar();
  14326. gl_FragColor.addAssign( weights.element( 0 ).mul( getSample( { theta: 0.0, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  14327. Loop( { start: int( 1 ), end: n }, ( { i } ) => {
  14328. If( i.greaterThanEqual( samples ), () => {
  14329. Break();
  14330. } );
  14331. const theta = float( dTheta.mul( float( i ) ) ).toVar();
  14332. 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 } ) ) );
  14333. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  14334. } );
  14335. return vec4( gl_FragColor, 1 );
  14336. } );
  14337. /** @module PMREMNode **/
  14338. let _generator = null;
  14339. const _cache = new WeakMap();
  14340. /**
  14341. * Generates the cubeUV size based on the given image height.
  14342. *
  14343. * @private
  14344. * @param {Number} imageHeight - The image height.
  14345. * @return {{texelWidth: Number,texelHeight: Number, maxMip: Number}} The result object.
  14346. */
  14347. function _generateCubeUVSize( imageHeight ) {
  14348. const maxMip = Math.log2( imageHeight ) - 2;
  14349. const texelHeight = 1.0 / imageHeight;
  14350. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  14351. return { texelWidth, texelHeight, maxMip };
  14352. }
  14353. /**
  14354. * Generates a PMREM from the given texture .
  14355. *
  14356. * @private
  14357. * @param {Texture} texture - The texture to create the PMREM for.
  14358. * @return {Texture} The PMREM.
  14359. */
  14360. function _getPMREMFromTexture( texture ) {
  14361. let cacheTexture = _cache.get( texture );
  14362. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : -1;
  14363. if ( pmremVersion !== texture.pmremVersion ) {
  14364. const image = texture.image;
  14365. if ( texture.isCubeTexture ) {
  14366. if ( isCubeMapReady( image ) ) {
  14367. cacheTexture = _generator.fromCubemap( texture, cacheTexture );
  14368. } else {
  14369. return null;
  14370. }
  14371. } else {
  14372. if ( isEquirectangularMapReady( image ) ) {
  14373. cacheTexture = _generator.fromEquirectangular( texture, cacheTexture );
  14374. } else {
  14375. return null;
  14376. }
  14377. }
  14378. cacheTexture.pmremVersion = texture.pmremVersion;
  14379. _cache.set( texture, cacheTexture );
  14380. }
  14381. return cacheTexture.texture;
  14382. }
  14383. /**
  14384. * This node represents a PMREM which is a special type of preprocessed
  14385. * environment map intended for PBR materials.
  14386. *
  14387. * ```js
  14388. * const material = new MeshStandardNodeMaterial();
  14389. * material.envNode = pmremTexture( envMap );
  14390. * ```
  14391. *
  14392. * @augments TempNode
  14393. */
  14394. class PMREMNode extends TempNode {
  14395. static get type() {
  14396. return 'PMREMNode';
  14397. }
  14398. /**
  14399. * Constructs a new function overloading node.
  14400. *
  14401. * @param {Texture} value - The input texture.
  14402. * @param {Node<vec2>} [uvNode=null] - The uv node.
  14403. * @param {Node<float>} [levelNode=null] - The level node.
  14404. */
  14405. constructor( value, uvNode = null, levelNode = null ) {
  14406. super( 'vec3' );
  14407. /**
  14408. * Reference to the input texture.
  14409. *
  14410. * @private
  14411. * @type {Texture}
  14412. */
  14413. this._value = value;
  14414. /**
  14415. * Reference to the generated PMREM.
  14416. *
  14417. * @private
  14418. * @type {Texture | null}
  14419. * @default null
  14420. */
  14421. this._pmrem = null;
  14422. /**
  14423. * The uv node.
  14424. *
  14425. * @type {Node<vec2>}
  14426. */
  14427. this.uvNode = uvNode;
  14428. /**
  14429. * The level node.
  14430. *
  14431. * @type {Node<float>}
  14432. */
  14433. this.levelNode = levelNode;
  14434. /**
  14435. * Reference to a PMREM generator.
  14436. *
  14437. * @private
  14438. * @type {PMREMGenerator}
  14439. * @default null
  14440. */
  14441. this._generator = null;
  14442. const defaultTexture = new Texture();
  14443. defaultTexture.isRenderTargetTexture = true;
  14444. /**
  14445. * The texture node holding the generated PMREM.
  14446. *
  14447. * @private
  14448. * @type {TextureNode}
  14449. */
  14450. this._texture = texture( defaultTexture );
  14451. /**
  14452. * A uniform representing the PMREM's width.
  14453. *
  14454. * @private
  14455. * @type {UniformNode<float>}
  14456. */
  14457. this._width = uniform( 0 );
  14458. /**
  14459. * A uniform representing the PMREM's height.
  14460. *
  14461. * @private
  14462. * @type {UniformNode<float>}
  14463. */
  14464. this._height = uniform( 0 );
  14465. /**
  14466. * A uniform representing the PMREM's max Mip.
  14467. *
  14468. * @private
  14469. * @type {UniformNode<float>}
  14470. */
  14471. this._maxMip = uniform( 0 );
  14472. /**
  14473. * The `updateBeforeType` is set to `NodeUpdateType.RENDER`.
  14474. *
  14475. * @type {String}
  14476. * @default 'render'
  14477. */
  14478. this.updateBeforeType = NodeUpdateType.RENDER;
  14479. }
  14480. set value( value ) {
  14481. this._value = value;
  14482. this._pmrem = null;
  14483. }
  14484. /**
  14485. * The node's texture value.
  14486. *
  14487. * @type {Texture}
  14488. */
  14489. get value() {
  14490. return this._value;
  14491. }
  14492. /**
  14493. * Uses the given PMREM texture to update internal values.
  14494. *
  14495. * @param {Texture} texture - The PMREM texture.
  14496. */
  14497. updateFromTexture( texture ) {
  14498. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  14499. this._texture.value = texture;
  14500. this._width.value = cubeUVSize.texelWidth;
  14501. this._height.value = cubeUVSize.texelHeight;
  14502. this._maxMip.value = cubeUVSize.maxMip;
  14503. }
  14504. updateBefore() {
  14505. let pmrem = this._pmrem;
  14506. const pmremVersion = pmrem ? pmrem.pmremVersion : -1;
  14507. const texture = this._value;
  14508. if ( pmremVersion !== texture.pmremVersion ) {
  14509. if ( texture.isPMREMTexture === true ) {
  14510. pmrem = texture;
  14511. } else {
  14512. pmrem = _getPMREMFromTexture( texture );
  14513. }
  14514. if ( pmrem !== null ) {
  14515. this._pmrem = pmrem;
  14516. this.updateFromTexture( pmrem );
  14517. }
  14518. }
  14519. }
  14520. setup( builder ) {
  14521. if ( _generator === null ) {
  14522. _generator = builder.createPMREMGenerator();
  14523. }
  14524. //
  14525. this.updateBefore( builder );
  14526. //
  14527. let uvNode = this.uvNode;
  14528. if ( uvNode === null && builder.context.getUV ) {
  14529. uvNode = builder.context.getUV( this );
  14530. }
  14531. //
  14532. const texture = this.value;
  14533. if ( builder.renderer.coordinateSystem === WebGLCoordinateSystem && texture.isPMREMTexture !== true && texture.isRenderTargetTexture === true ) {
  14534. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  14535. }
  14536. uvNode = vec3( uvNode.x, uvNode.y.negate(), uvNode.z );
  14537. //
  14538. let levelNode = this.levelNode;
  14539. if ( levelNode === null && builder.context.getTextureLevel ) {
  14540. levelNode = builder.context.getTextureLevel( this );
  14541. }
  14542. //
  14543. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  14544. }
  14545. }
  14546. /**
  14547. * Returns `true` if the given cube map image has been fully loaded.
  14548. *
  14549. * @private
  14550. * @param {Array<(Image|Object)>} image - The cube map image.
  14551. * @return {Boolean} Whether the given cube map is ready or not.
  14552. */
  14553. function isCubeMapReady( image ) {
  14554. if ( image === null || image === undefined ) return false;
  14555. let count = 0;
  14556. const length = 6;
  14557. for ( let i = 0; i < length; i ++ ) {
  14558. if ( image[ i ] !== undefined ) count ++;
  14559. }
  14560. return count === length;
  14561. }
  14562. /**
  14563. * Returns `true` if the given equirectangular image has been fully loaded.
  14564. *
  14565. * @private
  14566. * @param {(Image|Object)} image - The equirectangular image.
  14567. * @return {Boolean} Whether the given cube map is ready or not.
  14568. */
  14569. function isEquirectangularMapReady( image ) {
  14570. if ( image === null || image === undefined ) return false;
  14571. return image.height > 0;
  14572. }
  14573. /**
  14574. * TSL function for creating a PMREM node.
  14575. *
  14576. * @function
  14577. * @param {Texture} value - The input texture.
  14578. * @param {Node<vec2>} [uvNode=null] - The uv node.
  14579. * @param {Node<float>} [levelNode=null] - The level node.
  14580. * @returns {PMREMNode}
  14581. */
  14582. const pmremTexture = /*@__PURE__*/ nodeProxy( PMREMNode );
  14583. const _envNodeCache = new WeakMap();
  14584. /**
  14585. * Represents a physical model for Image-based lighting (IBL). The environment
  14586. * is defined via environment maps in the equirectangular, cube map or cubeUV (PMREM) format.
  14587. * `EnvironmentNode` is intended for PBR materials like {@link MeshStandardNodeMaterial}.
  14588. *
  14589. * @augments LightingNode
  14590. */
  14591. class EnvironmentNode extends LightingNode {
  14592. static get type() {
  14593. return 'EnvironmentNode';
  14594. }
  14595. /**
  14596. * Constructs a new environment node.
  14597. *
  14598. * @param {Node} [envNode=null] - A node representing the environment.
  14599. */
  14600. constructor( envNode = null ) {
  14601. super();
  14602. /**
  14603. * A node representing the environment.
  14604. *
  14605. * @type {Node?}
  14606. * @default null
  14607. */
  14608. this.envNode = envNode;
  14609. }
  14610. setup( builder ) {
  14611. const { material } = builder;
  14612. let envNode = this.envNode;
  14613. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  14614. const value = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  14615. let cacheEnvNode = _envNodeCache.get( value );
  14616. if ( cacheEnvNode === undefined ) {
  14617. cacheEnvNode = pmremTexture( value );
  14618. _envNodeCache.set( value, cacheEnvNode );
  14619. }
  14620. envNode = cacheEnvNode;
  14621. }
  14622. //
  14623. const envMap = material.envMap;
  14624. const intensity = envMap ? reference( 'envMapIntensity', 'float', builder.material ) : reference( 'environmentIntensity', 'float', builder.scene ); // @TODO: Add materialEnvIntensity in MaterialNode
  14625. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  14626. const radianceNormalView = useAnisotropy ? transformedBentNormalView : transformedNormalView;
  14627. const radiance = envNode.context( createRadianceContext( roughness, radianceNormalView ) ).mul( intensity );
  14628. const irradiance = envNode.context( createIrradianceContext( transformedNormalWorld ) ).mul( Math.PI ).mul( intensity );
  14629. const isolateRadiance = cache( radiance );
  14630. const isolateIrradiance = cache( irradiance );
  14631. //
  14632. builder.context.radiance.addAssign( isolateRadiance );
  14633. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  14634. //
  14635. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  14636. if ( clearcoatRadiance ) {
  14637. const clearcoatRadianceContext = envNode.context( createRadianceContext( clearcoatRoughness, transformedClearcoatNormalView ) ).mul( intensity );
  14638. const isolateClearcoatRadiance = cache( clearcoatRadianceContext );
  14639. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  14640. }
  14641. }
  14642. }
  14643. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  14644. let reflectVec = null;
  14645. return {
  14646. getUV: () => {
  14647. if ( reflectVec === null ) {
  14648. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  14649. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  14650. reflectVec = roughnessNode.mul( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  14651. reflectVec = reflectVec.transformDirection( cameraViewMatrix );
  14652. }
  14653. return reflectVec;
  14654. },
  14655. getTextureLevel: () => {
  14656. return roughnessNode;
  14657. }
  14658. };
  14659. };
  14660. const createIrradianceContext = ( normalWorldNode ) => {
  14661. return {
  14662. getUV: () => {
  14663. return normalWorldNode;
  14664. },
  14665. getTextureLevel: () => {
  14666. return float( 1.0 );
  14667. }
  14668. };
  14669. };
  14670. const _defaultValues$6 = /*@__PURE__*/ new MeshStandardMaterial();
  14671. /**
  14672. * Node material version of `MeshStandardMaterial`.
  14673. *
  14674. * @augments NodeMaterial
  14675. */
  14676. class MeshStandardNodeMaterial extends NodeMaterial {
  14677. static get type() {
  14678. return 'MeshStandardNodeMaterial';
  14679. }
  14680. /**
  14681. * Constructs a new mesh standard node material.
  14682. *
  14683. * @param {Object?} parameters - The configuration parameter.
  14684. */
  14685. constructor( parameters ) {
  14686. super();
  14687. /**
  14688. * This flag can be used for type testing.
  14689. *
  14690. * @type {Boolean}
  14691. * @readonly
  14692. * @default true
  14693. */
  14694. this.isMeshStandardNodeMaterial = true;
  14695. /**
  14696. * Set to `true` because standard materials react on lights.
  14697. *
  14698. * @type {Boolean}
  14699. * @default true
  14700. */
  14701. this.lights = true;
  14702. /**
  14703. * The emissive color of standard materials is by default inferred from the `emissive`,
  14704. * `emissiveIntensity` and `emissiveMap` properties. This node property allows to
  14705. * overwrite the default and define the emissive color with a node instead.
  14706. *
  14707. * If you don't want to overwrite the emissive color but modify the existing
  14708. * value instead, use {@link module:MaterialNode.materialEmissive}.
  14709. *
  14710. * @type {Node<vec3>?}
  14711. * @default null
  14712. */
  14713. this.emissiveNode = null;
  14714. /**
  14715. * The metalness of standard materials is by default inferred from the `metalness`,
  14716. * and `metalnessMap` properties. This node property allows to
  14717. * overwrite the default and define the metalness with a node instead.
  14718. *
  14719. * If you don't want to overwrite the metalness but modify the existing
  14720. * value instead, use {@link module:MaterialNode.materialMetalness}.
  14721. *
  14722. * @type {Node<float>?}
  14723. * @default null
  14724. */
  14725. this.metalnessNode = null;
  14726. /**
  14727. * The roughness of standard materials is by default inferred from the `roughness`,
  14728. * and `roughnessMap` properties. This node property allows to
  14729. * overwrite the default and define the roughness with a node instead.
  14730. *
  14731. * If you don't want to overwrite the roughness but modify the existing
  14732. * value instead, use {@link module:MaterialNode.materialRoughness}.
  14733. *
  14734. * @type {Node<float>?}
  14735. * @default null
  14736. */
  14737. this.roughnessNode = null;
  14738. this.setDefaultValues( _defaultValues$6 );
  14739. this.setValues( parameters );
  14740. }
  14741. /**
  14742. * Overwritten since this type of material uses {@link EnvironmentNode}
  14743. * to implement the PBR (PMREM based) environment mapping. Besides, the
  14744. * method honors `Scene.environment`.
  14745. *
  14746. * @param {NodeBuilder} builder - The current node builder.
  14747. * @return {EnvironmentNode<vec3>?} The environment node.
  14748. */
  14749. setupEnvironment( builder ) {
  14750. let envNode = super.setupEnvironment( builder );
  14751. if ( envNode === null && builder.environmentNode ) {
  14752. envNode = builder.environmentNode;
  14753. }
  14754. return envNode ? new EnvironmentNode( envNode ) : null;
  14755. }
  14756. /**
  14757. * Setups the lighting model.
  14758. *
  14759. * @return {PhysicalLightingModel} The lighting model.
  14760. */
  14761. setupLightingModel( /*builder*/ ) {
  14762. return new PhysicalLightingModel();
  14763. }
  14764. /**
  14765. * Setups the specular related node variables.
  14766. */
  14767. setupSpecular() {
  14768. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  14769. specularColor.assign( specularColorNode );
  14770. specularF90.assign( 1.0 );
  14771. }
  14772. /**
  14773. * Setups the standard specific node variables.
  14774. *
  14775. * @param {NodeBuilder} builder - The current node builder.
  14776. */
  14777. setupVariants() {
  14778. // METALNESS
  14779. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  14780. metalness.assign( metalnessNode );
  14781. // ROUGHNESS
  14782. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  14783. roughnessNode = getRoughness( { roughness: roughnessNode } );
  14784. roughness.assign( roughnessNode );
  14785. // SPECULAR COLOR
  14786. this.setupSpecular();
  14787. // DIFFUSE COLOR
  14788. diffuseColor.assign( vec4( diffuseColor.rgb.mul( metalnessNode.oneMinus() ), diffuseColor.a ) );
  14789. }
  14790. copy( source ) {
  14791. this.emissiveNode = source.emissiveNode;
  14792. this.metalnessNode = source.metalnessNode;
  14793. this.roughnessNode = source.roughnessNode;
  14794. return super.copy( source );
  14795. }
  14796. }
  14797. const _defaultValues$5 = /*@__PURE__*/ new MeshPhysicalMaterial();
  14798. /**
  14799. * Node material version of `MeshPhysicalMaterial`.
  14800. *
  14801. * @augments MeshStandardNodeMaterial
  14802. */
  14803. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  14804. static get type() {
  14805. return 'MeshPhysicalNodeMaterial';
  14806. }
  14807. /**
  14808. * Constructs a new mesh physical node material.
  14809. *
  14810. * @param {Object?} parameters - The configuration parameter.
  14811. */
  14812. constructor( parameters ) {
  14813. super();
  14814. /**
  14815. * This flag can be used for type testing.
  14816. *
  14817. * @type {Boolean}
  14818. * @readonly
  14819. * @default true
  14820. */
  14821. this.isMeshPhysicalNodeMaterial = true;
  14822. /**
  14823. * The clearcoat of physical materials is by default inferred from the `clearcoat`
  14824. * and `clearcoatMap` properties. This node property allows to overwrite the default
  14825. * and define the clearcoat with a node instead.
  14826. *
  14827. * If you don't want to overwrite the clearcoat but modify the existing
  14828. * value instead, use {@link module:MaterialNode.materialClearcoat}.
  14829. *
  14830. * @type {Node<float>?}
  14831. * @default null
  14832. */
  14833. this.clearcoatNode = null;
  14834. /**
  14835. * The clearcoat roughness of physical materials is by default inferred from the `clearcoatRoughness`
  14836. * and `clearcoatRoughnessMap` properties. This node property allows to overwrite the default
  14837. * and define the clearcoat roughness with a node instead.
  14838. *
  14839. * If you don't want to overwrite the clearcoat roughness but modify the existing
  14840. * value instead, use {@link module:MaterialNode.materialClearcoatRoughness}.
  14841. *
  14842. * @type {Node<float>?}
  14843. * @default null
  14844. */
  14845. this.clearcoatRoughnessNode = null;
  14846. /**
  14847. * The clearcoat normal of physical materials is by default inferred from the `clearcoatNormalMap`
  14848. * property. This node property allows to overwrite the default
  14849. * and define the clearcoat normal with a node instead.
  14850. *
  14851. * If you don't want to overwrite the clearcoat normal but modify the existing
  14852. * value instead, use {@link module:MaterialNode.materialClearcoatNormal}.
  14853. *
  14854. * @type {Node<vec3>?}
  14855. * @default null
  14856. */
  14857. this.clearcoatNormalNode = null;
  14858. /**
  14859. * The sheen of physical materials is by default inferred from the `sheen`, `sheenColor`
  14860. * and `sheenColorMap` properties. This node property allows to overwrite the default
  14861. * and define the sheen with a node instead.
  14862. *
  14863. * If you don't want to overwrite the sheen but modify the existing
  14864. * value instead, use {@link module:MaterialNode.materialSheen}.
  14865. *
  14866. * @type {Node<vec3>?}
  14867. * @default null
  14868. */
  14869. this.sheenNode = null;
  14870. /**
  14871. * The sheen roughness of physical materials is by default inferred from the `sheenRoughness` and
  14872. * `sheenRoughnessMap` properties. This node property allows to overwrite the default
  14873. * and define the sheen roughness with a node instead.
  14874. *
  14875. * If you don't want to overwrite the sheen roughness but modify the existing
  14876. * value instead, use {@link module:MaterialNode.materialSheenRoughness}.
  14877. *
  14878. * @type {Node<float>?}
  14879. * @default null
  14880. */
  14881. this.sheenRoughnessNode = null;
  14882. /**
  14883. * The iridescence of physical materials is by default inferred from the `iridescence`
  14884. * property. This node property allows to overwrite the default
  14885. * and define the iridescence with a node instead.
  14886. *
  14887. * If you don't want to overwrite the iridescence but modify the existing
  14888. * value instead, use {@link module:MaterialNode.materialIridescence}.
  14889. *
  14890. * @type {Node<float>?}
  14891. * @default null
  14892. */
  14893. this.iridescenceNode = null;
  14894. /**
  14895. * The iridescence IOR of physical materials is by default inferred from the `iridescenceIOR`
  14896. * property. This node property allows to overwrite the default
  14897. * and define the iridescence IOR with a node instead.
  14898. *
  14899. * If you don't want to overwrite the iridescence IOR but modify the existing
  14900. * value instead, use {@link module:MaterialNode.materialIridescenceIOR}.
  14901. *
  14902. * @type {Node<float>?}
  14903. * @default null
  14904. */
  14905. this.iridescenceIORNode = null;
  14906. /**
  14907. * The iridescence thickness of physical materials is by default inferred from the `iridescenceThicknessRange`
  14908. * and `iridescenceThicknessMap` properties. This node property allows to overwrite the default
  14909. * and define the iridescence thickness with a node instead.
  14910. *
  14911. * If you don't want to overwrite the iridescence thickness but modify the existing
  14912. * value instead, use {@link module:MaterialNode.materialIridescenceThickness}.
  14913. *
  14914. * @type {Node<float>?}
  14915. * @default null
  14916. */
  14917. this.iridescenceThicknessNode = null;
  14918. /**
  14919. * The specular intensity of physical materials is by default inferred from the `specularIntensity`
  14920. * and `specularIntensityMap` properties. This node property allows to overwrite the default
  14921. * and define the specular intensity with a node instead.
  14922. *
  14923. * If you don't want to overwrite the specular intensity but modify the existing
  14924. * value instead, use {@link module:MaterialNode.materialSpecularIntensity}.
  14925. *
  14926. * @type {Node<float>?}
  14927. * @default null
  14928. */
  14929. this.specularIntensityNode = null;
  14930. /**
  14931. * The specular color of physical materials is by default inferred from the `specularColor`
  14932. * and `specularColorMap` properties. This node property allows to overwrite the default
  14933. * and define the specular color with a node instead.
  14934. *
  14935. * If you don't want to overwrite the specular color but modify the existing
  14936. * value instead, use {@link module:MaterialNode.materialSpecularColor}.
  14937. *
  14938. * @type {Node<vec3>?}
  14939. * @default null
  14940. */
  14941. this.specularColorNode = null;
  14942. /**
  14943. * The ior of physical materials is by default inferred from the `ior`
  14944. * property. This node property allows to overwrite the default
  14945. * and define the ior with a node instead.
  14946. *
  14947. * If you don't want to overwrite the ior but modify the existing
  14948. * value instead, use {@link module:MaterialNode.materialIOR}.
  14949. *
  14950. * @type {Node<float>?}
  14951. * @default null
  14952. */
  14953. this.iorNode = null;
  14954. /**
  14955. * The transmission of physical materials is by default inferred from the `transmission` and
  14956. * `transmissionMap` properties. This node property allows to overwrite the default
  14957. * and define the transmission with a node instead.
  14958. *
  14959. * If you don't want to overwrite the transmission but modify the existing
  14960. * value instead, use {@link module:MaterialNode.materialTransmission}.
  14961. *
  14962. * @type {Node<float>?}
  14963. * @default null
  14964. */
  14965. this.transmissionNode = null;
  14966. /**
  14967. * The thickness of physical materials is by default inferred from the `thickness` and
  14968. * `thicknessMap` properties. This node property allows to overwrite the default
  14969. * and define the thickness with a node instead.
  14970. *
  14971. * If you don't want to overwrite the thickness but modify the existing
  14972. * value instead, use {@link module:MaterialNode.materialThickness}.
  14973. *
  14974. * @type {Node<float>?}
  14975. * @default null
  14976. */
  14977. this.thicknessNode = null;
  14978. /**
  14979. * The attenuation distance of physical materials is by default inferred from the
  14980. * `attenuationDistance` property. This node property allows to overwrite the default
  14981. * and define the attenuation distance with a node instead.
  14982. *
  14983. * If you don't want to overwrite the attenuation distance but modify the existing
  14984. * value instead, use {@link module:MaterialNode.materialAttenuationDistance}.
  14985. *
  14986. * @type {Node<float>?}
  14987. * @default null
  14988. */
  14989. this.attenuationDistanceNode = null;
  14990. /**
  14991. * The attenuation color of physical materials is by default inferred from the
  14992. * `attenuationColor` property. This node property allows to overwrite the default
  14993. * and define the attenuation color with a node instead.
  14994. *
  14995. * If you don't want to overwrite the attenuation color but modify the existing
  14996. * value instead, use {@link module:MaterialNode.materialAttenuationColor}.
  14997. *
  14998. * @type {Node<vec3>?}
  14999. * @default null
  15000. */
  15001. this.attenuationColorNode = null;
  15002. /**
  15003. * The dispersion of physical materials is by default inferred from the
  15004. * `dispersion` property. This node property allows to overwrite the default
  15005. * and define the dispersion with a node instead.
  15006. *
  15007. * If you don't want to overwrite the dispersion but modify the existing
  15008. * value instead, use {@link module:MaterialNode.materialDispersion}.
  15009. *
  15010. * @type {Node<float>?}
  15011. * @default null
  15012. */
  15013. this.dispersionNode = null;
  15014. /**
  15015. * The anisotropy of physical materials is by default inferred from the
  15016. * `anisotropy` property. This node property allows to overwrite the default
  15017. * and define the anisotropy with a node instead.
  15018. *
  15019. * If you don't want to overwrite the anisotropy but modify the existing
  15020. * value instead, use {@link module:MaterialNode.materialAnisotropy}.
  15021. *
  15022. * @type {Node<float>?}
  15023. * @default null
  15024. */
  15025. this.anisotropyNode = null;
  15026. this.setDefaultValues( _defaultValues$5 );
  15027. this.setValues( parameters );
  15028. }
  15029. /**
  15030. * Whether the lighting model should use clearcoat or not.
  15031. *
  15032. * @type {Boolean}
  15033. * @default true
  15034. */
  15035. get useClearcoat() {
  15036. return this.clearcoat > 0 || this.clearcoatNode !== null;
  15037. }
  15038. /**
  15039. * Whether the lighting model should use iridescence or not.
  15040. *
  15041. * @type {Boolean}
  15042. * @default true
  15043. */
  15044. get useIridescence() {
  15045. return this.iridescence > 0 || this.iridescenceNode !== null;
  15046. }
  15047. /**
  15048. * Whether the lighting model should use sheen or not.
  15049. *
  15050. * @type {Boolean}
  15051. * @default true
  15052. */
  15053. get useSheen() {
  15054. return this.sheen > 0 || this.sheenNode !== null;
  15055. }
  15056. /**
  15057. * Whether the lighting model should use anisotropy or not.
  15058. *
  15059. * @type {Boolean}
  15060. * @default true
  15061. */
  15062. get useAnisotropy() {
  15063. return this.anisotropy > 0 || this.anisotropyNode !== null;
  15064. }
  15065. /**
  15066. * Whether the lighting model should use transmission or not.
  15067. *
  15068. * @type {Boolean}
  15069. * @default true
  15070. */
  15071. get useTransmission() {
  15072. return this.transmission > 0 || this.transmissionNode !== null;
  15073. }
  15074. /**
  15075. * Whether the lighting model should use dispersion or not.
  15076. *
  15077. * @type {Boolean}
  15078. * @default true
  15079. */
  15080. get useDispersion() {
  15081. return this.dispersion > 0 || this.dispersionNode !== null;
  15082. }
  15083. /**
  15084. * Setups the specular related node variables.
  15085. */
  15086. setupSpecular() {
  15087. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  15088. ior.assign( iorNode );
  15089. 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 ) );
  15090. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  15091. }
  15092. /**
  15093. * Setups the lighting model.
  15094. *
  15095. * @return {PhysicalLightingModel} The lighting model.
  15096. */
  15097. setupLightingModel( /*builder*/ ) {
  15098. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion );
  15099. }
  15100. /**
  15101. * Setups the physical specific node variables.
  15102. *
  15103. * @param {NodeBuilder} builder - The current node builder.
  15104. */
  15105. setupVariants( builder ) {
  15106. super.setupVariants( builder );
  15107. // CLEARCOAT
  15108. if ( this.useClearcoat ) {
  15109. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  15110. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  15111. clearcoat.assign( clearcoatNode );
  15112. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  15113. }
  15114. // SHEEN
  15115. if ( this.useSheen ) {
  15116. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  15117. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  15118. sheen.assign( sheenNode );
  15119. sheenRoughness.assign( sheenRoughnessNode );
  15120. }
  15121. // IRIDESCENCE
  15122. if ( this.useIridescence ) {
  15123. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  15124. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  15125. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  15126. iridescence.assign( iridescenceNode );
  15127. iridescenceIOR.assign( iridescenceIORNode );
  15128. iridescenceThickness.assign( iridescenceThicknessNode );
  15129. }
  15130. // ANISOTROPY
  15131. if ( this.useAnisotropy ) {
  15132. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  15133. anisotropy.assign( anisotropyV.length() );
  15134. If( anisotropy.equal( 0.0 ), () => {
  15135. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  15136. } ).Else( () => {
  15137. anisotropyV.divAssign( vec2( anisotropy ) );
  15138. anisotropy.assign( anisotropy.saturate() );
  15139. } );
  15140. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  15141. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  15142. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  15143. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  15144. }
  15145. // TRANSMISSION
  15146. if ( this.useTransmission ) {
  15147. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  15148. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  15149. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  15150. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  15151. transmission.assign( transmissionNode );
  15152. thickness.assign( thicknessNode );
  15153. attenuationDistance.assign( attenuationDistanceNode );
  15154. attenuationColor.assign( attenuationColorNode );
  15155. if ( this.useDispersion ) {
  15156. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  15157. dispersion.assign( dispersionNode );
  15158. }
  15159. }
  15160. }
  15161. /**
  15162. * Setups the clearcoat normal node.
  15163. *
  15164. * @return {Node<vec3>} The clearcoat normal.
  15165. */
  15166. setupClearcoatNormal() {
  15167. return this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  15168. }
  15169. setup( builder ) {
  15170. builder.context.setupClearcoatNormal = () => this.setupClearcoatNormal( builder );
  15171. super.setup( builder );
  15172. }
  15173. copy( source ) {
  15174. this.clearcoatNode = source.clearcoatNode;
  15175. this.clearcoatRoughnessNode = source.clearcoatRoughnessNode;
  15176. this.clearcoatNormalNode = source.clearcoatNormalNode;
  15177. this.sheenNode = source.sheenNode;
  15178. this.sheenRoughnessNode = source.sheenRoughnessNode;
  15179. this.iridescenceNode = source.iridescenceNode;
  15180. this.iridescenceIORNode = source.iridescenceIORNode;
  15181. this.iridescenceThicknessNode = source.iridescenceThicknessNode;
  15182. this.specularIntensityNode = source.specularIntensityNode;
  15183. this.specularColorNode = source.specularColorNode;
  15184. this.transmissionNode = source.transmissionNode;
  15185. this.thicknessNode = source.thicknessNode;
  15186. this.attenuationDistanceNode = source.attenuationDistanceNode;
  15187. this.attenuationColorNode = source.attenuationColorNode;
  15188. this.dispersionNode = source.dispersionNode;
  15189. this.anisotropyNode = source.anisotropyNode;
  15190. return super.copy( source );
  15191. }
  15192. }
  15193. /** @module MeshSSSNodeMaterial **/
  15194. /**
  15195. * Represents the lighting model for {@link MeshSSSNodeMaterial}.
  15196. *
  15197. * @augments PhysicalLightingModel
  15198. */
  15199. class SSSLightingModel extends PhysicalLightingModel {
  15200. /**
  15201. * Constructs a new physical lighting model.
  15202. *
  15203. * @param {Boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  15204. * @param {Boolean} [sheen=false] - Whether sheen is supported or not.
  15205. * @param {Boolean} [iridescence=false] - Whether iridescence is supported or not.
  15206. * @param {Boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  15207. * @param {Boolean} [transmission=false] - Whether transmission is supported or not.
  15208. * @param {Boolean} [dispersion=false] - Whether dispersion is supported or not.
  15209. * @param {Boolean} [sss=false] - Whether SSS is supported or not.
  15210. */
  15211. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false, sss = false ) {
  15212. super( clearcoat, sheen, iridescence, anisotropy, transmission, dispersion );
  15213. /**
  15214. * Whether the lighting model should use SSS or not.
  15215. *
  15216. * @type {Boolean}
  15217. * @default false
  15218. */
  15219. this.useSSS = sss;
  15220. }
  15221. /**
  15222. * Extends the default implementation with a SSS term.
  15223. *
  15224. * 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/}
  15225. *
  15226. * @param {Object} input - The input data.
  15227. * @param {StackNode} stack - The current stack.
  15228. * @param {NodeBuilder} builder - The current node builder.
  15229. */
  15230. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  15231. if ( this.useSSS === true ) {
  15232. const material = builder.material;
  15233. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  15234. const scatteringHalf = lightDirection.add( transformedNormalView.mul( thicknessDistortionNode ) ).normalize();
  15235. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  15236. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  15237. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  15238. }
  15239. super.direct( { lightDirection, lightColor, reflectedLight }, stack, builder );
  15240. }
  15241. }
  15242. /**
  15243. * This node material is an experimental extension of {@link MeshPhysicalNodeMaterial}
  15244. * that implements a Subsurface scattering (SSS) term.
  15245. *
  15246. * @augments MeshPhysicalNodeMaterial
  15247. */
  15248. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  15249. static get type() {
  15250. return 'MeshSSSNodeMaterial';
  15251. }
  15252. /**
  15253. * Constructs a new mesh SSS node material.
  15254. *
  15255. * @param {Object?} parameters - The configuration parameter.
  15256. */
  15257. constructor( parameters ) {
  15258. super( parameters );
  15259. /**
  15260. * Represents the thickness color.
  15261. *
  15262. * @type {Node<vec3>?}
  15263. * @default null
  15264. */
  15265. this.thicknessColorNode = null;
  15266. /**
  15267. * Represents the distortion factor.
  15268. *
  15269. * @type {Node<float>?}
  15270. */
  15271. this.thicknessDistortionNode = float( 0.1 );
  15272. /**
  15273. * Represents the thickness ambient factor.
  15274. *
  15275. * @type {Node<float>?}
  15276. */
  15277. this.thicknessAmbientNode = float( 0.0 );
  15278. /**
  15279. * Represents the thickness attenuation.
  15280. *
  15281. * @type {Node<float>?}
  15282. */
  15283. this.thicknessAttenuationNode = float( .1 );
  15284. /**
  15285. * Represents the thickness power.
  15286. *
  15287. * @type {Node<float>?}
  15288. */
  15289. this.thicknessPowerNode = float( 2.0 );
  15290. /**
  15291. * Represents the thickness scale.
  15292. *
  15293. * @type {Node<float>?}
  15294. */
  15295. this.thicknessScaleNode = float( 10.0 );
  15296. }
  15297. /**
  15298. * Whether the lighting model should use SSS or not.
  15299. *
  15300. * @type {Boolean}
  15301. * @default true
  15302. */
  15303. get useSSS() {
  15304. return this.thicknessColorNode !== null;
  15305. }
  15306. /**
  15307. * Setups the lighting model.
  15308. *
  15309. * @return {SSSLightingModel} The lighting model.
  15310. */
  15311. setupLightingModel( /*builder*/ ) {
  15312. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion, this.useSSS );
  15313. }
  15314. copy( source ) {
  15315. this.thicknessColorNode = source.thicknessColorNode;
  15316. this.thicknessDistortionNode = source.thicknessDistortionNode;
  15317. this.thicknessAmbientNode = source.thicknessAmbientNode;
  15318. this.thicknessAttenuationNode = source.thicknessAttenuationNode;
  15319. this.thicknessPowerNode = source.thicknessPowerNode;
  15320. this.thicknessScaleNode = source.thicknessScaleNode;
  15321. return super.copy( source );
  15322. }
  15323. }
  15324. const getGradientIrradiance = /*@__PURE__*/ Fn( ( { normal, lightDirection, builder } ) => {
  15325. // dotNL will be from -1.0 to 1.0
  15326. const dotNL = normal.dot( lightDirection );
  15327. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  15328. if ( builder.material.gradientMap ) {
  15329. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  15330. return vec3( gradientMap.r );
  15331. } else {
  15332. const fw = coord.fwidth().mul( 0.5 );
  15333. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  15334. }
  15335. } );
  15336. /**
  15337. * Represents the lighting model for a toon material. Used in {@link MeshToonNodeMaterial}.
  15338. *
  15339. * @augments LightingModel
  15340. */
  15341. class ToonLightingModel extends LightingModel {
  15342. /**
  15343. * Implements the direct lighting. Instead of using a conventional smooth irradiance, the irradiance is
  15344. * reduced to a small number of discrete shades to create a comic-like, flat look.
  15345. *
  15346. * @param {Object} input - The input data.
  15347. * @param {StackNode} stack - The current stack.
  15348. * @param {NodeBuilder} builder - The current node builder.
  15349. */
  15350. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  15351. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  15352. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  15353. }
  15354. /**
  15355. * Implements the indirect lighting.
  15356. *
  15357. * @param {ContextNode} input - The current node context.
  15358. * @param {StackNode} stack - The current stack.
  15359. * @param {NodeBuilder} builder - The current node builder.
  15360. */
  15361. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  15362. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  15363. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  15364. }
  15365. }
  15366. const _defaultValues$4 = /*@__PURE__*/ new MeshToonMaterial();
  15367. /**
  15368. * Node material version of `MeshToonMaterial`.
  15369. *
  15370. * @augments NodeMaterial
  15371. */
  15372. class MeshToonNodeMaterial extends NodeMaterial {
  15373. static get type() {
  15374. return 'MeshToonNodeMaterial';
  15375. }
  15376. /**
  15377. * Constructs a new mesh toon node material.
  15378. *
  15379. * @param {Object?} parameters - The configuration parameter.
  15380. */
  15381. constructor( parameters ) {
  15382. super();
  15383. /**
  15384. * This flag can be used for type testing.
  15385. *
  15386. * @type {Boolean}
  15387. * @readonly
  15388. * @default true
  15389. */
  15390. this.isMeshToonNodeMaterial = true;
  15391. /**
  15392. * Set to `true` because toon materials react on lights.
  15393. *
  15394. * @type {Boolean}
  15395. * @default true
  15396. */
  15397. this.lights = true;
  15398. this.setDefaultValues( _defaultValues$4 );
  15399. this.setValues( parameters );
  15400. }
  15401. /**
  15402. * Setups the lighting model.
  15403. *
  15404. * @return {ToonLightingModel} The lighting model.
  15405. */
  15406. setupLightingModel( /*builder*/ ) {
  15407. return new ToonLightingModel();
  15408. }
  15409. }
  15410. /** @module MatcapUVNode **/
  15411. /**
  15412. * Can be used to compute texture coordinates for projecting a
  15413. * matcap onto a mesh. Used by {@link MeshMatcapNodeMaterial}.
  15414. *
  15415. * @augments TempNode
  15416. */
  15417. class MatcapUVNode extends TempNode {
  15418. static get type() {
  15419. return 'MatcapUVNode';
  15420. }
  15421. /**
  15422. * Constructs a new matcap uv node.
  15423. */
  15424. constructor() {
  15425. super( 'vec2' );
  15426. }
  15427. setup() {
  15428. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  15429. const y = positionViewDirection.cross( x );
  15430. return vec2( x.dot( transformedNormalView ), y.dot( transformedNormalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  15431. }
  15432. }
  15433. /**
  15434. * TSL function for creating a matcap uv node.
  15435. *
  15436. * @function
  15437. * @returns {MatcapUVNode}
  15438. */
  15439. const matcapUV = /*@__PURE__*/ nodeImmutable( MatcapUVNode );
  15440. const _defaultValues$3 = /*@__PURE__*/ new MeshMatcapMaterial();
  15441. /**
  15442. * Node material version of `MeshMatcapMaterial`.
  15443. *
  15444. * @augments NodeMaterial
  15445. */
  15446. class MeshMatcapNodeMaterial extends NodeMaterial {
  15447. static get type() {
  15448. return 'MeshMatcapNodeMaterial';
  15449. }
  15450. /**
  15451. * Constructs a new mesh normal node material.
  15452. *
  15453. * @param {Object?} parameters - The configuration parameter.
  15454. */
  15455. constructor( parameters ) {
  15456. super();
  15457. /**
  15458. * This flag can be used for type testing.
  15459. *
  15460. * @type {Boolean}
  15461. * @readonly
  15462. * @default true
  15463. */
  15464. this.isMeshMatcapNodeMaterial = true;
  15465. this.setDefaultValues( _defaultValues$3 );
  15466. this.setValues( parameters );
  15467. }
  15468. /**
  15469. * Setups the matcap specific node variables.
  15470. *
  15471. * @param {NodeBuilder} builder - The current node builder.
  15472. */
  15473. setupVariants( builder ) {
  15474. const uv = matcapUV;
  15475. let matcapColor;
  15476. if ( builder.material.matcap ) {
  15477. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  15478. } else {
  15479. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  15480. }
  15481. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  15482. }
  15483. }
  15484. /** @module RotateNode **/
  15485. /**
  15486. * Applies a rotation to the given position node.
  15487. *
  15488. * @augments TempNode
  15489. */
  15490. class RotateNode extends TempNode {
  15491. static get type() {
  15492. return 'RotateNode';
  15493. }
  15494. /**
  15495. * Constructs a new rotate node.
  15496. *
  15497. * @param {Node} positionNode - The position node.
  15498. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  15499. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  15500. */
  15501. constructor( positionNode, rotationNode ) {
  15502. super();
  15503. /**
  15504. * The position node.
  15505. *
  15506. * @type {Node}
  15507. */
  15508. this.positionNode = positionNode;
  15509. /**
  15510. * Represents the rotation that is applied to the position node.
  15511. * Depending on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  15512. *
  15513. * @type {Node}
  15514. */
  15515. this.rotationNode = rotationNode;
  15516. }
  15517. /**
  15518. * The type of the {@link RotateNode#positionNode} defines the node's type.
  15519. *
  15520. * @param {NodeBuilder} builder - The current node builder.
  15521. * @return {String} The node's type.
  15522. */
  15523. getNodeType( builder ) {
  15524. return this.positionNode.getNodeType( builder );
  15525. }
  15526. setup( builder ) {
  15527. const { rotationNode, positionNode } = this;
  15528. const nodeType = this.getNodeType( builder );
  15529. if ( nodeType === 'vec2' ) {
  15530. const cosAngle = rotationNode.cos();
  15531. const sinAngle = rotationNode.sin();
  15532. const rotationMatrix = mat2(
  15533. cosAngle, sinAngle,
  15534. sinAngle.negate(), cosAngle
  15535. );
  15536. return rotationMatrix.mul( positionNode );
  15537. } else {
  15538. const rotation = rotationNode;
  15539. 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 ) );
  15540. 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 ) );
  15541. 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 ) );
  15542. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  15543. }
  15544. }
  15545. }
  15546. /**
  15547. * TSL function for creating a rotate node.
  15548. *
  15549. * @function
  15550. * @param {Node} positionNode - The position node.
  15551. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  15552. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  15553. * @returns {RotateNode}
  15554. */
  15555. const rotate = /*@__PURE__*/ nodeProxy( RotateNode );
  15556. const _defaultValues$2 = /*@__PURE__*/ new SpriteMaterial();
  15557. /**
  15558. * Node material version of `SpriteMaterial`.
  15559. *
  15560. * @augments NodeMaterial
  15561. */
  15562. class SpriteNodeMaterial extends NodeMaterial {
  15563. static get type() {
  15564. return 'SpriteNodeMaterial';
  15565. }
  15566. /**
  15567. * Constructs a new sprite node material.
  15568. *
  15569. * @param {Object?} parameters - The configuration parameter.
  15570. */
  15571. constructor( parameters ) {
  15572. super();
  15573. /**
  15574. * This flag can be used for type testing.
  15575. *
  15576. * @type {Boolean}
  15577. * @readonly
  15578. * @default true
  15579. */
  15580. this.isSpriteNodeMaterial = true;
  15581. this._useSizeAttenuation = true;
  15582. /**
  15583. * This property makes it possible to define the position of the sprite with a
  15584. * node. That can be useful when the material is used with instanced rendering
  15585. * and node data are defined with an instanced attribute node:
  15586. * ```js
  15587. * const positionAttribute = new InstancedBufferAttribute( new Float32Array( positions ), 3 );
  15588. * material.positionNode = instancedBufferAttribute( positionAttribute );
  15589. * ```
  15590. * Another possibility is to compute the instanced data with a compute shader:
  15591. * ```js
  15592. * const positionBuffer = instancedArray( particleCount, 'vec3' );
  15593. * particleMaterial.positionNode = positionBuffer.toAttribute();
  15594. * ```
  15595. *
  15596. * @type {Node<vec2>?}
  15597. * @default null
  15598. */
  15599. this.positionNode = null;
  15600. /**
  15601. * The rotation of sprite materials is by default inferred from the `rotation`,
  15602. * property. This node property allows to overwrite the default and define
  15603. * the rotation with a node instead.
  15604. *
  15605. * If you don't want to overwrite the rotation but modify the existing
  15606. * value instead, use {@link module:MaterialNode.materialRotation}.
  15607. *
  15608. * @type {Node<float>?}
  15609. * @default null
  15610. */
  15611. this.rotationNode = null;
  15612. /**
  15613. * This node property provides an additional way to scale sprites next to
  15614. * `Object3D.scale`. The scale transformation based in `Object3D.scale`
  15615. * is multiplied with the scale value of this node in the vertex shader.
  15616. *
  15617. * @type {Node<vec2>?}
  15618. * @default null
  15619. */
  15620. this.scaleNode = null;
  15621. this.setDefaultValues( _defaultValues$2 );
  15622. this.setValues( parameters );
  15623. }
  15624. /**
  15625. * Setups the position node in view space. This method implements
  15626. * the sprite specific vertex shader.
  15627. *
  15628. * @param {NodeBuilder} builder - The current node builder.
  15629. * @return {Node<vec3>} The position in view space.
  15630. */
  15631. setupPositionView( builder ) {
  15632. const { object, camera } = builder;
  15633. const sizeAttenuation = this.sizeAttenuation;
  15634. const { positionNode, rotationNode, scaleNode } = this;
  15635. const mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  15636. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  15637. if ( scaleNode !== null ) {
  15638. scale = scale.mul( float( scaleNode ) );
  15639. }
  15640. if ( sizeAttenuation === false ) {
  15641. if ( camera.isPerspectiveCamera ) {
  15642. scale = scale.mul( mvPosition.z.negate() );
  15643. } else {
  15644. const orthoScale = float( 2.0 ).div( cameraProjectionMatrix.element( 1 ).element( 1 ) );
  15645. scale = scale.mul( orthoScale.mul( 2 ) );
  15646. }
  15647. }
  15648. let alignedPosition = positionGeometry.xy;
  15649. if ( object.center && object.center.isVector2 === true ) {
  15650. const center = reference$1( 'center', 'vec2', object );
  15651. alignedPosition = alignedPosition.sub( center.sub( 0.5 ) );
  15652. }
  15653. alignedPosition = alignedPosition.mul( scale );
  15654. const rotation = float( rotationNode || materialRotation );
  15655. const rotatedPosition = rotate( alignedPosition, rotation );
  15656. return vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  15657. }
  15658. copy( source ) {
  15659. this.positionNode = source.positionNode;
  15660. this.rotationNode = source.rotationNode;
  15661. this.scaleNode = source.scaleNode;
  15662. return super.copy( source );
  15663. }
  15664. /**
  15665. * Whether to use size attenuation or not.
  15666. *
  15667. * @type {Boolean}
  15668. * @default true
  15669. */
  15670. get sizeAttenuation() {
  15671. return this._useSizeAttenuation;
  15672. }
  15673. set sizeAttenuation( value ) {
  15674. if ( this._useSizeAttenuation !== value ) {
  15675. this._useSizeAttenuation = value;
  15676. this.needsUpdate = true;
  15677. }
  15678. }
  15679. }
  15680. const _defaultValues$1 = /*@__PURE__*/ new PointsMaterial();
  15681. /**
  15682. * Node material version of `PointsMaterial`.
  15683. *
  15684. * @augments NodeMaterial
  15685. */
  15686. class PointsNodeMaterial extends SpriteNodeMaterial {
  15687. static get type() {
  15688. return 'PointsNodeMaterial';
  15689. }
  15690. /**
  15691. * Constructs a new points node material.
  15692. *
  15693. * @param {Object?} parameters - The configuration parameter.
  15694. */
  15695. constructor( parameters ) {
  15696. super();
  15697. /**
  15698. * This node property provides an additional way to set the point size.
  15699. *
  15700. * @type {Node<vec2>?}
  15701. * @default null
  15702. */
  15703. this.sizeNode = null;
  15704. /**
  15705. * This flag can be used for type testing.
  15706. *
  15707. * @type {Boolean}
  15708. * @readonly
  15709. * @default true
  15710. */
  15711. this.isPointsNodeMaterial = true;
  15712. this.setDefaultValues( _defaultValues$1 );
  15713. this.setValues( parameters );
  15714. }
  15715. setupPositionView() {
  15716. const { positionNode } = this;
  15717. return modelViewMatrix.mul( vec3( positionNode || positionLocal ) ).xyz;
  15718. }
  15719. setupVertex( builder ) {
  15720. const mvp = super.setupVertex( builder );
  15721. // skip further processing if the material is not a node material
  15722. if ( builder.material.isNodeMaterial !== true ) {
  15723. return mvp;
  15724. }
  15725. // ndc space
  15726. const { rotationNode, scaleNode, sizeNode } = this;
  15727. const alignedPosition = positionGeometry.xy.toVar();
  15728. const aspect = viewport.z.div( viewport.w );
  15729. // rotation
  15730. if ( rotationNode && rotationNode.isNode ) {
  15731. const rotation = float( rotationNode );
  15732. alignedPosition.assign( rotate( alignedPosition, rotation ) );
  15733. }
  15734. // point size
  15735. let pointSize = sizeNode !== null ? vec2( sizeNode ) : materialPointSize;
  15736. if ( this.sizeAttenuation === true ) {
  15737. pointSize = pointSize.mul( pointSize.div( positionView.z.negate() ) );
  15738. }
  15739. // scale
  15740. if ( scaleNode && scaleNode.isNode ) {
  15741. pointSize = pointSize.mul( vec2( scaleNode ) );
  15742. }
  15743. alignedPosition.mulAssign( pointSize.mul( 2 ) );
  15744. alignedPosition.assign( alignedPosition.div( viewport.z ) );
  15745. alignedPosition.y.assign( alignedPosition.y.mul( aspect ) );
  15746. // back to clip space
  15747. alignedPosition.assign( alignedPosition.mul( mvp.w ) );
  15748. //clipPos.xy += offset;
  15749. mvp.addAssign( vec4( alignedPosition, 0, 0 ) );
  15750. return mvp;
  15751. }
  15752. /**
  15753. * Whether alpha to coverage should be used or not.
  15754. *
  15755. * @type {Boolean}
  15756. * @default true
  15757. */
  15758. get alphaToCoverage() {
  15759. return this._useAlphaToCoverage;
  15760. }
  15761. set alphaToCoverage( value ) {
  15762. if ( this._useAlphaToCoverage !== value ) {
  15763. this._useAlphaToCoverage = value;
  15764. this.needsUpdate = true;
  15765. }
  15766. }
  15767. }
  15768. /**
  15769. * Represents lighting model for a shadow material. Used in {@link ShadowNodeMaterial}.
  15770. *
  15771. * @augments LightingModel
  15772. */
  15773. class ShadowMaskModel extends LightingModel {
  15774. /**
  15775. * Constructs a new shadow mask model.
  15776. */
  15777. constructor() {
  15778. super();
  15779. /**
  15780. * The shadow mask node.
  15781. *
  15782. * @type {Node}
  15783. */
  15784. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  15785. }
  15786. /**
  15787. * Only used to save the shadow mask.
  15788. *
  15789. * @param {Object} input - The input data.
  15790. */
  15791. direct( { shadowMask } ) {
  15792. this.shadowNode.mulAssign( shadowMask );
  15793. }
  15794. /**
  15795. * Uses the shadow mask to produce the final color.
  15796. *
  15797. * @param {ContextNode} context - The current node context.
  15798. */
  15799. finish( context ) {
  15800. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  15801. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  15802. }
  15803. }
  15804. const _defaultValues = /*@__PURE__*/ new ShadowMaterial();
  15805. /**
  15806. * Node material version of `ShadowMaterial`.
  15807. *
  15808. * @augments NodeMaterial
  15809. */
  15810. class ShadowNodeMaterial extends NodeMaterial {
  15811. static get type() {
  15812. return 'ShadowNodeMaterial';
  15813. }
  15814. /**
  15815. * Constructs a new shadow node material.
  15816. *
  15817. * @param {Object?} parameters - The configuration parameter.
  15818. */
  15819. constructor( parameters ) {
  15820. super();
  15821. /**
  15822. * This flag can be used for type testing.
  15823. *
  15824. * @type {Boolean}
  15825. * @readonly
  15826. * @default true
  15827. */
  15828. this.isShadowNodeMaterial = true;
  15829. /**
  15830. * Set to `true` because so it's possible to implement
  15831. * the shadow mask effect.
  15832. *
  15833. * @type {Boolean}
  15834. * @default true
  15835. */
  15836. this.lights = true;
  15837. this.setDefaultValues( _defaultValues );
  15838. this.setValues( parameters );
  15839. }
  15840. /**
  15841. * Setups the lighting model.
  15842. *
  15843. * @return {ShadowMaskModel} The lighting model.
  15844. */
  15845. setupLightingModel( /*builder*/ ) {
  15846. return new ShadowMaskModel();
  15847. }
  15848. }
  15849. /** @module Texture3DNode **/
  15850. const normal = Fn( ( { texture, uv } ) => {
  15851. const epsilon = 0.0001;
  15852. const ret = vec3().toVar();
  15853. If( uv.x.lessThan( epsilon ), () => {
  15854. ret.assign( vec3( 1, 0, 0 ) );
  15855. } ).ElseIf( uv.y.lessThan( epsilon ), () => {
  15856. ret.assign( vec3( 0, 1, 0 ) );
  15857. } ).ElseIf( uv.z.lessThan( epsilon ), () => {
  15858. ret.assign( vec3( 0, 0, 1 ) );
  15859. } ).ElseIf( uv.x.greaterThan( 1 - epsilon ), () => {
  15860. ret.assign( vec3( -1, 0, 0 ) );
  15861. } ).ElseIf( uv.y.greaterThan( 1 - epsilon ), () => {
  15862. ret.assign( vec3( 0, -1, 0 ) );
  15863. } ).ElseIf( uv.z.greaterThan( 1 - epsilon ), () => {
  15864. ret.assign( vec3( 0, 0, -1 ) );
  15865. } ).Else( () => {
  15866. const step = 0.01;
  15867. const x = texture.sample( uv.add( vec3( -0.01, 0.0, 0.0 ) ) ).r.sub( texture.sample( uv.add( vec3( step, 0.0, 0.0 ) ) ).r );
  15868. const y = texture.sample( uv.add( vec3( 0.0, -0.01, 0.0 ) ) ).r.sub( texture.sample( uv.add( vec3( 0.0, step, 0.0 ) ) ).r );
  15869. const z = texture.sample( uv.add( vec3( 0.0, 0.0, -0.01 ) ) ).r.sub( texture.sample( uv.add( vec3( 0.0, 0.0, step ) ) ).r );
  15870. ret.assign( vec3( x, y, z ) );
  15871. } );
  15872. return ret.normalize();
  15873. } );
  15874. /**
  15875. * This type of uniform node represents a 3D texture.
  15876. *
  15877. * @augments module:TextureNode~TextureNode
  15878. */
  15879. class Texture3DNode extends TextureNode {
  15880. static get type() {
  15881. return 'Texture3DNode';
  15882. }
  15883. /**
  15884. * Constructs a new 3D texture node.
  15885. *
  15886. * @param {Data3DTexture} value - The 3D texture.
  15887. * @param {Node<vec2|vec3>?} [uvNode=null] - The uv node.
  15888. * @param {Node<int>?} [levelNode=null] - The level node.
  15889. */
  15890. constructor( value, uvNode = null, levelNode = null ) {
  15891. super( value, uvNode, levelNode );
  15892. /**
  15893. * This flag can be used for type testing.
  15894. *
  15895. * @type {Boolean}
  15896. * @readonly
  15897. * @default true
  15898. */
  15899. this.isTexture3DNode = true;
  15900. }
  15901. /**
  15902. * Overwrites the default implementation to return a fixed value `'texture3D'`.
  15903. *
  15904. * @param {NodeBuilder} builder - The current node builder.
  15905. * @return {String} The input type.
  15906. */
  15907. getInputType( /*builder*/ ) {
  15908. return 'texture3D';
  15909. }
  15910. /**
  15911. * Returns a default uv node which is in context of 3D textures a three-dimensional
  15912. * uv node.
  15913. *
  15914. * @return {Node<vec3>} The default uv node.
  15915. */
  15916. getDefaultUV() {
  15917. return vec3( 0.5, 0.5, 0.5 );
  15918. }
  15919. /**
  15920. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  15921. * for 3D textures. The uv transformation matrix is not applied to 3D textures.
  15922. *
  15923. * @param {Boolean} value - The update toggle.
  15924. */
  15925. setUpdateMatrix( /*value*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  15926. /**
  15927. * Overwrites the default implementation to return the unmodified uv node.
  15928. *
  15929. * @param {NodeBuilder} builder - The current node builder.
  15930. * @param {Node} uvNode - The uv node to setup.
  15931. * @return {Node} The unmodified uv node.
  15932. */
  15933. setupUV( builder, uvNode ) {
  15934. const texture = this.value;
  15935. if ( builder.isFlipY() && ( texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true ) ) {
  15936. if ( this.sampler ) {
  15937. uvNode = uvNode.flipY();
  15938. } else {
  15939. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  15940. }
  15941. }
  15942. return uvNode;
  15943. }
  15944. /**
  15945. * Generates the uv code snippet.
  15946. *
  15947. * @param {NodeBuilder} builder - The current node builder.
  15948. * @param {Node} uvNode - The uv node to generate code for.
  15949. * @return {String} The generated code snippet.
  15950. */
  15951. generateUV( builder, uvNode ) {
  15952. return uvNode.build( builder, 'vec3' );
  15953. }
  15954. /**
  15955. * TODO.
  15956. *
  15957. * @param {Node<vec3>} uvNode - The uv node .
  15958. * @return {Node<vec3>} TODO.
  15959. */
  15960. normal( uvNode ) {
  15961. return normal( { texture: this, uv: uvNode } );
  15962. }
  15963. }
  15964. /**
  15965. * TSL function for creating a 3D texture node.
  15966. *
  15967. * @function
  15968. * @param {Data3DTexture} value - The 3D texture.
  15969. * @param {Node<vec2|vec3>?} [uvNode=null] - The uv node.
  15970. * @param {Node<int>?} [levelNode=null] - The level node.
  15971. * @returns {Texture3DNode}
  15972. */
  15973. const texture3D = /*@__PURE__*/ nodeProxy( Texture3DNode );
  15974. /** @module VolumeNodeMaterial **/
  15975. /**
  15976. * Node material intended for volume rendering. The volumetric data are
  15977. * defined with an instance of {@link Data3DTexture}.
  15978. *
  15979. * @augments NodeMaterial
  15980. */
  15981. class VolumeNodeMaterial extends NodeMaterial {
  15982. static get type() {
  15983. return 'VolumeNodeMaterial';
  15984. }
  15985. /**
  15986. * Constructs a new volume node material.
  15987. *
  15988. * @param {Object?} parameters - The configuration parameter.
  15989. */
  15990. constructor( parameters ) {
  15991. super();
  15992. /**
  15993. * This flag can be used for type testing.
  15994. *
  15995. * @type {Boolean}
  15996. * @readonly
  15997. * @default true
  15998. */
  15999. this.isVolumeNodeMaterial = true;
  16000. /**
  16001. * The base color of the volume.
  16002. *
  16003. * @type {Color}
  16004. * @default 100
  16005. */
  16006. this.base = new Color( 0xffffff );
  16007. /**
  16008. * A 3D data texture holding the volumetric data.
  16009. *
  16010. * @type {Data3DTexture?}
  16011. * @default null
  16012. */
  16013. this.map = null;
  16014. /**
  16015. * This number of samples for each ray that hits the mesh's surface
  16016. * and travels through the volume.
  16017. *
  16018. * @type {Number}
  16019. * @default 100
  16020. */
  16021. this.steps = 100;
  16022. /**
  16023. * Callback for {@link VolumeNodeMaterial#testNode}.
  16024. *
  16025. * @callback testNodeCallback
  16026. * @param {Data3DTexture<float>} map - The 3D texture.
  16027. * @param {Node<float>} mapValue - The sampled value inside the volume.
  16028. * @param {Node<vec3>} probe - The probe which is the entry point of the ray on the mesh's surface.
  16029. * @param {Node<vec4>} finalColor - The final color.
  16030. */
  16031. /**
  16032. * The volume rendering of this material works by shooting rays
  16033. * from the camera position through each fragment of the mesh's
  16034. * surface and sample the inner volume in a raymarching fashion
  16035. * multiple times.
  16036. *
  16037. * This node can be used to assign a callback function of type `Fn`
  16038. * that will be executed per sample. The callback receives the
  16039. * texture, the sampled texture value as well as position on the surface
  16040. * where the rays enters the volume. The last parameter is a color
  16041. * that allows the callback to determine the final color.
  16042. *
  16043. * @type {testNodeCallback?}
  16044. * @default null
  16045. */
  16046. this.testNode = null;
  16047. this.setValues( parameters );
  16048. }
  16049. /**
  16050. * Setups the vertex and fragment stage of this node material.
  16051. *
  16052. * @param {NodeBuilder} builder - The current node builder.
  16053. */
  16054. setup( builder ) {
  16055. const map = texture3D( this.map, null, 0 );
  16056. const hitBox = Fn( ( { orig, dir } ) => {
  16057. const box_min = vec3( -0.5 );
  16058. const box_max = vec3( 0.5 );
  16059. const inv_dir = dir.reciprocal();
  16060. const tmin_tmp = box_min.sub( orig ).mul( inv_dir );
  16061. const tmax_tmp = box_max.sub( orig ).mul( inv_dir );
  16062. const tmin = min$1( tmin_tmp, tmax_tmp );
  16063. const tmax = max$1( tmin_tmp, tmax_tmp );
  16064. const t0 = max$1( tmin.x, max$1( tmin.y, tmin.z ) );
  16065. const t1 = min$1( tmax.x, min$1( tmax.y, tmax.z ) );
  16066. return vec2( t0, t1 );
  16067. } );
  16068. this.fragmentNode = Fn( () => {
  16069. const vOrigin = varying( vec3( modelWorldMatrixInverse.mul( vec4( cameraPosition, 1.0 ) ) ) );
  16070. const vDirection = varying( positionGeometry.sub( vOrigin ) );
  16071. const rayDir = vDirection.normalize();
  16072. const bounds = vec2( hitBox( { orig: vOrigin, dir: rayDir } ) ).toVar();
  16073. bounds.x.greaterThan( bounds.y ).discard();
  16074. bounds.assign( vec2( max$1( bounds.x, 0.0 ), bounds.y ) );
  16075. const p = vec3( vOrigin.add( bounds.x.mul( rayDir ) ) ).toVar();
  16076. const inc = vec3( rayDir.abs().reciprocal() ).toVar();
  16077. const delta = float( min$1( inc.x, min$1( inc.y, inc.z ) ) ).toVar( 'delta' ); // used 'delta' name in loop
  16078. delta.divAssign( materialReference( 'steps', 'float' ) );
  16079. const ac = vec4( materialReference( 'base', 'color' ), 0.0 ).toVar();
  16080. Loop( { type: 'float', start: bounds.x, end: bounds.y, update: '+= delta' }, () => {
  16081. const d = property( 'float', 'd' ).assign( map.sample( p.add( 0.5 ) ).r );
  16082. if ( this.testNode !== null ) {
  16083. this.testNode( { map: map, mapValue: d, probe: p, finalColor: ac } ).append();
  16084. } else {
  16085. // default to show surface of mesh
  16086. ac.a.assign( 1 );
  16087. Break();
  16088. }
  16089. p.addAssign( rayDir.mul( delta ) );
  16090. } );
  16091. ac.a.equal( 0 ).discard();
  16092. return vec4( ac );
  16093. } )();
  16094. super.setup( builder );
  16095. }
  16096. }
  16097. /**
  16098. * This module manages the internal animation loop of the renderer.
  16099. *
  16100. * @private
  16101. */
  16102. class Animation {
  16103. /**
  16104. * Constructs a new animation loop management component.
  16105. *
  16106. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  16107. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  16108. */
  16109. constructor( nodes, info ) {
  16110. /**
  16111. * Renderer component for managing nodes related logic.
  16112. *
  16113. * @type {Nodes}
  16114. */
  16115. this.nodes = nodes;
  16116. /**
  16117. * Renderer component for managing metrics and monitoring data.
  16118. *
  16119. * @type {Info}
  16120. */
  16121. this.info = info;
  16122. /**
  16123. * A reference to the context from `requestAnimationFrame()` can
  16124. * be called (usually `window`).
  16125. *
  16126. * @type {Window|XRSession}
  16127. */
  16128. this._context = self;
  16129. /**
  16130. * The user-defined animation loop.
  16131. *
  16132. * @type {Function?}
  16133. * @default null
  16134. */
  16135. this._animationLoop = null;
  16136. /**
  16137. * The requestId which is returned from the `requestAnimationFrame()` call.
  16138. * Can be used to cancel the stop the animation loop.
  16139. *
  16140. * @type {Number?}
  16141. * @default null
  16142. */
  16143. this._requestId = null;
  16144. }
  16145. /**
  16146. * Starts the internal animation loop.
  16147. */
  16148. start() {
  16149. const update = ( time, frame ) => {
  16150. this._requestId = this._context.requestAnimationFrame( update );
  16151. if ( this.info.autoReset === true ) this.info.reset();
  16152. this.nodes.nodeFrame.update();
  16153. this.info.frame = this.nodes.nodeFrame.frameId;
  16154. if ( this._animationLoop !== null ) this._animationLoop( time, frame );
  16155. };
  16156. update();
  16157. }
  16158. /**
  16159. * Stops the internal animation loop.
  16160. */
  16161. stop() {
  16162. this._context.cancelAnimationFrame( this._requestId );
  16163. this._requestId = null;
  16164. }
  16165. /**
  16166. * Returns the user-level animation loop.
  16167. *
  16168. * @return {Function} The animation loop.
  16169. */
  16170. getAnimationLoop() {
  16171. return this._animationLoop;
  16172. }
  16173. /**
  16174. * Defines the user-level animation loop.
  16175. *
  16176. * @param {Function} callback - The animation loop.
  16177. */
  16178. setAnimationLoop( callback ) {
  16179. this._animationLoop = callback;
  16180. }
  16181. /**
  16182. * Returns the animation context.
  16183. *
  16184. * @return {Window|XRSession} The animation context.
  16185. */
  16186. getContext() {
  16187. return this._context;
  16188. }
  16189. /**
  16190. * Defines the context in which `requestAnimationFrame()` is executed.
  16191. *
  16192. * @param {Window|XRSession} context - The context to set.
  16193. */
  16194. setContext( context ) {
  16195. this._context = context;
  16196. }
  16197. /**
  16198. * Frees all internal resources and stops the animation loop.
  16199. */
  16200. dispose() {
  16201. this.stop();
  16202. }
  16203. }
  16204. /**
  16205. * Data structure for the renderer. It allows defining values
  16206. * with chained, hierarchical keys. Keys are meant to be
  16207. * objects since the module internally works with Weak Maps
  16208. * for performance reasons.
  16209. *
  16210. * @private
  16211. */
  16212. class ChainMap {
  16213. /**
  16214. * Constructs a new Chain Map.
  16215. */
  16216. constructor() {
  16217. /**
  16218. * The root Weak Map.
  16219. *
  16220. * @type {WeakMap}
  16221. */
  16222. this.weakMap = new WeakMap();
  16223. }
  16224. /**
  16225. * Returns the value for the given array of keys.
  16226. *
  16227. * @param {Array<Object>} keys - List of keys.
  16228. * @return {Any} The value. Returns `undefined` if no value was found.
  16229. */
  16230. get( keys ) {
  16231. let map = this.weakMap;
  16232. for ( let i = 0; i < keys.length - 1; i ++ ) {
  16233. map = map.get( keys[ i ] );
  16234. if ( map === undefined ) return undefined;
  16235. }
  16236. return map.get( keys[ keys.length - 1 ] );
  16237. }
  16238. /**
  16239. * Sets the value for the given keys.
  16240. *
  16241. * @param {Array<Object>} keys - List of keys.
  16242. * @param {Any} value - The value to set.
  16243. * @return {ChainMap} A reference to this Chain Map.
  16244. */
  16245. set( keys, value ) {
  16246. let map = this.weakMap;
  16247. for ( let i = 0; i < keys.length - 1; i ++ ) {
  16248. const key = keys[ i ];
  16249. if ( map.has( key ) === false ) map.set( key, new WeakMap() );
  16250. map = map.get( key );
  16251. }
  16252. map.set( keys[ keys.length - 1 ], value );
  16253. return this;
  16254. }
  16255. /**
  16256. * Deletes a value for the given keys.
  16257. *
  16258. * @param {Array<Object>} keys - The keys.
  16259. * @return {Boolean} Returns `true` if the value has been removed successfully and `false` if the value has not be found.
  16260. */
  16261. delete( keys ) {
  16262. let map = this.weakMap;
  16263. for ( let i = 0; i < keys.length - 1; i ++ ) {
  16264. map = map.get( keys[ i ] );
  16265. if ( map === undefined ) return false;
  16266. }
  16267. return map.delete( keys[ keys.length - 1 ] );
  16268. }
  16269. }
  16270. let _id$9 = 0;
  16271. function getKeys( obj ) {
  16272. const keys = Object.keys( obj );
  16273. let proto = Object.getPrototypeOf( obj );
  16274. while ( proto ) {
  16275. const descriptors = Object.getOwnPropertyDescriptors( proto );
  16276. for ( const key in descriptors ) {
  16277. if ( descriptors[ key ] !== undefined ) {
  16278. const descriptor = descriptors[ key ];
  16279. if ( descriptor && typeof descriptor.get === 'function' ) {
  16280. keys.push( key );
  16281. }
  16282. }
  16283. }
  16284. proto = Object.getPrototypeOf( proto );
  16285. }
  16286. return keys;
  16287. }
  16288. /**
  16289. * A render object is the renderer's representation of single entity that gets drawn
  16290. * with a draw command. There is no unique mapping of render objects to 3D objects in the
  16291. * scene since render objects also depend from the used material, the current render context
  16292. * and the current scene's lighting.
  16293. *
  16294. * In general, the basic process of the renderer is:
  16295. *
  16296. * - Analyze the 3D objects in the scene and generate render lists containing render items.
  16297. * - Process the render lists by calling one or more render commands for each render item.
  16298. * - For each render command, request a render object and perform the draw.
  16299. *
  16300. * The module provides an interface to get data required for the draw command like the actual
  16301. * draw parameters or vertex buffers. It also holds a series of caching related methods since
  16302. * creating render objects should only be done when necessary.
  16303. *
  16304. * @private
  16305. */
  16306. class RenderObject {
  16307. /**
  16308. * Constructs a new render object.
  16309. *
  16310. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  16311. * @param {Geometries} geometries - Renderer component for managing geometries.
  16312. * @param {Renderer} renderer - The renderer.
  16313. * @param {Object3D} object - The 3D object.
  16314. * @param {Material} material - The 3D object's material.
  16315. * @param {Scene} scene - The scene the 3D object belongs to.
  16316. * @param {Camera} camera - The camera the object should be rendered with.
  16317. * @param {LightsNode} lightsNode - The lights node.
  16318. * @param {RenderContext} renderContext - The render context.
  16319. * @param {ClippingContext} clippingContext - The clipping context.
  16320. */
  16321. constructor( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext ) {
  16322. this.id = _id$9 ++;
  16323. /**
  16324. * Renderer component for managing nodes related logic.
  16325. *
  16326. * @type {Nodes}
  16327. * @private
  16328. */
  16329. this._nodes = nodes;
  16330. /**
  16331. * Renderer component for managing geometries.
  16332. *
  16333. * @type {Geometries}
  16334. * @private
  16335. */
  16336. this._geometries = geometries;
  16337. /**
  16338. * The renderer.
  16339. *
  16340. * @type {Renderer}
  16341. */
  16342. this.renderer = renderer;
  16343. /**
  16344. * The 3D object.
  16345. *
  16346. * @type {Object3D}
  16347. */
  16348. this.object = object;
  16349. /**
  16350. * The 3D object's material.
  16351. *
  16352. * @type {Material}
  16353. */
  16354. this.material = material;
  16355. /**
  16356. * The scene the 3D object belongs to.
  16357. *
  16358. * @type {Scene}
  16359. */
  16360. this.scene = scene;
  16361. /**
  16362. * The camera the 3D object should be rendered with.
  16363. *
  16364. * @type {Camera}
  16365. */
  16366. this.camera = camera;
  16367. /**
  16368. * The lights node.
  16369. *
  16370. * @type {LightsNode}
  16371. */
  16372. this.lightsNode = lightsNode;
  16373. /**
  16374. * The render context.
  16375. *
  16376. * @type {RenderContext}
  16377. */
  16378. this.context = renderContext;
  16379. /**
  16380. * The 3D object's geometry.
  16381. *
  16382. * @type {BufferGeometry}
  16383. */
  16384. this.geometry = object.geometry;
  16385. /**
  16386. * The render object's version.
  16387. *
  16388. * @type {Number}
  16389. */
  16390. this.version = material.version;
  16391. /**
  16392. * The draw range of the geometry.
  16393. *
  16394. * @type {Object?}
  16395. * @default null
  16396. */
  16397. this.drawRange = null;
  16398. /**
  16399. * An array holding the buffer attributes
  16400. * of the render object. This entails attribute
  16401. * definitions on geometry and node level.
  16402. *
  16403. * @type {Array<BufferAttribute>?}
  16404. * @default null
  16405. */
  16406. this.attributes = null;
  16407. /**
  16408. * A reference to a render pipeline the render
  16409. * object is processed with.
  16410. *
  16411. * @type {RenderPipeline}
  16412. * @default null
  16413. */
  16414. this.pipeline = null;
  16415. /**
  16416. * Only relevant for objects using
  16417. * multiple materials. This represents a group entry
  16418. * from the respective `BufferGeometry`.
  16419. *
  16420. * @type {{start: Number, count: Number}?}
  16421. * @default null
  16422. */
  16423. this.group = null;
  16424. /**
  16425. * An array holding the vertex buffers which can
  16426. * be buffer attributes but also interleaved buffers.
  16427. *
  16428. * @type {Array<BufferAttribute|InterleavedBuffer>?}
  16429. * @default null
  16430. */
  16431. this.vertexBuffers = null;
  16432. /**
  16433. * The parameters for the draw command.
  16434. *
  16435. * @type {Object?}
  16436. * @default null
  16437. */
  16438. this.drawParams = null;
  16439. /**
  16440. * If this render object is used inside a render bundle,
  16441. * this property points to the respective bundle group.
  16442. *
  16443. * @type {BundleGroup?}
  16444. * @default null
  16445. */
  16446. this.bundle = null;
  16447. /**
  16448. * The clipping context.
  16449. *
  16450. * @type {ClippingContext}
  16451. */
  16452. this.clippingContext = clippingContext;
  16453. /**
  16454. * The clipping context's cache key.
  16455. *
  16456. * @type {String}
  16457. */
  16458. this.clippingContextCacheKey = clippingContext !== null ? clippingContext.cacheKey : '';
  16459. /**
  16460. * The initial node cache key.
  16461. *
  16462. * @type {Number}
  16463. */
  16464. this.initialNodesCacheKey = this.getDynamicCacheKey();
  16465. /**
  16466. * The initial cache key.
  16467. *
  16468. * @type {Number}
  16469. */
  16470. this.initialCacheKey = this.getCacheKey();
  16471. /**
  16472. * The node builder state.
  16473. *
  16474. * @type {NodeBuilderState?}
  16475. * @private
  16476. * @default null
  16477. */
  16478. this._nodeBuilderState = null;
  16479. /**
  16480. * An array of bindings.
  16481. *
  16482. * @type {Array<BindGroup>?}
  16483. * @private
  16484. * @default null
  16485. */
  16486. this._bindings = null;
  16487. /**
  16488. * Reference to the node material observer.
  16489. *
  16490. * @type {NodeMaterialObserver?}
  16491. * @private
  16492. * @default null
  16493. */
  16494. this._monitor = null;
  16495. /**
  16496. * An event listener which is defined by `RenderObjects`. It performs
  16497. * clean up tasks when `dispose()` on this render object.
  16498. *
  16499. * @method
  16500. */
  16501. this.onDispose = null;
  16502. /**
  16503. * This flag can be used for type testing.
  16504. *
  16505. * @type {Boolean}
  16506. * @readonly
  16507. * @default true
  16508. */
  16509. this.isRenderObject = true;
  16510. /**
  16511. * An event listener which is executed when `dispose()` is called on
  16512. * the render object's material.
  16513. *
  16514. * @method
  16515. */
  16516. this.onMaterialDispose = () => {
  16517. this.dispose();
  16518. };
  16519. this.material.addEventListener( 'dispose', this.onMaterialDispose );
  16520. }
  16521. /**
  16522. * Updates the clipping context.
  16523. *
  16524. * @param {ClippingContext} context - The clipping context to set.
  16525. */
  16526. updateClipping( context ) {
  16527. this.clippingContext = context;
  16528. }
  16529. /**
  16530. * Whether the clipping requires an update or not.
  16531. *
  16532. * @type {Boolean}
  16533. * @readonly
  16534. */
  16535. get clippingNeedsUpdate() {
  16536. if ( this.clippingContext === null || this.clippingContext.cacheKey === this.clippingContextCacheKey ) return false;
  16537. this.clippingContextCacheKey = this.clippingContext.cacheKey;
  16538. return true;
  16539. }
  16540. /**
  16541. * The number of clipping planes defined in context of hardware clipping.
  16542. *
  16543. * @type {Number}
  16544. * @readonly
  16545. */
  16546. get hardwareClippingPlanes() {
  16547. return this.material.hardwareClipping === true ? this.clippingContext.unionClippingCount : 0;
  16548. }
  16549. /**
  16550. * Returns the node builder state of this render object.
  16551. *
  16552. * @return {NodeBuilderState} The node builder state.
  16553. */
  16554. getNodeBuilderState() {
  16555. return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) );
  16556. }
  16557. /**
  16558. * Returns the node material observer of this render object.
  16559. *
  16560. * @return {NodeMaterialObserver} The node material observer.
  16561. */
  16562. getMonitor() {
  16563. return this._monitor || ( this._monitor = this.getNodeBuilderState().observer );
  16564. }
  16565. /**
  16566. * Returns an array of bind groups of this render object.
  16567. *
  16568. * @return {Array<BindGroup>} The bindings.
  16569. */
  16570. getBindings() {
  16571. return this._bindings || ( this._bindings = this.getNodeBuilderState().createBindings() );
  16572. }
  16573. /**
  16574. * Returns a binding group by group name of this render object.
  16575. *
  16576. * @param {String} name - The name of the binding group.
  16577. * @return {BindGroup?} The bindings.
  16578. */
  16579. getBindingGroup( name ) {
  16580. for ( const bindingGroup of this.getBindings() ) {
  16581. if ( bindingGroup.name === name ) {
  16582. return bindingGroup;
  16583. }
  16584. }
  16585. }
  16586. /**
  16587. * Returns the index of the render object's geometry.
  16588. *
  16589. * @return {BufferAttribute?} The index. Returns `null` for non-indexed geometries.
  16590. */
  16591. getIndex() {
  16592. return this._geometries.getIndex( this );
  16593. }
  16594. /**
  16595. * Returns the indirect buffer attribute.
  16596. *
  16597. * @return {BufferAttribute?} The indirect attribute. `null` if no indirect drawing is used.
  16598. */
  16599. getIndirect() {
  16600. return this._geometries.getIndirect( this );
  16601. }
  16602. /**
  16603. * Returns an array that acts as a key for identifying the render object in a chain map.
  16604. *
  16605. * @return {Array<Object>} An array with object references.
  16606. */
  16607. getChainArray() {
  16608. return [ this.object, this.material, this.context, this.lightsNode ];
  16609. }
  16610. /**
  16611. * This method is used when the geometry of a 3D object has been exchanged and the
  16612. * respective render object now requires an update.
  16613. *
  16614. * @param {BufferGeometry} geometry - The geometry to set.
  16615. */
  16616. setGeometry( geometry ) {
  16617. this.geometry = geometry;
  16618. this.attributes = null;
  16619. }
  16620. /**
  16621. * Returns the buffer attributes of the render object. The returned array holds
  16622. * attribute definitions on geometry and node level.
  16623. *
  16624. * @return {Array<BufferAttribute>} An array with buffer attributes.
  16625. */
  16626. getAttributes() {
  16627. if ( this.attributes !== null ) return this.attributes;
  16628. const nodeAttributes = this.getNodeBuilderState().nodeAttributes;
  16629. const geometry = this.geometry;
  16630. const attributes = [];
  16631. const vertexBuffers = new Set();
  16632. for ( const nodeAttribute of nodeAttributes ) {
  16633. const attribute = nodeAttribute.node && nodeAttribute.node.attribute ? nodeAttribute.node.attribute : geometry.getAttribute( nodeAttribute.name );
  16634. if ( attribute === undefined ) continue;
  16635. attributes.push( attribute );
  16636. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  16637. vertexBuffers.add( bufferAttribute );
  16638. }
  16639. this.attributes = attributes;
  16640. this.vertexBuffers = Array.from( vertexBuffers.values() );
  16641. return attributes;
  16642. }
  16643. /**
  16644. * Returns the vertex buffers of the render object.
  16645. *
  16646. * @return {Array<BufferAttribute|InterleavedBuffer>} An array with buffer attribute or interleaved buffers.
  16647. */
  16648. getVertexBuffers() {
  16649. if ( this.vertexBuffers === null ) this.getAttributes();
  16650. return this.vertexBuffers;
  16651. }
  16652. /**
  16653. * Returns the draw parameters for the render object.
  16654. *
  16655. * @return {{vertexCount: Number, firstVertex: Number, instanceCount: Number, firstInstance: Number}} The draw parameters.
  16656. */
  16657. getDrawParameters() {
  16658. const { object, material, geometry, group, drawRange } = this;
  16659. const drawParams = this.drawParams || ( this.drawParams = {
  16660. vertexCount: 0,
  16661. firstVertex: 0,
  16662. instanceCount: 0,
  16663. firstInstance: 0
  16664. } );
  16665. const index = this.getIndex();
  16666. const hasIndex = ( index !== null );
  16667. const instanceCount = geometry.isInstancedBufferGeometry ? geometry.instanceCount : ( object.count > 1 ? object.count : 1 );
  16668. if ( instanceCount === 0 ) return null;
  16669. drawParams.instanceCount = instanceCount;
  16670. if ( object.isBatchedMesh === true ) return drawParams;
  16671. let rangeFactor = 1;
  16672. if ( material.wireframe === true && ! object.isPoints && ! object.isLineSegments && ! object.isLine && ! object.isLineLoop ) {
  16673. rangeFactor = 2;
  16674. }
  16675. let firstVertex = drawRange.start * rangeFactor;
  16676. let lastVertex = ( drawRange.start + drawRange.count ) * rangeFactor;
  16677. if ( group !== null ) {
  16678. firstVertex = Math.max( firstVertex, group.start * rangeFactor );
  16679. lastVertex = Math.min( lastVertex, ( group.start + group.count ) * rangeFactor );
  16680. }
  16681. const position = geometry.attributes.position;
  16682. let itemCount = Infinity;
  16683. if ( hasIndex ) {
  16684. itemCount = index.count;
  16685. } else if ( position !== undefined && position !== null ) {
  16686. itemCount = position.count;
  16687. }
  16688. firstVertex = Math.max( firstVertex, 0 );
  16689. lastVertex = Math.min( lastVertex, itemCount );
  16690. const count = lastVertex - firstVertex;
  16691. if ( count < 0 || count === Infinity ) return null;
  16692. drawParams.vertexCount = count;
  16693. drawParams.firstVertex = firstVertex;
  16694. return drawParams;
  16695. }
  16696. /**
  16697. * Returns the render object's geometry cache key.
  16698. *
  16699. * The geometry cache key is part of the material cache key.
  16700. *
  16701. * @return {String} The geometry cache key.
  16702. */
  16703. getGeometryCacheKey() {
  16704. const { geometry } = this;
  16705. let cacheKey = '';
  16706. for ( const name of Object.keys( geometry.attributes ).sort() ) {
  16707. const attribute = geometry.attributes[ name ];
  16708. cacheKey += name + ',';
  16709. if ( attribute.data ) cacheKey += attribute.data.stride + ',';
  16710. if ( attribute.offset ) cacheKey += attribute.offset + ',';
  16711. if ( attribute.itemSize ) cacheKey += attribute.itemSize + ',';
  16712. if ( attribute.normalized ) cacheKey += 'n,';
  16713. }
  16714. // structural equality isn't sufficient for morph targets since the
  16715. // data are maintained in textures. only if the targets are all equal
  16716. // the texture and thus the instance of `MorphNode` can be shared.
  16717. for ( const name of Object.keys( geometry.morphAttributes ).sort() ) {
  16718. const targets = geometry.morphAttributes[ name ];
  16719. cacheKey += 'morph-' + name + ',';
  16720. for ( let i = 0, l = targets.length; i < l; i ++ ) {
  16721. const attribute = targets[ i ];
  16722. cacheKey += attribute.id + ',';
  16723. }
  16724. }
  16725. if ( geometry.index ) {
  16726. cacheKey += 'index,';
  16727. }
  16728. return cacheKey;
  16729. }
  16730. /**
  16731. * Returns the render object's material cache key.
  16732. *
  16733. * The material cache key is part of the render object cache key.
  16734. *
  16735. * @return {Number} The material cache key.
  16736. */
  16737. getMaterialCacheKey() {
  16738. const { object, material } = this;
  16739. let cacheKey = material.customProgramCacheKey();
  16740. for ( const property of getKeys( material ) ) {
  16741. if ( /^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test( property ) ) continue;
  16742. const value = material[ property ];
  16743. let valueKey;
  16744. if ( value !== null ) {
  16745. // some material values require a formatting
  16746. const type = typeof value;
  16747. if ( type === 'number' ) {
  16748. valueKey = value !== 0 ? '1' : '0'; // Convert to on/off, important for clearcoat, transmission, etc
  16749. } else if ( type === 'object' ) {
  16750. valueKey = '{';
  16751. if ( value.isTexture ) {
  16752. valueKey += value.mapping;
  16753. }
  16754. valueKey += '}';
  16755. } else {
  16756. valueKey = String( value );
  16757. }
  16758. } else {
  16759. valueKey = String( value );
  16760. }
  16761. cacheKey += /*property + ':' +*/ valueKey + ',';
  16762. }
  16763. cacheKey += this.clippingContextCacheKey + ',';
  16764. if ( object.geometry ) {
  16765. cacheKey += this.getGeometryCacheKey();
  16766. }
  16767. if ( object.skeleton ) {
  16768. cacheKey += object.skeleton.bones.length + ',';
  16769. }
  16770. if ( object.isBatchedMesh ) {
  16771. cacheKey += object._matricesTexture.uuid + ',';
  16772. if ( object._colorsTexture !== null ) {
  16773. cacheKey += object._colorsTexture.uuid + ',';
  16774. }
  16775. }
  16776. if ( object.count > 1 ) {
  16777. // TODO: https://github.com/mrdoob/three.js/pull/29066#issuecomment-2269400850
  16778. cacheKey += object.uuid + ',';
  16779. }
  16780. cacheKey += object.receiveShadow + ',';
  16781. return hashString( cacheKey );
  16782. }
  16783. /**
  16784. * Whether the geometry requires an update or not.
  16785. *
  16786. * @type {Boolean}
  16787. * @readonly
  16788. */
  16789. get needsGeometryUpdate() {
  16790. return this.geometry.id !== this.object.geometry.id;
  16791. }
  16792. /**
  16793. * Whether the render object requires an update or not.
  16794. *
  16795. * Note: There are two distinct places where render objects are checked for an update.
  16796. *
  16797. * 1. In `RenderObjects.get()` which is executed when the render object is request. This
  16798. * method checks the `needsUpdate` flag and recreates the render object if necessary.
  16799. * 2. In `Renderer._renderObjectDirect()` right after getting the render object via
  16800. * `RenderObjects.get()`. The render object's NodeMaterialObserver is then used to detect
  16801. * a need for a refresh due to material, geometry or object related value changes.
  16802. *
  16803. * TODO: Investigate if it's possible to merge both steps so there is only a single place
  16804. * that performs the 'needsUpdate' check.
  16805. *
  16806. * @type {Boolean}
  16807. * @readonly
  16808. */
  16809. get needsUpdate() {
  16810. return /*this.object.static !== true &&*/ ( this.initialNodesCacheKey !== this.getDynamicCacheKey() || this.clippingNeedsUpdate );
  16811. }
  16812. /**
  16813. * Returns the dynamic cache key which represents a key that is computed per draw command.
  16814. *
  16815. * @return {Number} The cache key.
  16816. */
  16817. getDynamicCacheKey() {
  16818. let cacheKey = 0;
  16819. // `Nodes.getCacheKey()` returns an environment cache key which is not relevant when
  16820. // the renderer is inside a shadow pass.
  16821. if ( this.material.isShadowPassMaterial !== true ) {
  16822. cacheKey = this._nodes.getCacheKey( this.scene, this.lightsNode );
  16823. }
  16824. if ( this.camera.isArrayCamera ) {
  16825. cacheKey = hash$1( cacheKey, this.camera.cameras.length );
  16826. }
  16827. if ( this.object.receiveShadow ) {
  16828. cacheKey = hash$1( cacheKey, 1 );
  16829. }
  16830. return cacheKey;
  16831. }
  16832. /**
  16833. * Returns the render object's cache key.
  16834. *
  16835. * @return {Number} The cache key.
  16836. */
  16837. getCacheKey() {
  16838. return this.getMaterialCacheKey() + this.getDynamicCacheKey();
  16839. }
  16840. /**
  16841. * Frees internal resources.
  16842. */
  16843. dispose() {
  16844. this.material.removeEventListener( 'dispose', this.onMaterialDispose );
  16845. this.onDispose();
  16846. }
  16847. }
  16848. const _chainKeys$5 = [];
  16849. /**
  16850. * This module manages the render objects of the renderer.
  16851. *
  16852. * @private
  16853. */
  16854. class RenderObjects {
  16855. /**
  16856. * Constructs a new render object management component.
  16857. *
  16858. * @param {Renderer} renderer - The renderer.
  16859. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  16860. * @param {Geometries} geometries - Renderer component for managing geometries.
  16861. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  16862. * @param {Bindings} bindings - Renderer component for managing bindings.
  16863. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  16864. */
  16865. constructor( renderer, nodes, geometries, pipelines, bindings, info ) {
  16866. /**
  16867. * The renderer.
  16868. *
  16869. * @type {Renderer}
  16870. */
  16871. this.renderer = renderer;
  16872. /**
  16873. * Renderer component for managing nodes related logic.
  16874. *
  16875. * @type {Nodes}
  16876. */
  16877. this.nodes = nodes;
  16878. /**
  16879. * Renderer component for managing geometries.
  16880. *
  16881. * @type {Geometries}
  16882. */
  16883. this.geometries = geometries;
  16884. /**
  16885. * Renderer component for managing pipelines.
  16886. *
  16887. * @type {Pipelines}
  16888. */
  16889. this.pipelines = pipelines;
  16890. /**
  16891. * Renderer component for managing bindings.
  16892. *
  16893. * @type {Bindings}
  16894. */
  16895. this.bindings = bindings;
  16896. /**
  16897. * Renderer component for managing metrics and monitoring data.
  16898. *
  16899. * @type {Info}
  16900. */
  16901. this.info = info;
  16902. /**
  16903. * A dictionary that manages render contexts in chain maps
  16904. * for each pass ID.
  16905. *
  16906. * @type {Object<String,ChainMap>}
  16907. */
  16908. this.chainMaps = {};
  16909. }
  16910. /**
  16911. * Returns a render object for the given object and state data.
  16912. *
  16913. * @param {Object3D} object - The 3D object.
  16914. * @param {Material} material - The 3D object's material.
  16915. * @param {Scene} scene - The scene the 3D object belongs to.
  16916. * @param {Camera} camera - The camera the 3D object should be rendered with.
  16917. * @param {LightsNode} lightsNode - The lights node.
  16918. * @param {RenderContext} renderContext - The render context.
  16919. * @param {ClippingContext} clippingContext - The clipping context.
  16920. * @param {String?} passId - An optional ID for identifying the pass.
  16921. * @return {RenderObject} The render object.
  16922. */
  16923. get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  16924. const chainMap = this.getChainMap( passId );
  16925. // reuse chainArray
  16926. _chainKeys$5[ 0 ] = object;
  16927. _chainKeys$5[ 1 ] = material;
  16928. _chainKeys$5[ 2 ] = renderContext;
  16929. _chainKeys$5[ 3 ] = lightsNode;
  16930. let renderObject = chainMap.get( _chainKeys$5 );
  16931. if ( renderObject === undefined ) {
  16932. renderObject = this.createRenderObject( this.nodes, this.geometries, this.renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  16933. chainMap.set( _chainKeys$5, renderObject );
  16934. } else {
  16935. renderObject.updateClipping( clippingContext );
  16936. if ( renderObject.needsGeometryUpdate ) {
  16937. renderObject.setGeometry( object.geometry );
  16938. }
  16939. if ( renderObject.version !== material.version || renderObject.needsUpdate ) {
  16940. if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) {
  16941. renderObject.dispose();
  16942. renderObject = this.get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  16943. } else {
  16944. renderObject.version = material.version;
  16945. }
  16946. }
  16947. }
  16948. _chainKeys$5.length = 0;
  16949. return renderObject;
  16950. }
  16951. /**
  16952. * Returns a chain map for the given pass ID.
  16953. *
  16954. * @param {String} [passId='default'] - The pass ID.
  16955. * @return {ChainMap} The chain map.
  16956. */
  16957. getChainMap( passId = 'default' ) {
  16958. return this.chainMaps[ passId ] || ( this.chainMaps[ passId ] = new ChainMap() );
  16959. }
  16960. /**
  16961. * Frees internal resources.
  16962. */
  16963. dispose() {
  16964. this.chainMaps = {};
  16965. }
  16966. /**
  16967. * Factory method for creating render objects with the given list of parameters.
  16968. *
  16969. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  16970. * @param {Geometries} geometries - Renderer component for managing geometries.
  16971. * @param {Renderer} renderer - The renderer.
  16972. * @param {Object3D} object - The 3D object.
  16973. * @param {Material} material - The object's material.
  16974. * @param {Scene} scene - The scene the 3D object belongs to.
  16975. * @param {Camera} camera - The camera the object should be rendered with.
  16976. * @param {LightsNode} lightsNode - The lights node.
  16977. * @param {RenderContext} renderContext - The render context.
  16978. * @param {ClippingContext} clippingContext - The clipping context.
  16979. * @param {String?} passId - An optional ID for identifying the pass.
  16980. * @return {RenderObject} The render object.
  16981. */
  16982. createRenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  16983. const chainMap = this.getChainMap( passId );
  16984. const renderObject = new RenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext );
  16985. renderObject.onDispose = () => {
  16986. this.pipelines.delete( renderObject );
  16987. this.bindings.delete( renderObject );
  16988. this.nodes.delete( renderObject );
  16989. chainMap.delete( renderObject.getChainArray() );
  16990. };
  16991. return renderObject;
  16992. }
  16993. }
  16994. /**
  16995. * Data structure for the renderer. It is intended to manage
  16996. * data of objects in dictionaries.
  16997. *
  16998. * @private
  16999. */
  17000. class DataMap {
  17001. /**
  17002. * Constructs a new data map.
  17003. */
  17004. constructor() {
  17005. /**
  17006. * `DataMap` internally uses a weak map
  17007. * to manage its data.
  17008. *
  17009. * @type {WeakMap}
  17010. */
  17011. this.data = new WeakMap();
  17012. }
  17013. /**
  17014. * Returns the dictionary for the given object.
  17015. *
  17016. * @param {Object} object - The object.
  17017. * @return {Object} The dictionary.
  17018. */
  17019. get( object ) {
  17020. let map = this.data.get( object );
  17021. if ( map === undefined ) {
  17022. map = {};
  17023. this.data.set( object, map );
  17024. }
  17025. return map;
  17026. }
  17027. /**
  17028. * Deletes the dictionary for the given object.
  17029. *
  17030. * @param {Object} object - The object.
  17031. * @return {Object?} The deleted dictionary.
  17032. */
  17033. delete( object ) {
  17034. let map = null;
  17035. if ( this.data.has( object ) ) {
  17036. map = this.data.get( object );
  17037. this.data.delete( object );
  17038. }
  17039. return map;
  17040. }
  17041. /**
  17042. * Returns `true` if the given object has a dictionary defined.
  17043. *
  17044. * @param {Object} object - The object to test.
  17045. * @return {Boolean} Whether a dictionary is defined or not.
  17046. */
  17047. has( object ) {
  17048. return this.data.has( object );
  17049. }
  17050. /**
  17051. * Frees internal resources.
  17052. */
  17053. dispose() {
  17054. this.data = new WeakMap();
  17055. }
  17056. }
  17057. const AttributeType = {
  17058. VERTEX: 1,
  17059. INDEX: 2,
  17060. STORAGE: 3,
  17061. INDIRECT: 4
  17062. };
  17063. // size of a chunk in bytes (STD140 layout)
  17064. const GPU_CHUNK_BYTES = 16;
  17065. // @TODO: Move to src/constants.js
  17066. const BlendColorFactor = 211;
  17067. const OneMinusBlendColorFactor = 212;
  17068. /**
  17069. * This renderer module manages geometry attributes.
  17070. *
  17071. * @private
  17072. * @augments DataMap
  17073. */
  17074. class Attributes extends DataMap {
  17075. /**
  17076. * Constructs a new attribute management component.
  17077. *
  17078. * @param {Backend} backend - The renderer's backend.
  17079. */
  17080. constructor( backend ) {
  17081. super();
  17082. /**
  17083. * The renderer's backend.
  17084. *
  17085. * @type {Backend}
  17086. */
  17087. this.backend = backend;
  17088. }
  17089. /**
  17090. * Deletes the data for the given attribute.
  17091. *
  17092. * @param {BufferAttribute} attribute - The attribute.
  17093. * @return {Object} The deleted attribute data.
  17094. */
  17095. delete( attribute ) {
  17096. const attributeData = super.delete( attribute );
  17097. if ( attributeData !== undefined ) {
  17098. this.backend.destroyAttribute( attribute );
  17099. }
  17100. return attributeData;
  17101. }
  17102. /**
  17103. * Updates the given attribute. This method creates attribute buffers
  17104. * for new attributes and updates data for existing ones.
  17105. *
  17106. * @param {BufferAttribute} attribute - The attribute to update.
  17107. * @param {Number} type - The attribute type.
  17108. */
  17109. update( attribute, type ) {
  17110. const data = this.get( attribute );
  17111. if ( data.version === undefined ) {
  17112. if ( type === AttributeType.VERTEX ) {
  17113. this.backend.createAttribute( attribute );
  17114. } else if ( type === AttributeType.INDEX ) {
  17115. this.backend.createIndexAttribute( attribute );
  17116. } else if ( type === AttributeType.STORAGE ) {
  17117. this.backend.createStorageAttribute( attribute );
  17118. } else if ( type === AttributeType.INDIRECT ) {
  17119. this.backend.createIndirectStorageAttribute( attribute );
  17120. }
  17121. data.version = this._getBufferAttribute( attribute ).version;
  17122. } else {
  17123. const bufferAttribute = this._getBufferAttribute( attribute );
  17124. if ( data.version < bufferAttribute.version || bufferAttribute.usage === DynamicDrawUsage ) {
  17125. this.backend.updateAttribute( attribute );
  17126. data.version = bufferAttribute.version;
  17127. }
  17128. }
  17129. }
  17130. /**
  17131. * Utility method for handling interleaved buffer attributes correctly.
  17132. * To process them, their `InterleavedBuffer` is returned.
  17133. *
  17134. * @param {BufferAttribute} attribute - The attribute.
  17135. * @return {BufferAttribute|InterleavedBuffer}
  17136. */
  17137. _getBufferAttribute( attribute ) {
  17138. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  17139. return attribute;
  17140. }
  17141. }
  17142. /**
  17143. * Returns the wireframe version for the given geometry.
  17144. *
  17145. * @private
  17146. * @function
  17147. * @param {BufferGeometry} geometry - The geometry.
  17148. * @return {Number} The version.
  17149. */
  17150. function getWireframeVersion( geometry ) {
  17151. return ( geometry.index !== null ) ? geometry.index.version : geometry.attributes.position.version;
  17152. }
  17153. /**
  17154. * Returns a wireframe index attribute for the given geometry.
  17155. *
  17156. * @private
  17157. * @function
  17158. * @param {BufferGeometry} geometry - The geometry.
  17159. * @return {BufferAttribute} The wireframe index attribute.
  17160. */
  17161. function getWireframeIndex( geometry ) {
  17162. const indices = [];
  17163. const geometryIndex = geometry.index;
  17164. const geometryPosition = geometry.attributes.position;
  17165. if ( geometryIndex !== null ) {
  17166. const array = geometryIndex.array;
  17167. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  17168. const a = array[ i + 0 ];
  17169. const b = array[ i + 1 ];
  17170. const c = array[ i + 2 ];
  17171. indices.push( a, b, b, c, c, a );
  17172. }
  17173. } else {
  17174. const array = geometryPosition.array;
  17175. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  17176. const a = i + 0;
  17177. const b = i + 1;
  17178. const c = i + 2;
  17179. indices.push( a, b, b, c, c, a );
  17180. }
  17181. }
  17182. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  17183. attribute.version = getWireframeVersion( geometry );
  17184. return attribute;
  17185. }
  17186. /**
  17187. * This renderer module manages geometries.
  17188. *
  17189. * @private
  17190. * @augments DataMap
  17191. */
  17192. class Geometries extends DataMap {
  17193. /**
  17194. * Constructs a new geometry management component.
  17195. *
  17196. * @param {Attributes} attributes - Renderer component for managing attributes.
  17197. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  17198. */
  17199. constructor( attributes, info ) {
  17200. super();
  17201. /**
  17202. * Renderer component for managing attributes.
  17203. *
  17204. * @type {Attributes}
  17205. */
  17206. this.attributes = attributes;
  17207. /**
  17208. * Renderer component for managing metrics and monitoring data.
  17209. *
  17210. * @type {Info}
  17211. */
  17212. this.info = info;
  17213. /**
  17214. * Weak Map for managing attributes for wireframe rendering.
  17215. *
  17216. * @type {WeakMap<BufferGeometry,BufferAttribute>}
  17217. */
  17218. this.wireframes = new WeakMap();
  17219. /**
  17220. * This Weak Map is used to make sure buffer attributes are
  17221. * updated only once per render call.
  17222. *
  17223. * @type {WeakMap<BufferAttribute,Number>}
  17224. */
  17225. this.attributeCall = new WeakMap();
  17226. }
  17227. /**
  17228. * Returns `true` if the given render object has an initialized geometry.
  17229. *
  17230. * @param {RenderObject} renderObject - The render object.
  17231. * @return {Boolean} Whether if the given render object has an initialized geometry or not.
  17232. */
  17233. has( renderObject ) {
  17234. const geometry = renderObject.geometry;
  17235. return super.has( geometry ) && this.get( geometry ).initialized === true;
  17236. }
  17237. /**
  17238. * Prepares the geometry of the given render object for rendering.
  17239. *
  17240. * @param {RenderObject} renderObject - The render object.
  17241. */
  17242. updateForRender( renderObject ) {
  17243. if ( this.has( renderObject ) === false ) this.initGeometry( renderObject );
  17244. this.updateAttributes( renderObject );
  17245. }
  17246. /**
  17247. * Initializes the geometry of the given render object.
  17248. *
  17249. * @param {RenderObject} renderObject - The render object.
  17250. */
  17251. initGeometry( renderObject ) {
  17252. const geometry = renderObject.geometry;
  17253. const geometryData = this.get( geometry );
  17254. geometryData.initialized = true;
  17255. this.info.memory.geometries ++;
  17256. const onDispose = () => {
  17257. this.info.memory.geometries --;
  17258. const index = geometry.index;
  17259. const geometryAttributes = renderObject.getAttributes();
  17260. if ( index !== null ) {
  17261. this.attributes.delete( index );
  17262. }
  17263. for ( const geometryAttribute of geometryAttributes ) {
  17264. this.attributes.delete( geometryAttribute );
  17265. }
  17266. const wireframeAttribute = this.wireframes.get( geometry );
  17267. if ( wireframeAttribute !== undefined ) {
  17268. this.attributes.delete( wireframeAttribute );
  17269. }
  17270. geometry.removeEventListener( 'dispose', onDispose );
  17271. };
  17272. geometry.addEventListener( 'dispose', onDispose );
  17273. }
  17274. /**
  17275. * Updates the geometry attributes of the given render object.
  17276. *
  17277. * @param {RenderObject} renderObject - The render object.
  17278. */
  17279. updateAttributes( renderObject ) {
  17280. // attributes
  17281. const attributes = renderObject.getAttributes();
  17282. for ( const attribute of attributes ) {
  17283. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  17284. this.updateAttribute( attribute, AttributeType.STORAGE );
  17285. } else {
  17286. this.updateAttribute( attribute, AttributeType.VERTEX );
  17287. }
  17288. }
  17289. // indexes
  17290. const index = this.getIndex( renderObject );
  17291. if ( index !== null ) {
  17292. this.updateAttribute( index, AttributeType.INDEX );
  17293. }
  17294. // indirect
  17295. const indirect = renderObject.geometry.indirect;
  17296. if ( indirect !== null ) {
  17297. this.updateAttribute( indirect, AttributeType.INDIRECT );
  17298. }
  17299. }
  17300. /**
  17301. * Updates the given attribute.
  17302. *
  17303. * @param {BufferAttribute} attribute - The attribute to update.
  17304. * @param {Number} type - The attribute type.
  17305. */
  17306. updateAttribute( attribute, type ) {
  17307. const callId = this.info.render.calls;
  17308. if ( ! attribute.isInterleavedBufferAttribute ) {
  17309. if ( this.attributeCall.get( attribute ) !== callId ) {
  17310. this.attributes.update( attribute, type );
  17311. this.attributeCall.set( attribute, callId );
  17312. }
  17313. } else {
  17314. if ( this.attributeCall.get( attribute ) === undefined ) {
  17315. this.attributes.update( attribute, type );
  17316. this.attributeCall.set( attribute, callId );
  17317. } else if ( this.attributeCall.get( attribute.data ) !== callId ) {
  17318. this.attributes.update( attribute, type );
  17319. this.attributeCall.set( attribute.data, callId );
  17320. this.attributeCall.set( attribute, callId );
  17321. }
  17322. }
  17323. }
  17324. /**
  17325. * Returns the indirect buffer attribute of the given render object.
  17326. *
  17327. * @param {RenderObject} renderObject - The render object.
  17328. * @return {BufferAttribute?} The indirect attribute. `null` if no indirect drawing is used.
  17329. */
  17330. getIndirect( renderObject ) {
  17331. return renderObject.geometry.indirect;
  17332. }
  17333. /**
  17334. * Returns the index of the given render object's geometry. This is implemented
  17335. * in a method to return a wireframe index if necessary.
  17336. *
  17337. * @param {RenderObject} renderObject - The render object.
  17338. * @return {BufferAttribute?} The index. Returns `null` for non-indexed geometries.
  17339. */
  17340. getIndex( renderObject ) {
  17341. const { geometry, material } = renderObject;
  17342. let index = geometry.index;
  17343. if ( material.wireframe === true ) {
  17344. const wireframes = this.wireframes;
  17345. let wireframeAttribute = wireframes.get( geometry );
  17346. if ( wireframeAttribute === undefined ) {
  17347. wireframeAttribute = getWireframeIndex( geometry );
  17348. wireframes.set( geometry, wireframeAttribute );
  17349. } else if ( wireframeAttribute.version !== getWireframeVersion( geometry ) ) {
  17350. this.attributes.delete( wireframeAttribute );
  17351. wireframeAttribute = getWireframeIndex( geometry );
  17352. wireframes.set( geometry, wireframeAttribute );
  17353. }
  17354. index = wireframeAttribute;
  17355. }
  17356. return index;
  17357. }
  17358. }
  17359. /**
  17360. * This renderer module provides a series of statistical information
  17361. * about the GPU memory and the rendering process. Useful for debugging
  17362. * and monitoring.
  17363. */
  17364. class Info {
  17365. /**
  17366. * Constructs a new info component.
  17367. */
  17368. constructor() {
  17369. /**
  17370. * Whether frame related metrics should automatically
  17371. * be resetted or not. This property should be set to `false`
  17372. * by apps which manage their own animation loop. They must
  17373. * then call `renderer.info.reset()` once per frame manually.
  17374. *
  17375. * @type {Boolean}
  17376. * @default true
  17377. */
  17378. this.autoReset = true;
  17379. /**
  17380. * The current frame ID. This ID is managed
  17381. * by `NodeFrame`.
  17382. *
  17383. * @type {Number}
  17384. * @readonly
  17385. * @default 0
  17386. */
  17387. this.frame = 0;
  17388. /**
  17389. * The number of render calls since the
  17390. * app has been started.
  17391. *
  17392. * @type {Number}
  17393. * @readonly
  17394. * @default 0
  17395. */
  17396. this.calls = 0;
  17397. /**
  17398. * Render related metrics.
  17399. *
  17400. * @type {Object}
  17401. * @readonly
  17402. * @property {Number} calls - The number of render calls since the app has been started.
  17403. * @property {Number} frameCalls - The number of render calls of the current frame.
  17404. * @property {Number} drawCalls - The number of draw calls of the current frame.
  17405. * @property {Number} triangles - The number of rendered triangle primitives of the current frame.
  17406. * @property {Number} points - The number of rendered point primitives of the current frame.
  17407. * @property {Number} lines - The number of rendered line primitives of the current frame.
  17408. * @property {Number} timestamp - The timestamp of the frame when using `renderer.renderAsync()`.
  17409. */
  17410. this.render = {
  17411. calls: 0,
  17412. frameCalls: 0,
  17413. drawCalls: 0,
  17414. triangles: 0,
  17415. points: 0,
  17416. lines: 0,
  17417. timestamp: 0,
  17418. };
  17419. /**
  17420. * Compute related metrics.
  17421. *
  17422. * @type {Object}
  17423. * @readonly
  17424. * @property {Number} calls - The number of compute calls since the app has been started.
  17425. * @property {Number} frameCalls - The number of compute calls of the current frame.
  17426. * @property {Number} timestamp - The timestamp of the frame when using `renderer.computeAsync()`.
  17427. */
  17428. this.compute = {
  17429. calls: 0,
  17430. frameCalls: 0,
  17431. timestamp: 0
  17432. };
  17433. /**
  17434. * Memory related metrics.
  17435. *
  17436. * @type {Object}
  17437. * @readonly
  17438. * @property {Number} geometries - The number of active geometries.
  17439. * @property {Number} frameCalls - The number of active textures.
  17440. */
  17441. this.memory = {
  17442. geometries: 0,
  17443. textures: 0
  17444. };
  17445. }
  17446. /**
  17447. * This method should be executed per draw call and updates the corresponding metrics.
  17448. *
  17449. * @param {Object3D} object - The 3D object that is going to be rendered.
  17450. * @param {Number} count - The vertex or index count.
  17451. * @param {Number} instanceCount - The instance count.
  17452. */
  17453. update( object, count, instanceCount ) {
  17454. this.render.drawCalls ++;
  17455. if ( object.isMesh || object.isSprite ) {
  17456. this.render.triangles += instanceCount * ( count / 3 );
  17457. } else if ( object.isPoints ) {
  17458. this.render.points += instanceCount * count;
  17459. } else if ( object.isLineSegments ) {
  17460. this.render.lines += instanceCount * ( count / 2 );
  17461. } else if ( object.isLine ) {
  17462. this.render.lines += instanceCount * ( count - 1 );
  17463. } else {
  17464. console.error( 'THREE.WebGPUInfo: Unknown object type.' );
  17465. }
  17466. }
  17467. /**
  17468. * Resets frame related metrics.
  17469. */
  17470. reset() {
  17471. this.render.drawCalls = 0;
  17472. this.render.frameCalls = 0;
  17473. this.compute.frameCalls = 0;
  17474. this.render.triangles = 0;
  17475. this.render.points = 0;
  17476. this.render.lines = 0;
  17477. }
  17478. /**
  17479. * Performs a complete reset of the object.
  17480. */
  17481. dispose() {
  17482. this.reset();
  17483. this.calls = 0;
  17484. this.render.calls = 0;
  17485. this.compute.calls = 0;
  17486. this.render.timestamp = 0;
  17487. this.compute.timestamp = 0;
  17488. this.memory.geometries = 0;
  17489. this.memory.textures = 0;
  17490. }
  17491. }
  17492. /**
  17493. * Abstract class for representing pipelines.
  17494. *
  17495. * @private
  17496. * @abstract
  17497. */
  17498. class Pipeline {
  17499. /**
  17500. * Constructs a new pipeline.
  17501. *
  17502. * @param {String} cacheKey - The pipeline's cache key.
  17503. */
  17504. constructor( cacheKey ) {
  17505. /**
  17506. * The pipeline's cache key.
  17507. *
  17508. * @type {String}
  17509. */
  17510. this.cacheKey = cacheKey;
  17511. /**
  17512. * How often the pipeline is currently in use.
  17513. *
  17514. * @type {Number}
  17515. * @default 0
  17516. */
  17517. this.usedTimes = 0;
  17518. }
  17519. }
  17520. /**
  17521. * Class for representing render pipelines.
  17522. *
  17523. * @private
  17524. * @augments Pipeline
  17525. */
  17526. class RenderPipeline extends Pipeline {
  17527. /**
  17528. * Constructs a new render pipeline.
  17529. *
  17530. * @param {String} cacheKey - The pipeline's cache key.
  17531. * @param {ProgrammableStage} vertexProgram - The pipeline's vertex shader.
  17532. * @param {ProgrammableStage} fragmentProgram - The pipeline's fragment shader.
  17533. */
  17534. constructor( cacheKey, vertexProgram, fragmentProgram ) {
  17535. super( cacheKey );
  17536. /**
  17537. * The pipeline's vertex shader.
  17538. *
  17539. * @type {ProgrammableStage}
  17540. */
  17541. this.vertexProgram = vertexProgram;
  17542. /**
  17543. * The pipeline's fragment shader.
  17544. *
  17545. * @type {ProgrammableStage}
  17546. */
  17547. this.fragmentProgram = fragmentProgram;
  17548. }
  17549. }
  17550. /**
  17551. * Class for representing compute pipelines.
  17552. *
  17553. * @private
  17554. * @augments Pipeline
  17555. */
  17556. class ComputePipeline extends Pipeline {
  17557. /**
  17558. * Constructs a new render pipeline.
  17559. *
  17560. * @param {String} cacheKey - The pipeline's cache key.
  17561. * @param {ProgrammableStage} computeProgram - The pipeline's compute shader.
  17562. */
  17563. constructor( cacheKey, computeProgram ) {
  17564. super( cacheKey );
  17565. /**
  17566. * The pipeline's compute shader.
  17567. *
  17568. * @type {ProgrammableStage}
  17569. */
  17570. this.computeProgram = computeProgram;
  17571. /**
  17572. * This flag can be used for type testing.
  17573. *
  17574. * @type {Boolean}
  17575. * @readonly
  17576. * @default true
  17577. */
  17578. this.isComputePipeline = true;
  17579. }
  17580. }
  17581. let _id$8 = 0;
  17582. /**
  17583. * Class for representing programmable stages which are vertex,
  17584. * fragment or compute shaders. Unlike fixed-function states (like blending),
  17585. * they represent the programmable part of a pipeline.
  17586. *
  17587. * @private
  17588. */
  17589. class ProgrammableStage {
  17590. /**
  17591. * Constructs a new programmable stage.
  17592. *
  17593. * @param {String} code - The shader code.
  17594. * @param {('vertex'|'fragment'|'compute')} stage - The type of stage.
  17595. * @param {String} name - The name of the shader.
  17596. * @param {Array<Object>?} [transforms=null] - The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  17597. * @param {Array<Object>?} [attributes=null] - The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  17598. */
  17599. constructor( code, stage, name, transforms = null, attributes = null ) {
  17600. /**
  17601. * The id of the programmable stage.
  17602. *
  17603. * @type {Number}
  17604. */
  17605. this.id = _id$8 ++;
  17606. /**
  17607. * The shader code.
  17608. *
  17609. * @type {String}
  17610. */
  17611. this.code = code;
  17612. /**
  17613. * The type of stage.
  17614. *
  17615. * @type {String}
  17616. */
  17617. this.stage = stage;
  17618. /**
  17619. * The name of the stage.
  17620. * This is used for debugging purposes.
  17621. *
  17622. * @type {String}
  17623. */
  17624. this.name = name;
  17625. /**
  17626. * The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  17627. *
  17628. * @type {Array<Object>?}
  17629. */
  17630. this.transforms = transforms;
  17631. /**
  17632. * The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  17633. *
  17634. * @type {Array<Object>?}
  17635. */
  17636. this.attributes = attributes;
  17637. /**
  17638. * How often the programmable stage is currently in use.
  17639. *
  17640. * @type {Number}
  17641. * @default 0
  17642. */
  17643. this.usedTimes = 0;
  17644. }
  17645. }
  17646. /**
  17647. * This renderer module manages the pipelines of the renderer.
  17648. *
  17649. * @private
  17650. * @augments DataMap
  17651. */
  17652. class Pipelines extends DataMap {
  17653. /**
  17654. * Constructs a new pipeline management component.
  17655. *
  17656. * @param {Backend} backend - The renderer's backend.
  17657. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  17658. */
  17659. constructor( backend, nodes ) {
  17660. super();
  17661. /**
  17662. * The renderer's backend.
  17663. *
  17664. * @type {Backend}
  17665. */
  17666. this.backend = backend;
  17667. /**
  17668. * Renderer component for managing nodes related logic.
  17669. *
  17670. * @type {Nodes}
  17671. */
  17672. this.nodes = nodes;
  17673. /**
  17674. * A references to the bindings management component.
  17675. * This reference will be set inside the `Bindings`
  17676. * constructor.
  17677. *
  17678. * @type {Bindings?}
  17679. * @default null
  17680. */
  17681. this.bindings = null;
  17682. /**
  17683. * Internal cache for maintaining pipelines.
  17684. * The key of the map is a cache key, the value the pipeline.
  17685. *
  17686. * @type {Map<String,Pipeline>}
  17687. */
  17688. this.caches = new Map();
  17689. /**
  17690. * This dictionary maintains for each shader stage type (vertex,
  17691. * fragment and compute) the programmable stage objects which
  17692. * represent the actual shader code.
  17693. *
  17694. * @type {Object<String,Map>}
  17695. */
  17696. this.programs = {
  17697. vertex: new Map(),
  17698. fragment: new Map(),
  17699. compute: new Map()
  17700. };
  17701. }
  17702. /**
  17703. * Returns a compute pipeline for the given compute node.
  17704. *
  17705. * @param {Node} computeNode - The compute node.
  17706. * @param {Array<BindGroup>} bindings - The bindings.
  17707. * @return {ComputePipeline} The compute pipeline.
  17708. */
  17709. getForCompute( computeNode, bindings ) {
  17710. const { backend } = this;
  17711. const data = this.get( computeNode );
  17712. if ( this._needsComputeUpdate( computeNode ) ) {
  17713. const previousPipeline = data.pipeline;
  17714. if ( previousPipeline ) {
  17715. previousPipeline.usedTimes --;
  17716. previousPipeline.computeProgram.usedTimes --;
  17717. }
  17718. // get shader
  17719. const nodeBuilderState = this.nodes.getForCompute( computeNode );
  17720. // programmable stage
  17721. let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader );
  17722. if ( stageCompute === undefined ) {
  17723. if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram );
  17724. stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', computeNode.name, nodeBuilderState.transforms, nodeBuilderState.nodeAttributes );
  17725. this.programs.compute.set( nodeBuilderState.computeShader, stageCompute );
  17726. backend.createProgram( stageCompute );
  17727. }
  17728. // determine compute pipeline
  17729. const cacheKey = this._getComputeCacheKey( computeNode, stageCompute );
  17730. let pipeline = this.caches.get( cacheKey );
  17731. if ( pipeline === undefined ) {
  17732. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  17733. pipeline = this._getComputePipeline( computeNode, stageCompute, cacheKey, bindings );
  17734. }
  17735. // keep track of all used times
  17736. pipeline.usedTimes ++;
  17737. stageCompute.usedTimes ++;
  17738. //
  17739. data.version = computeNode.version;
  17740. data.pipeline = pipeline;
  17741. }
  17742. return data.pipeline;
  17743. }
  17744. /**
  17745. * Returns a render pipeline for the given render object.
  17746. *
  17747. * @param {RenderObject} renderObject - The render object.
  17748. * @param {Array<Promise>?} [promises=null] - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  17749. * @return {RenderPipeline} The render pipeline.
  17750. */
  17751. getForRender( renderObject, promises = null ) {
  17752. const { backend } = this;
  17753. const data = this.get( renderObject );
  17754. if ( this._needsRenderUpdate( renderObject ) ) {
  17755. const previousPipeline = data.pipeline;
  17756. if ( previousPipeline ) {
  17757. previousPipeline.usedTimes --;
  17758. previousPipeline.vertexProgram.usedTimes --;
  17759. previousPipeline.fragmentProgram.usedTimes --;
  17760. }
  17761. // get shader
  17762. const nodeBuilderState = renderObject.getNodeBuilderState();
  17763. const name = renderObject.material ? renderObject.material.name : '';
  17764. // programmable stages
  17765. let stageVertex = this.programs.vertex.get( nodeBuilderState.vertexShader );
  17766. if ( stageVertex === undefined ) {
  17767. if ( previousPipeline && previousPipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.vertexProgram );
  17768. stageVertex = new ProgrammableStage( nodeBuilderState.vertexShader, 'vertex', name );
  17769. this.programs.vertex.set( nodeBuilderState.vertexShader, stageVertex );
  17770. backend.createProgram( stageVertex );
  17771. }
  17772. let stageFragment = this.programs.fragment.get( nodeBuilderState.fragmentShader );
  17773. if ( stageFragment === undefined ) {
  17774. if ( previousPipeline && previousPipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.fragmentProgram );
  17775. stageFragment = new ProgrammableStage( nodeBuilderState.fragmentShader, 'fragment', name );
  17776. this.programs.fragment.set( nodeBuilderState.fragmentShader, stageFragment );
  17777. backend.createProgram( stageFragment );
  17778. }
  17779. // determine render pipeline
  17780. const cacheKey = this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  17781. let pipeline = this.caches.get( cacheKey );
  17782. if ( pipeline === undefined ) {
  17783. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  17784. pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises );
  17785. } else {
  17786. renderObject.pipeline = pipeline;
  17787. }
  17788. // keep track of all used times
  17789. pipeline.usedTimes ++;
  17790. stageVertex.usedTimes ++;
  17791. stageFragment.usedTimes ++;
  17792. //
  17793. data.pipeline = pipeline;
  17794. }
  17795. return data.pipeline;
  17796. }
  17797. /**
  17798. * Deletes the pipeline for the given render object.
  17799. *
  17800. * @param {RenderObject} object - The render object.
  17801. * @return {Object?} The deleted dictionary.
  17802. */
  17803. delete( object ) {
  17804. const pipeline = this.get( object ).pipeline;
  17805. if ( pipeline ) {
  17806. // pipeline
  17807. pipeline.usedTimes --;
  17808. if ( pipeline.usedTimes === 0 ) this._releasePipeline( pipeline );
  17809. // programs
  17810. if ( pipeline.isComputePipeline ) {
  17811. pipeline.computeProgram.usedTimes --;
  17812. if ( pipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( pipeline.computeProgram );
  17813. } else {
  17814. pipeline.fragmentProgram.usedTimes --;
  17815. pipeline.vertexProgram.usedTimes --;
  17816. if ( pipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( pipeline.vertexProgram );
  17817. if ( pipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( pipeline.fragmentProgram );
  17818. }
  17819. }
  17820. return super.delete( object );
  17821. }
  17822. /**
  17823. * Frees internal resources.
  17824. */
  17825. dispose() {
  17826. super.dispose();
  17827. this.caches = new Map();
  17828. this.programs = {
  17829. vertex: new Map(),
  17830. fragment: new Map(),
  17831. compute: new Map()
  17832. };
  17833. }
  17834. /**
  17835. * Updates the pipeline for the given render object.
  17836. *
  17837. * @param {RenderObject} renderObject - The render object.
  17838. */
  17839. updateForRender( renderObject ) {
  17840. this.getForRender( renderObject );
  17841. }
  17842. /**
  17843. * Returns a compute pipeline for the given parameters.
  17844. *
  17845. * @private
  17846. * @param {Node} computeNode - The compute node.
  17847. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  17848. * @param {String} cacheKey - The cache key.
  17849. * @param {Array<BindGroup>} bindings - The bindings.
  17850. * @return {ComputePipeline} The compute pipeline.
  17851. */
  17852. _getComputePipeline( computeNode, stageCompute, cacheKey, bindings ) {
  17853. // check for existing pipeline
  17854. cacheKey = cacheKey || this._getComputeCacheKey( computeNode, stageCompute );
  17855. let pipeline = this.caches.get( cacheKey );
  17856. if ( pipeline === undefined ) {
  17857. pipeline = new ComputePipeline( cacheKey, stageCompute );
  17858. this.caches.set( cacheKey, pipeline );
  17859. this.backend.createComputePipeline( pipeline, bindings );
  17860. }
  17861. return pipeline;
  17862. }
  17863. /**
  17864. * Returns a render pipeline for the given parameters.
  17865. *
  17866. * @private
  17867. * @param {RenderObject} renderObject - The render object.
  17868. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  17869. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  17870. * @param {String} cacheKey - The cache key.
  17871. * @param {Array<Promise>?} promises - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  17872. * @return {ComputePipeline} The compute pipeline.
  17873. */
  17874. _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) {
  17875. // check for existing pipeline
  17876. cacheKey = cacheKey || this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  17877. let pipeline = this.caches.get( cacheKey );
  17878. if ( pipeline === undefined ) {
  17879. pipeline = new RenderPipeline( cacheKey, stageVertex, stageFragment );
  17880. this.caches.set( cacheKey, pipeline );
  17881. renderObject.pipeline = pipeline;
  17882. // The `promises` array is `null` by default and only set to an empty array when
  17883. // `Renderer.compileAsync()` is used. The next call actually fills the array with
  17884. // pending promises that resolve when the render pipelines are ready for rendering.
  17885. this.backend.createRenderPipeline( renderObject, promises );
  17886. }
  17887. return pipeline;
  17888. }
  17889. /**
  17890. * Computes a cache key representing a compute pipeline.
  17891. *
  17892. * @private
  17893. * @param {Node} computeNode - The compute node.
  17894. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  17895. * @return {String} The cache key.
  17896. */
  17897. _getComputeCacheKey( computeNode, stageCompute ) {
  17898. return computeNode.id + ',' + stageCompute.id;
  17899. }
  17900. /**
  17901. * Computes a cache key representing a render pipeline.
  17902. *
  17903. * @private
  17904. * @param {RenderObject} renderObject - The render object.
  17905. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  17906. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  17907. * @return {String} The cache key.
  17908. */
  17909. _getRenderCacheKey( renderObject, stageVertex, stageFragment ) {
  17910. return stageVertex.id + ',' + stageFragment.id + ',' + this.backend.getRenderCacheKey( renderObject );
  17911. }
  17912. /**
  17913. * Releases the given pipeline.
  17914. *
  17915. * @private
  17916. * @param {Pipeline} pipeline - The pipeline to release.
  17917. */
  17918. _releasePipeline( pipeline ) {
  17919. this.caches.delete( pipeline.cacheKey );
  17920. }
  17921. /**
  17922. * Releases the shader program.
  17923. *
  17924. * @private
  17925. * @param {Object} program - The shader program to release.
  17926. */
  17927. _releaseProgram( program ) {
  17928. const code = program.code;
  17929. const stage = program.stage;
  17930. this.programs[ stage ].delete( code );
  17931. }
  17932. /**
  17933. * Returns `true` if the compute pipeline for the given compute node requires an update.
  17934. *
  17935. * @private
  17936. * @param {Node} computeNode - The compute node.
  17937. * @return {Boolean} Whether the compute pipeline for the given compute node requires an update or not.
  17938. */
  17939. _needsComputeUpdate( computeNode ) {
  17940. const data = this.get( computeNode );
  17941. return data.pipeline === undefined || data.version !== computeNode.version;
  17942. }
  17943. /**
  17944. * Returns `true` if the render pipeline for the given render object requires an update.
  17945. *
  17946. * @private
  17947. * @param {RenderObject} renderObject - The render object.
  17948. * @return {Boolean} Whether the render object for the given render object requires an update or not.
  17949. */
  17950. _needsRenderUpdate( renderObject ) {
  17951. const data = this.get( renderObject );
  17952. return data.pipeline === undefined || this.backend.needsRenderUpdate( renderObject );
  17953. }
  17954. }
  17955. /**
  17956. * This renderer module manages the bindings of the renderer.
  17957. *
  17958. * @private
  17959. * @augments DataMap
  17960. */
  17961. class Bindings extends DataMap {
  17962. /**
  17963. * Constructs a new bindings management component.
  17964. *
  17965. * @param {Backend} backend - The renderer's backend.
  17966. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  17967. * @param {Textures} textures - Renderer component for managing textures.
  17968. * @param {Attributes} attributes - Renderer component for managing attributes.
  17969. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  17970. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  17971. */
  17972. constructor( backend, nodes, textures, attributes, pipelines, info ) {
  17973. super();
  17974. /**
  17975. * The renderer's backend.
  17976. *
  17977. * @type {Backend}
  17978. */
  17979. this.backend = backend;
  17980. /**
  17981. * Renderer component for managing textures.
  17982. *
  17983. * @type {Textures}
  17984. */
  17985. this.textures = textures;
  17986. /**
  17987. * Renderer component for managing pipelines.
  17988. *
  17989. * @type {Pipelines}
  17990. */
  17991. this.pipelines = pipelines;
  17992. /**
  17993. * Renderer component for managing attributes.
  17994. *
  17995. * @type {Attributes}
  17996. */
  17997. this.attributes = attributes;
  17998. /**
  17999. * Renderer component for managing nodes related logic.
  18000. *
  18001. * @type {Nodes}
  18002. */
  18003. this.nodes = nodes;
  18004. /**
  18005. * Renderer component for managing metrics and monitoring data.
  18006. *
  18007. * @type {Info}
  18008. */
  18009. this.info = info;
  18010. this.pipelines.bindings = this; // assign bindings to pipelines
  18011. }
  18012. /**
  18013. * Returns the bind groups for the given render object.
  18014. *
  18015. * @param {RenderObject} renderObject - The render object.
  18016. * @return {Array<BindGroup>} The bind groups.
  18017. */
  18018. getForRender( renderObject ) {
  18019. const bindings = renderObject.getBindings();
  18020. for ( const bindGroup of bindings ) {
  18021. const groupData = this.get( bindGroup );
  18022. if ( groupData.bindGroup === undefined ) {
  18023. // each object defines an array of bindings (ubos, textures, samplers etc.)
  18024. this._init( bindGroup );
  18025. this.backend.createBindings( bindGroup, bindings, 0 );
  18026. groupData.bindGroup = bindGroup;
  18027. }
  18028. }
  18029. return bindings;
  18030. }
  18031. /**
  18032. * Returns the bind groups for the given compute node.
  18033. *
  18034. * @param {Node} computeNode - The compute node.
  18035. * @return {Array<BindGroup>} The bind groups.
  18036. */
  18037. getForCompute( computeNode ) {
  18038. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  18039. for ( const bindGroup of bindings ) {
  18040. const groupData = this.get( bindGroup );
  18041. if ( groupData.bindGroup === undefined ) {
  18042. this._init( bindGroup );
  18043. this.backend.createBindings( bindGroup, bindings, 0 );
  18044. groupData.bindGroup = bindGroup;
  18045. }
  18046. }
  18047. return bindings;
  18048. }
  18049. /**
  18050. * Updates the bindings for the given compute node.
  18051. *
  18052. * @param {Node} computeNode - The compute node.
  18053. */
  18054. updateForCompute( computeNode ) {
  18055. this._updateBindings( this.getForCompute( computeNode ) );
  18056. }
  18057. /**
  18058. * Updates the bindings for the given render object.
  18059. *
  18060. * @param {RenderObject} renderObject - The render object.
  18061. */
  18062. updateForRender( renderObject ) {
  18063. this._updateBindings( this.getForRender( renderObject ) );
  18064. }
  18065. /**
  18066. * Updates the given array of bindings.
  18067. *
  18068. * @param {Array<BindGroup>} bindings - The bind groups.
  18069. */
  18070. _updateBindings( bindings ) {
  18071. for ( const bindGroup of bindings ) {
  18072. this._update( bindGroup, bindings );
  18073. }
  18074. }
  18075. /**
  18076. * Initializes the given bind group.
  18077. *
  18078. * @param {BindGroup} bindGroup - The bind group to initialize.
  18079. */
  18080. _init( bindGroup ) {
  18081. for ( const binding of bindGroup.bindings ) {
  18082. if ( binding.isSampledTexture ) {
  18083. this.textures.updateTexture( binding.texture );
  18084. } else if ( binding.isStorageBuffer ) {
  18085. const attribute = binding.attribute;
  18086. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  18087. this.attributes.update( attribute, attributeType );
  18088. }
  18089. }
  18090. }
  18091. /**
  18092. * Updates the given bind group.
  18093. *
  18094. * @param {BindGroup} bindGroup - The bind group to update.
  18095. * @param {Array<BindGroup>} bindings - The bind groups.
  18096. */
  18097. _update( bindGroup, bindings ) {
  18098. const { backend } = this;
  18099. let needsBindingsUpdate = false;
  18100. let cacheBindings = true;
  18101. let cacheIndex = 0;
  18102. let version = 0;
  18103. // iterate over all bindings and check if buffer updates or a new binding group is required
  18104. for ( const binding of bindGroup.bindings ) {
  18105. if ( binding.isNodeUniformsGroup ) {
  18106. const updated = this.nodes.updateGroup( binding );
  18107. // every uniforms group is a uniform buffer. So if no update is required,
  18108. // we move one with the next binding. Otherwise the next if block will update the group.
  18109. if ( updated === false ) continue;
  18110. }
  18111. if ( binding.isUniformBuffer ) {
  18112. const updated = binding.update();
  18113. if ( updated ) {
  18114. backend.updateBinding( binding );
  18115. }
  18116. } else if ( binding.isSampler ) {
  18117. binding.update();
  18118. } else if ( binding.isSampledTexture ) {
  18119. const texturesTextureData = this.textures.get( binding.texture );
  18120. if ( binding.needsBindingsUpdate( texturesTextureData.generation ) ) needsBindingsUpdate = true;
  18121. const updated = binding.update();
  18122. const texture = binding.texture;
  18123. if ( updated ) {
  18124. this.textures.updateTexture( texture );
  18125. }
  18126. const textureData = backend.get( texture );
  18127. if ( textureData.externalTexture !== undefined || texturesTextureData.isDefaultTexture ) {
  18128. cacheBindings = false;
  18129. } else {
  18130. cacheIndex = cacheIndex * 10 + texture.id;
  18131. version += texture.version;
  18132. }
  18133. if ( backend.isWebGPUBackend === true && textureData.texture === undefined && textureData.externalTexture === undefined ) {
  18134. // TODO: Remove this once we found why updated === false isn't bound to a texture in the WebGPU backend
  18135. console.error( 'Bindings._update: binding should be available:', binding, updated, texture, binding.textureNode.value, needsBindingsUpdate );
  18136. this.textures.updateTexture( texture );
  18137. needsBindingsUpdate = true;
  18138. }
  18139. if ( texture.isStorageTexture === true ) {
  18140. const textureData = this.get( texture );
  18141. if ( binding.store === true ) {
  18142. textureData.needsMipmap = true;
  18143. } else if ( this.textures.needsMipmaps( texture ) && textureData.needsMipmap === true ) {
  18144. this.backend.generateMipmaps( texture );
  18145. textureData.needsMipmap = false;
  18146. }
  18147. }
  18148. }
  18149. }
  18150. if ( needsBindingsUpdate === true ) {
  18151. this.backend.updateBindings( bindGroup, bindings, cacheBindings ? cacheIndex : 0, version );
  18152. }
  18153. }
  18154. }
  18155. /**
  18156. * Default sorting function for opaque render items.
  18157. *
  18158. * @private
  18159. * @function
  18160. * @param {Object} a - The first render item.
  18161. * @param {Object} b - The second render item.
  18162. * @return {Number} A numeric value which defines the sort order.
  18163. */
  18164. function painterSortStable( a, b ) {
  18165. if ( a.groupOrder !== b.groupOrder ) {
  18166. return a.groupOrder - b.groupOrder;
  18167. } else if ( a.renderOrder !== b.renderOrder ) {
  18168. return a.renderOrder - b.renderOrder;
  18169. } else if ( a.material.id !== b.material.id ) {
  18170. return a.material.id - b.material.id;
  18171. } else if ( a.z !== b.z ) {
  18172. return a.z - b.z;
  18173. } else {
  18174. return a.id - b.id;
  18175. }
  18176. }
  18177. /**
  18178. * Default sorting function for transparent render items.
  18179. *
  18180. * @private
  18181. * @function
  18182. * @param {Object} a - The first render item.
  18183. * @param {Object} b - The second render item.
  18184. * @return {Number} A numeric value which defines the sort order.
  18185. */
  18186. function reversePainterSortStable( a, b ) {
  18187. if ( a.groupOrder !== b.groupOrder ) {
  18188. return a.groupOrder - b.groupOrder;
  18189. } else if ( a.renderOrder !== b.renderOrder ) {
  18190. return a.renderOrder - b.renderOrder;
  18191. } else if ( a.z !== b.z ) {
  18192. return b.z - a.z;
  18193. } else {
  18194. return a.id - b.id;
  18195. }
  18196. }
  18197. /**
  18198. * Returns `true` if the given transparent material requires a double pass.
  18199. *
  18200. * @private
  18201. * @function
  18202. * @param {Material} material - The transparent material.
  18203. * @return {Boolean} Whether the given material requires a double pass or not.
  18204. */
  18205. function needsDoublePass( material ) {
  18206. const hasTransmission = material.transmission > 0 || material.transmissionNode;
  18207. return hasTransmission && material.side === DoubleSide && material.forceSinglePass === false;
  18208. }
  18209. /**
  18210. * When the renderer analyzes the scene at the beginning of a render call,
  18211. * it stores 3D object for further processing in render lists. Depending on the
  18212. * properties of a 3D objects (like their transformation or material state), the
  18213. * objects are maintained in ordered lists for the actual rendering.
  18214. *
  18215. * Render lists are unique per scene and camera combination.
  18216. *
  18217. * @private
  18218. * @augments Pipeline
  18219. */
  18220. class RenderList {
  18221. /**
  18222. * Constructs a render list.
  18223. *
  18224. * @param {Lighting} lighting - The lighting management component.
  18225. * @param {Scene} scene - The scene.
  18226. * @param {Camera} camera - The camera the scene is rendered with.
  18227. */
  18228. constructor( lighting, scene, camera ) {
  18229. /**
  18230. * 3D objects are transformed into render items and stored in this array.
  18231. *
  18232. * @type {Array<Object>}
  18233. */
  18234. this.renderItems = [];
  18235. /**
  18236. * The current render items index.
  18237. *
  18238. * @type {Number}
  18239. * @default 0
  18240. */
  18241. this.renderItemsIndex = 0;
  18242. /**
  18243. * A list with opaque render items.
  18244. *
  18245. * @type {Array<Object>}
  18246. */
  18247. this.opaque = [];
  18248. /**
  18249. * A list with transparent render items which require
  18250. * double pass rendering (e.g. transmissive objects).
  18251. *
  18252. * @type {Array<Object>}
  18253. */
  18254. this.transparentDoublePass = [];
  18255. /**
  18256. * A list with transparent render items.
  18257. *
  18258. * @type {Array<Object>}
  18259. */
  18260. this.transparent = [];
  18261. /**
  18262. * A list with transparent render bundle data.
  18263. *
  18264. * @type {Array<Object>}
  18265. */
  18266. this.bundles = [];
  18267. /**
  18268. * The render list's lights node. This node is later
  18269. * relevant for the actual analytical light nodes which
  18270. * compute the scene's lighting in the shader.
  18271. *
  18272. * @type {LightsNode}
  18273. */
  18274. this.lightsNode = lighting.getNode( scene, camera );
  18275. /**
  18276. * The scene's lights stored in an array. This array
  18277. * is used to setup the lights node.
  18278. *
  18279. * @type {Array<Light>}
  18280. */
  18281. this.lightsArray = [];
  18282. /**
  18283. * The scene.
  18284. *
  18285. * @type {Scene}
  18286. */
  18287. this.scene = scene;
  18288. /**
  18289. * The camera the scene is rendered with.
  18290. *
  18291. * @type {Camera}
  18292. */
  18293. this.camera = camera;
  18294. /**
  18295. * How many objects perform occlusion query tests.
  18296. *
  18297. * @type {Number}
  18298. * @default 0
  18299. */
  18300. this.occlusionQueryCount = 0;
  18301. }
  18302. /**
  18303. * This method is called right at the beginning of a render call
  18304. * before the scene is analyzed. It prepares the internal data
  18305. * structures for the upcoming render lists generation.
  18306. *
  18307. * @return {RenderList} A reference to this render list.
  18308. */
  18309. begin() {
  18310. this.renderItemsIndex = 0;
  18311. this.opaque.length = 0;
  18312. this.transparentDoublePass.length = 0;
  18313. this.transparent.length = 0;
  18314. this.bundles.length = 0;
  18315. this.lightsArray.length = 0;
  18316. this.occlusionQueryCount = 0;
  18317. return this;
  18318. }
  18319. /**
  18320. * Returns a render item for the giving render item state. The state is defined
  18321. * by a series of object-related parameters.
  18322. *
  18323. * The method avoids object creation by holding render items and reusing them in
  18324. * subsequent render calls (just with different property values).
  18325. *
  18326. * @param {Object3D} object - The 3D object.
  18327. * @param {BufferGeometry} geometry - The 3D object's geometry.
  18328. * @param {Material} material - The 3D object's material.
  18329. * @param {Number} groupOrder - The current group order.
  18330. * @param {Number} z - Th 3D object's depth value (z value in clip space).
  18331. * @param {Number?} group - {Object?} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  18332. * @param {ClippingContext} clippingContext - The current clipping context.
  18333. * @return {Object} The render item.
  18334. */
  18335. getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext ) {
  18336. let renderItem = this.renderItems[ this.renderItemsIndex ];
  18337. if ( renderItem === undefined ) {
  18338. renderItem = {
  18339. id: object.id,
  18340. object: object,
  18341. geometry: geometry,
  18342. material: material,
  18343. groupOrder: groupOrder,
  18344. renderOrder: object.renderOrder,
  18345. z: z,
  18346. group: group,
  18347. clippingContext: clippingContext
  18348. };
  18349. this.renderItems[ this.renderItemsIndex ] = renderItem;
  18350. } else {
  18351. renderItem.id = object.id;
  18352. renderItem.object = object;
  18353. renderItem.geometry = geometry;
  18354. renderItem.material = material;
  18355. renderItem.groupOrder = groupOrder;
  18356. renderItem.renderOrder = object.renderOrder;
  18357. renderItem.z = z;
  18358. renderItem.group = group;
  18359. renderItem.clippingContext = clippingContext;
  18360. }
  18361. this.renderItemsIndex ++;
  18362. return renderItem;
  18363. }
  18364. /**
  18365. * Pushes the given object as a render item to the internal render lists.
  18366. * The selected lists depend on the object properties.
  18367. *
  18368. * @param {Object3D} object - The 3D object.
  18369. * @param {BufferGeometry} geometry - The 3D object's geometry.
  18370. * @param {Material} material - The 3D object's material.
  18371. * @param {Number} groupOrder - The current group order.
  18372. * @param {Number} z - Th 3D object's depth value (z value in clip space).
  18373. * @param {Number?} group - {Object?} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  18374. * @param {ClippingContext} clippingContext - The current clipping context.
  18375. */
  18376. push( object, geometry, material, groupOrder, z, group, clippingContext ) {
  18377. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  18378. if ( object.occlusionTest === true ) this.occlusionQueryCount ++;
  18379. if ( material.transparent === true || material.transmission > 0 ) {
  18380. if ( needsDoublePass( material ) ) this.transparentDoublePass.push( renderItem );
  18381. this.transparent.push( renderItem );
  18382. } else {
  18383. this.opaque.push( renderItem );
  18384. }
  18385. }
  18386. /**
  18387. * Inserts the given object as a render item at the start of the internal render lists.
  18388. * The selected lists depend on the object properties.
  18389. *
  18390. * @param {Object3D} object - The 3D object.
  18391. * @param {BufferGeometry} geometry - The 3D object's geometry.
  18392. * @param {Material} material - The 3D object's material.
  18393. * @param {Number} groupOrder - The current group order.
  18394. * @param {Number} z - Th 3D object's depth value (z value in clip space).
  18395. * @param {Number?} group - {Object?} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  18396. * @param {ClippingContext} clippingContext - The current clipping context.
  18397. */
  18398. unshift( object, geometry, material, groupOrder, z, group, clippingContext ) {
  18399. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  18400. if ( material.transparent === true || material.transmission > 0 ) {
  18401. if ( needsDoublePass( material ) ) this.transparentDoublePass.unshift( renderItem );
  18402. this.transparent.unshift( renderItem );
  18403. } else {
  18404. this.opaque.unshift( renderItem );
  18405. }
  18406. }
  18407. /**
  18408. * Pushes render bundle group data into the render list.
  18409. *
  18410. * @param {Object} group - Bundle group data.
  18411. */
  18412. pushBundle( group ) {
  18413. this.bundles.push( group );
  18414. }
  18415. /**
  18416. * Pushes a light into the render list.
  18417. *
  18418. * @param {Light} light - The light.
  18419. */
  18420. pushLight( light ) {
  18421. this.lightsArray.push( light );
  18422. }
  18423. /**
  18424. * Sorts the internal render lists.
  18425. *
  18426. * @param {function(Any, Any): Number} customOpaqueSort - A custom sort function for opaque objects.
  18427. * @param {function(Any, Any): Number} customTransparentSort - A custom sort function for transparent objects.
  18428. */
  18429. sort( customOpaqueSort, customTransparentSort ) {
  18430. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  18431. if ( this.transparentDoublePass.length > 1 ) this.transparentDoublePass.sort( customTransparentSort || reversePainterSortStable );
  18432. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  18433. }
  18434. /**
  18435. * This method performs finalizing tasks right after the render lists
  18436. * have been generated.
  18437. */
  18438. finish() {
  18439. // update lights
  18440. this.lightsNode.setLights( this.lightsArray );
  18441. // Clear references from inactive renderItems in the list
  18442. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  18443. const renderItem = this.renderItems[ i ];
  18444. if ( renderItem.id === null ) break;
  18445. renderItem.id = null;
  18446. renderItem.object = null;
  18447. renderItem.geometry = null;
  18448. renderItem.material = null;
  18449. renderItem.groupOrder = null;
  18450. renderItem.renderOrder = null;
  18451. renderItem.z = null;
  18452. renderItem.group = null;
  18453. renderItem.clippingContext = null;
  18454. }
  18455. }
  18456. }
  18457. const _chainKeys$4 = [];
  18458. /**
  18459. * This renderer module manages the render lists which are unique
  18460. * per scene and camera combination.
  18461. *
  18462. * @private
  18463. */
  18464. class RenderLists {
  18465. /**
  18466. * Constructs a render lists management component.
  18467. *
  18468. * @param {Lighting} lighting - The lighting management component.
  18469. */
  18470. constructor( lighting ) {
  18471. /**
  18472. * The lighting management component.
  18473. *
  18474. * @type {Lighting}
  18475. */
  18476. this.lighting = lighting;
  18477. /**
  18478. * The internal chain map which holds the render lists.
  18479. *
  18480. * @type {ChainMap}
  18481. */
  18482. this.lists = new ChainMap();
  18483. }
  18484. /**
  18485. * Returns a render list for the given scene and camera.
  18486. *
  18487. * @param {Scene} scene - The scene.
  18488. * @param {Camera} camera - The camera.
  18489. * @return {RenderList} The render list.
  18490. */
  18491. get( scene, camera ) {
  18492. const lists = this.lists;
  18493. _chainKeys$4[ 0 ] = scene;
  18494. _chainKeys$4[ 1 ] = camera;
  18495. let list = lists.get( _chainKeys$4 );
  18496. if ( list === undefined ) {
  18497. list = new RenderList( this.lighting, scene, camera );
  18498. lists.set( _chainKeys$4, list );
  18499. }
  18500. _chainKeys$4.length = 0;
  18501. return list;
  18502. }
  18503. /**
  18504. * Frees all internal resources.
  18505. */
  18506. dispose() {
  18507. this.lists = new ChainMap();
  18508. }
  18509. }
  18510. let _id$7 = 0;
  18511. /**
  18512. * Any render or compute command is executed in a specific context that defines
  18513. * the state of the renderer and its backend. Typical examples for such context
  18514. * data are the current clear values or data from the active framebuffer. This
  18515. * module is used to represent these contexts as objects.
  18516. *
  18517. * @private
  18518. */
  18519. class RenderContext {
  18520. /**
  18521. * Constructs a new render context.
  18522. */
  18523. constructor() {
  18524. /**
  18525. * The context's ID.
  18526. *
  18527. * @type {Number}
  18528. */
  18529. this.id = _id$7 ++;
  18530. /**
  18531. * Whether the current active framebuffer has a color attachment.
  18532. *
  18533. * @type {Boolean}
  18534. * @default true
  18535. */
  18536. this.color = true;
  18537. /**
  18538. * Whether the color attachment should be cleared or not.
  18539. *
  18540. * @type {Boolean}
  18541. * @default true
  18542. */
  18543. this.clearColor = true;
  18544. /**
  18545. * The clear color value.
  18546. *
  18547. * @type {Object}
  18548. * @default true
  18549. */
  18550. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  18551. /**
  18552. * Whether the current active framebuffer has a depth attachment.
  18553. *
  18554. * @type {Boolean}
  18555. * @default true
  18556. */
  18557. this.depth = true;
  18558. /**
  18559. * Whether the depth attachment should be cleared or not.
  18560. *
  18561. * @type {Boolean}
  18562. * @default true
  18563. */
  18564. this.clearDepth = true;
  18565. /**
  18566. * The clear depth value.
  18567. *
  18568. * @type {Number}
  18569. * @default 1
  18570. */
  18571. this.clearDepthValue = 1;
  18572. /**
  18573. * Whether the current active framebuffer has a stencil attachment.
  18574. *
  18575. * @type {Boolean}
  18576. * @default false
  18577. */
  18578. this.stencil = false;
  18579. /**
  18580. * Whether the stencil attachment should be cleared or not.
  18581. *
  18582. * @type {Boolean}
  18583. * @default true
  18584. */
  18585. this.clearStencil = true;
  18586. /**
  18587. * The clear stencil value.
  18588. *
  18589. * @type {Number}
  18590. * @default 1
  18591. */
  18592. this.clearStencilValue = 1;
  18593. /**
  18594. * By default the viewport encloses the entire framebuffer If a smaller
  18595. * viewport is manually defined, this property is to `true` by the renderer.
  18596. *
  18597. * @type {Boolean}
  18598. * @default false
  18599. */
  18600. this.viewport = false;
  18601. /**
  18602. * The viewport value. This value is in physical pixels meaning it incorporates
  18603. * the renderer's pixel ratio. The viewport property of render targets or
  18604. * the renderer is in logical pixels.
  18605. *
  18606. * @type {Vector4}
  18607. */
  18608. this.viewportValue = new Vector4();
  18609. /**
  18610. * When the scissor test is active and scissor rectangle smaller than the
  18611. * framebuffers dimensions, this property is to `true` by the renderer.
  18612. *
  18613. * @type {Boolean}
  18614. * @default false
  18615. */
  18616. this.scissor = false;
  18617. /**
  18618. * The scissor rectangle.
  18619. *
  18620. * @type {Vector4}
  18621. */
  18622. this.scissorValue = new Vector4();
  18623. /**
  18624. * The active render target.
  18625. *
  18626. * @type {RenderTarget?}
  18627. * @default null
  18628. */
  18629. this.renderTarget = null;
  18630. /**
  18631. * The textures of the active render target.
  18632. * `null` when no render target is set.
  18633. *
  18634. * @type {Array<Texture>?}
  18635. * @default null
  18636. */
  18637. this.textures = null;
  18638. /**
  18639. * The depth texture of the active render target.
  18640. * `null` when no render target is set.
  18641. *
  18642. * @type {DepthTexture?}
  18643. * @default null
  18644. */
  18645. this.depthTexture = null;
  18646. /**
  18647. * The active cube face.
  18648. *
  18649. * @type {Number}
  18650. * @default 0
  18651. */
  18652. this.activeCubeFace = 0;
  18653. /**
  18654. * The active mipmap level.
  18655. *
  18656. * @type {Number}
  18657. * @default 0
  18658. */
  18659. this.activeMipmapLevel = 0;
  18660. /**
  18661. * The number of MSAA samples. This value is always `1` when
  18662. * MSAA isn't used.
  18663. *
  18664. * @type {Number}
  18665. * @default 1
  18666. */
  18667. this.sampleCount = 1;
  18668. /**
  18669. * The active render target's width in physical pixels.
  18670. *
  18671. * @type {Number}
  18672. * @default 0
  18673. */
  18674. this.width = 0;
  18675. /**
  18676. * The active render target's height in physical pixels.
  18677. *
  18678. * @type {Number}
  18679. * @default 0
  18680. */
  18681. this.height = 0;
  18682. /**
  18683. * The occlusion query count.
  18684. *
  18685. * @type {Number}
  18686. * @default 0
  18687. */
  18688. this.occlusionQueryCount = 0;
  18689. /**
  18690. * The current clipping context.
  18691. *
  18692. * @type {ClippingContext?}
  18693. * @default null
  18694. */
  18695. this.clippingContext = null;
  18696. /**
  18697. * This flag can be used for type testing.
  18698. *
  18699. * @type {Boolean}
  18700. * @readonly
  18701. * @default true
  18702. */
  18703. this.isRenderContext = true;
  18704. }
  18705. /**
  18706. * Returns the cache key of this render context.
  18707. *
  18708. * @return {Number} The cache key.
  18709. */
  18710. getCacheKey() {
  18711. return getCacheKey( this );
  18712. }
  18713. }
  18714. /**
  18715. * Computes a cache key for the given render context. This key
  18716. * should identify the render target state so it is possible to
  18717. * configure the correct attachments in the respective backend.
  18718. *
  18719. * @param {RenderContext} renderContext - The render context.
  18720. * @return {Number} The cache key.
  18721. */
  18722. function getCacheKey( renderContext ) {
  18723. const { textures, activeCubeFace } = renderContext;
  18724. const values = [ activeCubeFace ];
  18725. for ( const texture of textures ) {
  18726. values.push( texture.id );
  18727. }
  18728. return hashArray( values );
  18729. }
  18730. const _chainKeys$3 = [];
  18731. const _defaultScene = /*@__PURE__*/ new Scene();
  18732. const _defaultCamera = /*@__PURE__*/ new Camera();
  18733. /**
  18734. * This module manages the render contexts of the renderer.
  18735. *
  18736. * @private
  18737. */
  18738. class RenderContexts {
  18739. /**
  18740. * Constructs a new render context management component.
  18741. */
  18742. constructor() {
  18743. /**
  18744. * A dictionary that manages render contexts in chain maps
  18745. * for each attachment state.
  18746. *
  18747. * @type {Object<String,ChainMap>}
  18748. */
  18749. this.chainMaps = {};
  18750. }
  18751. /**
  18752. * Returns a render context for the given scene, camera and render target.
  18753. *
  18754. * @param {Scene} scene - The scene.
  18755. * @param {Camera} camera - The camera that is used to render the scene.
  18756. * @param {RenderTarget?} [renderTarget=null] - The active render target.
  18757. * @return {RenderContext} The render context.
  18758. */
  18759. get( scene, camera, renderTarget = null ) {
  18760. _chainKeys$3[ 0 ] = scene;
  18761. _chainKeys$3[ 1 ] = camera;
  18762. let attachmentState;
  18763. if ( renderTarget === null ) {
  18764. attachmentState = 'default';
  18765. } else {
  18766. const format = renderTarget.texture.format;
  18767. const count = renderTarget.textures.length;
  18768. attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  18769. }
  18770. const chainMap = this._getChainMap( attachmentState );
  18771. let renderState = chainMap.get( _chainKeys$3 );
  18772. if ( renderState === undefined ) {
  18773. renderState = new RenderContext();
  18774. chainMap.set( _chainKeys$3, renderState );
  18775. }
  18776. _chainKeys$3.length = 0;
  18777. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  18778. return renderState;
  18779. }
  18780. /**
  18781. * Returns a render context intended for clear operations.
  18782. *
  18783. * @param {RenderTarget?} [renderTarget=null] - The active render target.
  18784. * @return {RenderContext} The render context.
  18785. */
  18786. getForClear( renderTarget = null ) {
  18787. return this.get( _defaultScene, _defaultCamera, renderTarget );
  18788. }
  18789. /**
  18790. * Returns a chain map for the given attachment state.
  18791. *
  18792. * @private
  18793. * @param {String} attachmentState - The attachment state.
  18794. * @return {ChainMap} The chain map.
  18795. */
  18796. _getChainMap( attachmentState ) {
  18797. return this.chainMaps[ attachmentState ] || ( this.chainMaps[ attachmentState ] = new ChainMap() );
  18798. }
  18799. /**
  18800. * Frees internal resources.
  18801. */
  18802. dispose() {
  18803. this.chainMaps = {};
  18804. }
  18805. }
  18806. const _size$3 = /*@__PURE__*/ new Vector3();
  18807. /**
  18808. * This module manages the textures of the renderer.
  18809. *
  18810. * @private
  18811. * @augments DataMap
  18812. */
  18813. class Textures extends DataMap {
  18814. /**
  18815. * Constructs a new texture management component.
  18816. *
  18817. * @param {Renderer} renderer - The renderer.
  18818. * @param {Backend} backend - The renderer's backend.
  18819. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  18820. */
  18821. constructor( renderer, backend, info ) {
  18822. super();
  18823. /**
  18824. * The renderer.
  18825. *
  18826. * @type {Renderer}
  18827. */
  18828. this.renderer = renderer;
  18829. /**
  18830. * The backend.
  18831. *
  18832. * @type {Backend}
  18833. */
  18834. this.backend = backend;
  18835. /**
  18836. * Renderer component for managing metrics and monitoring data.
  18837. *
  18838. * @type {Info}
  18839. */
  18840. this.info = info;
  18841. }
  18842. /**
  18843. * Updates the given render target. Based on the given render target configuration,
  18844. * it updates the texture states representing the attachments of the framebuffer.
  18845. *
  18846. * @param {RenderTarget} renderTarget - The render target to update.
  18847. * @param {Number} [activeMipmapLevel=0] - The active mipmap level.
  18848. */
  18849. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  18850. const renderTargetData = this.get( renderTarget );
  18851. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  18852. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  18853. const textures = renderTarget.textures;
  18854. const size = this.getSize( textures[ 0 ] );
  18855. const mipWidth = size.width >> activeMipmapLevel;
  18856. const mipHeight = size.height >> activeMipmapLevel;
  18857. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  18858. const useDepthTexture = renderTarget.depthBuffer === true || renderTarget.stencilBuffer === true;
  18859. let textureNeedsUpdate = false;
  18860. if ( depthTexture === undefined && useDepthTexture ) {
  18861. depthTexture = new DepthTexture();
  18862. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  18863. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  18864. depthTexture.image.width = mipWidth;
  18865. depthTexture.image.height = mipHeight;
  18866. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  18867. }
  18868. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  18869. textureNeedsUpdate = true;
  18870. if ( depthTexture ) {
  18871. depthTexture.needsUpdate = true;
  18872. depthTexture.image.width = mipWidth;
  18873. depthTexture.image.height = mipHeight;
  18874. }
  18875. }
  18876. renderTargetData.width = size.width;
  18877. renderTargetData.height = size.height;
  18878. renderTargetData.textures = textures;
  18879. renderTargetData.depthTexture = depthTexture || null;
  18880. renderTargetData.depth = renderTarget.depthBuffer;
  18881. renderTargetData.stencil = renderTarget.stencilBuffer;
  18882. renderTargetData.renderTarget = renderTarget;
  18883. if ( renderTargetData.sampleCount !== sampleCount ) {
  18884. textureNeedsUpdate = true;
  18885. if ( depthTexture ) {
  18886. depthTexture.needsUpdate = true;
  18887. }
  18888. renderTargetData.sampleCount = sampleCount;
  18889. }
  18890. //
  18891. const options = { sampleCount };
  18892. // when using the WebXR Layers API, the render target uses external textures which
  18893. // require no manual updates
  18894. if ( renderTarget.isXRRenderTarget === true && renderTarget.hasExternalTextures === true ) {
  18895. if ( depthTexture && renderTarget.autoAllocateDepthBuffer === true ) {
  18896. this.updateTexture( depthTexture, options );
  18897. }
  18898. } else {
  18899. for ( let i = 0; i < textures.length; i ++ ) {
  18900. const texture = textures[ i ];
  18901. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  18902. this.updateTexture( texture, options );
  18903. }
  18904. if ( depthTexture ) {
  18905. this.updateTexture( depthTexture, options );
  18906. }
  18907. }
  18908. // dispose handler
  18909. if ( renderTargetData.initialized !== true ) {
  18910. renderTargetData.initialized = true;
  18911. // dispose
  18912. const onDispose = () => {
  18913. renderTarget.removeEventListener( 'dispose', onDispose );
  18914. for ( let i = 0; i < textures.length; i ++ ) {
  18915. this._destroyTexture( textures[ i ] );
  18916. }
  18917. if ( depthTexture ) {
  18918. this._destroyTexture( depthTexture );
  18919. }
  18920. this.delete( renderTarget );
  18921. };
  18922. renderTarget.addEventListener( 'dispose', onDispose );
  18923. }
  18924. }
  18925. /**
  18926. * Updates the given texture. Depending on the texture state, this method
  18927. * triggers the upload of texture data to the GPU memory. If the texture data are
  18928. * not yet ready for the upload, it uses default texture data for as a placeholder.
  18929. *
  18930. * @param {Texture} texture - The texture to update.
  18931. * @param {Object} [options={}] - The options.
  18932. */
  18933. updateTexture( texture, options = {} ) {
  18934. const textureData = this.get( texture );
  18935. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  18936. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  18937. const backend = this.backend;
  18938. if ( isRenderTarget && textureData.initialized === true ) {
  18939. // it's an update
  18940. backend.destroySampler( texture );
  18941. backend.destroyTexture( texture );
  18942. }
  18943. //
  18944. if ( texture.isFramebufferTexture ) {
  18945. const renderTarget = this.renderer.getRenderTarget();
  18946. if ( renderTarget ) {
  18947. texture.type = renderTarget.texture.type;
  18948. } else {
  18949. texture.type = UnsignedByteType;
  18950. }
  18951. }
  18952. //
  18953. const { width, height, depth } = this.getSize( texture );
  18954. options.width = width;
  18955. options.height = height;
  18956. options.depth = depth;
  18957. options.needsMipmaps = this.needsMipmaps( texture );
  18958. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  18959. //
  18960. if ( isRenderTarget || texture.isStorageTexture === true ) {
  18961. backend.createSampler( texture );
  18962. backend.createTexture( texture, options );
  18963. textureData.generation = texture.version;
  18964. } else {
  18965. const needsCreate = textureData.initialized !== true;
  18966. if ( needsCreate ) backend.createSampler( texture );
  18967. if ( texture.version > 0 ) {
  18968. const image = texture.image;
  18969. if ( image === undefined ) {
  18970. console.warn( 'THREE.Renderer: Texture marked for update but image is undefined.' );
  18971. } else if ( image.complete === false ) {
  18972. console.warn( 'THREE.Renderer: Texture marked for update but image is incomplete.' );
  18973. } else {
  18974. if ( texture.images ) {
  18975. const images = [];
  18976. for ( const image of texture.images ) {
  18977. images.push( image );
  18978. }
  18979. options.images = images;
  18980. } else {
  18981. options.image = image;
  18982. }
  18983. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  18984. backend.createTexture( texture, options );
  18985. textureData.isDefaultTexture = false;
  18986. textureData.generation = texture.version;
  18987. }
  18988. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  18989. if ( options.needsMipmaps && texture.mipmaps.length === 0 ) backend.generateMipmaps( texture );
  18990. }
  18991. } else {
  18992. // async update
  18993. backend.createDefaultTexture( texture );
  18994. textureData.isDefaultTexture = true;
  18995. textureData.generation = texture.version;
  18996. }
  18997. }
  18998. // dispose handler
  18999. if ( textureData.initialized !== true ) {
  19000. textureData.initialized = true;
  19001. textureData.generation = texture.version;
  19002. //
  19003. this.info.memory.textures ++;
  19004. // dispose
  19005. const onDispose = () => {
  19006. texture.removeEventListener( 'dispose', onDispose );
  19007. this._destroyTexture( texture );
  19008. this.info.memory.textures --;
  19009. };
  19010. texture.addEventListener( 'dispose', onDispose );
  19011. }
  19012. //
  19013. textureData.version = texture.version;
  19014. }
  19015. /**
  19016. * Computes the size of the given texture and writes the result
  19017. * into the target vector. This vector is also returned by the
  19018. * method.
  19019. *
  19020. * If no texture data are available for the compute yet, the method
  19021. * returns default size values.
  19022. *
  19023. * @param {Texture} texture - The texture to compute the size for.
  19024. * @param {Vector3} target - The target vector.
  19025. * @return {Vector3} The target vector.
  19026. */
  19027. getSize( texture, target = _size$3 ) {
  19028. let image = texture.images ? texture.images[ 0 ] : texture.image;
  19029. if ( image ) {
  19030. if ( image.image !== undefined ) image = image.image;
  19031. target.width = image.width || 1;
  19032. target.height = image.height || 1;
  19033. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  19034. } else {
  19035. target.width = target.height = target.depth = 1;
  19036. }
  19037. return target;
  19038. }
  19039. /**
  19040. * Computes the number of mipmap levels for the given texture.
  19041. *
  19042. * @param {Texture} texture - The texture.
  19043. * @param {Number} width - The texture's width.
  19044. * @param {Number} height - The texture's height.
  19045. * @return {Number} The number of mipmap levels.
  19046. */
  19047. getMipLevels( texture, width, height ) {
  19048. let mipLevelCount;
  19049. if ( texture.isCompressedTexture ) {
  19050. if ( texture.mipmaps ) {
  19051. mipLevelCount = texture.mipmaps.length;
  19052. } else {
  19053. mipLevelCount = 1;
  19054. }
  19055. } else {
  19056. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  19057. }
  19058. return mipLevelCount;
  19059. }
  19060. /**
  19061. * Returns `true` if the given texture requires mipmaps.
  19062. *
  19063. * @param {Texture} texture - The texture.
  19064. * @return {Boolean} Whether mipmaps are required or not.
  19065. */
  19066. needsMipmaps( texture ) {
  19067. return this.isEnvironmentTexture( texture ) || texture.isCompressedTexture === true || texture.generateMipmaps;
  19068. }
  19069. /**
  19070. * Returns `true` if the given texture is an environment map.
  19071. *
  19072. * @param {Texture} texture - The texture.
  19073. * @return {Boolean} Whether the given texture is an environment map or not.
  19074. */
  19075. isEnvironmentTexture( texture ) {
  19076. const mapping = texture.mapping;
  19077. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  19078. }
  19079. /**
  19080. * Frees internal resource when the given texture isn't
  19081. * required anymore.
  19082. *
  19083. * @param {Texture} texture - The texture to destroy.
  19084. */
  19085. _destroyTexture( texture ) {
  19086. this.backend.destroySampler( texture );
  19087. this.backend.destroyTexture( texture );
  19088. this.delete( texture );
  19089. }
  19090. }
  19091. /**
  19092. * A four-component version of {@link Color} which is internally
  19093. * used by the renderer to represents clear color with alpha as
  19094. * one object.
  19095. *
  19096. * @private
  19097. * @augments Color
  19098. */
  19099. class Color4 extends Color {
  19100. /**
  19101. * Constructs a new four-component color.
  19102. * You can also pass a single THREE.Color, hex or
  19103. * string argument to this constructor.
  19104. *
  19105. * @param {Number|String} [r=1] - The red value.
  19106. * @param {Number} [g=1] - The green value.
  19107. * @param {Number} [b=1] - The blue value.
  19108. * @param {Number} [a=1] - The alpha value.
  19109. */
  19110. constructor( r, g, b, a = 1 ) {
  19111. super( r, g, b );
  19112. this.a = a;
  19113. }
  19114. /**
  19115. * Overwrites the default to honor alpha.
  19116. * You can also pass a single THREE.Color, hex or
  19117. * string argument to this method.
  19118. *
  19119. * @param {Number|String} r - The red value.
  19120. * @param {Number} g - The green value.
  19121. * @param {Number} b - The blue value.
  19122. * @param {Number} [a=1] - The alpha value.
  19123. * @return {Color4} A reference to this object.
  19124. */
  19125. set( r, g, b, a = 1 ) {
  19126. this.a = a;
  19127. return super.set( r, g, b );
  19128. }
  19129. /**
  19130. * Overwrites the default to honor alpha.
  19131. *
  19132. * @param {Color4} color - The color to copy.
  19133. * @return {Color4} A reference to this object.
  19134. */
  19135. copy( color ) {
  19136. if ( color.a !== undefined ) this.a = color.a;
  19137. return super.copy( color );
  19138. }
  19139. /**
  19140. * Overwrites the default to honor alpha.
  19141. *
  19142. * @return {Color4} The cloned color.
  19143. */
  19144. clone() {
  19145. return new this.constructor( this.r, this.g, this.b, this.a );
  19146. }
  19147. }
  19148. /** @module ParameterNode **/
  19149. /**
  19150. * Special version of {@link PropertyNode} which is used for parameters.
  19151. *
  19152. * @augments PropertyNode
  19153. */
  19154. class ParameterNode extends PropertyNode {
  19155. static get type() {
  19156. return 'ParameterNode';
  19157. }
  19158. /**
  19159. * Constructs a new parameter node.
  19160. *
  19161. * @param {String} nodeType - The type of the node.
  19162. * @param {String?} [name=null] - The name of the parameter in the shader.
  19163. */
  19164. constructor( nodeType, name = null ) {
  19165. super( nodeType, name );
  19166. /**
  19167. * This flag can be used for type testing.
  19168. *
  19169. * @type {Boolean}
  19170. * @readonly
  19171. * @default true
  19172. */
  19173. this.isParameterNode = true;
  19174. }
  19175. getHash() {
  19176. return this.uuid;
  19177. }
  19178. generate() {
  19179. return this.name;
  19180. }
  19181. }
  19182. /**
  19183. * TSL function for creating a parameter node.
  19184. *
  19185. * @function
  19186. * @param {String} type - The type of the node.
  19187. * @param {String?} name - The name of the parameter in the shader.
  19188. * @returns {ParameterNode}
  19189. */
  19190. const parameter = ( type, name ) => nodeObject( new ParameterNode( type, name ) );
  19191. /** @module StackNode **/
  19192. /**
  19193. * Stack is a helper for Nodes that need to produce stack-based code instead of continuous flow.
  19194. * They are usually needed in cases like `If`, `Else`.
  19195. *
  19196. * @augments Node
  19197. */
  19198. class StackNode extends Node {
  19199. static get type() {
  19200. return 'StackNode';
  19201. }
  19202. /**
  19203. * Constructs a new stack node.
  19204. *
  19205. * @param {StackNode?} [parent=null] - The parent stack node.
  19206. */
  19207. constructor( parent = null ) {
  19208. super();
  19209. /**
  19210. * List of nodes.
  19211. *
  19212. * @type {Array<Node>}
  19213. */
  19214. this.nodes = [];
  19215. /**
  19216. * The output node.
  19217. *
  19218. * @type {Node?}
  19219. * @default null
  19220. */
  19221. this.outputNode = null;
  19222. /**
  19223. * The parent stack node.
  19224. *
  19225. * @type {StackNode}
  19226. * @default null
  19227. */
  19228. this.parent = parent;
  19229. /**
  19230. * The current conditional node.
  19231. *
  19232. * @private
  19233. * @type {ConditionalNode}
  19234. * @default null
  19235. */
  19236. this._currentCond = null;
  19237. /**
  19238. * This flag can be used for type testing.
  19239. *
  19240. * @type {Boolean}
  19241. * @readonly
  19242. * @default true
  19243. */
  19244. this.isStackNode = true;
  19245. }
  19246. getNodeType( builder ) {
  19247. return this.outputNode ? this.outputNode.getNodeType( builder ) : 'void';
  19248. }
  19249. /**
  19250. * Adds a node to this stack.
  19251. *
  19252. * @param {Node} node - The node to add.
  19253. * @return {StackNode} A reference to this stack node.
  19254. */
  19255. add( node ) {
  19256. this.nodes.push( node );
  19257. return this;
  19258. }
  19259. /**
  19260. * Represent an `if` statement in TSL.
  19261. *
  19262. * @param {Node} boolNode - Represents the condition.
  19263. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  19264. * @return {StackNode} A reference to this stack node.
  19265. */
  19266. If( boolNode, method ) {
  19267. const methodNode = new ShaderNode( method );
  19268. this._currentCond = select( boolNode, methodNode );
  19269. return this.add( this._currentCond );
  19270. }
  19271. /**
  19272. * Represent an `elseif` statement in TSL.
  19273. *
  19274. * @param {Node} boolNode - Represents the condition.
  19275. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  19276. * @return {StackNode} A reference to this stack node.
  19277. */
  19278. ElseIf( boolNode, method ) {
  19279. const methodNode = new ShaderNode( method );
  19280. const ifNode = select( boolNode, methodNode );
  19281. this._currentCond.elseNode = ifNode;
  19282. this._currentCond = ifNode;
  19283. return this;
  19284. }
  19285. /**
  19286. * Represent an `else` statement in TSL.
  19287. *
  19288. * @param {Function} method - TSL code which is executed in the `else` case.
  19289. * @return {StackNode} A reference to this stack node.
  19290. */
  19291. Else( method ) {
  19292. this._currentCond.elseNode = new ShaderNode( method );
  19293. return this;
  19294. }
  19295. build( builder, ...params ) {
  19296. const previousStack = getCurrentStack();
  19297. setCurrentStack( this );
  19298. for ( const node of this.nodes ) {
  19299. node.build( builder, 'void' );
  19300. }
  19301. setCurrentStack( previousStack );
  19302. return this.outputNode ? this.outputNode.build( builder, ...params ) : super.build( builder, ...params );
  19303. }
  19304. // Deprecated
  19305. /**
  19306. * @function
  19307. * @deprecated since r168. Use {@link StackNode#Else} instead.
  19308. *
  19309. * @param {...any} params
  19310. * @returns {StackNode}
  19311. */
  19312. else( ...params ) { // @deprecated, r168
  19313. console.warn( 'TSL.StackNode: .else() has been renamed to .Else().' );
  19314. return this.Else( ...params );
  19315. }
  19316. /**
  19317. * @deprecated since r168. Use {@link StackNode#ElseIf} instead.
  19318. *
  19319. * @param {...any} params
  19320. * @returns {StackNode}
  19321. */
  19322. elseif( ...params ) { // @deprecated, r168
  19323. console.warn( 'TSL.StackNode: .elseif() has been renamed to .ElseIf().' );
  19324. return this.ElseIf( ...params );
  19325. }
  19326. }
  19327. /**
  19328. * TSL function for creating a stack node.
  19329. *
  19330. * @function
  19331. * @param {StackNode?} [parent=null] - The parent stack node.
  19332. * @returns {StackNode}
  19333. */
  19334. const stack = /*@__PURE__*/ nodeProxy( StackNode );
  19335. /** @module OutputStructNode **/
  19336. /**
  19337. * This node can be used to define multiple outputs in a shader programs.
  19338. *
  19339. * @augments Node
  19340. */
  19341. class OutputStructNode extends Node {
  19342. static get type() {
  19343. return 'OutputStructNode';
  19344. }
  19345. /**
  19346. * Constructs a new output struct node. The constructor can be invoked with an
  19347. * arbitrary number of nodes representing the members.
  19348. *
  19349. * @param {...Node} members - A parameter list of nodes.
  19350. */
  19351. constructor( ...members ) {
  19352. super();
  19353. /**
  19354. * An array of nodes which defines the output.
  19355. *
  19356. * @type {Array<Node>}
  19357. */
  19358. this.members = members;
  19359. /**
  19360. * This flag can be used for type testing.
  19361. *
  19362. * @type {Boolean}
  19363. * @readonly
  19364. * @default true
  19365. */
  19366. this.isOutputStructNode = true;
  19367. }
  19368. setup( builder ) {
  19369. super.setup( builder );
  19370. const members = this.members;
  19371. const types = [];
  19372. for ( let i = 0; i < members.length; i ++ ) {
  19373. types.push( members[ i ].getNodeType( builder ) );
  19374. }
  19375. this.nodeType = builder.getStructTypeFromNode( this, types ).name;
  19376. }
  19377. generate( builder, output ) {
  19378. const propertyName = builder.getOutputStructName();
  19379. const members = this.members;
  19380. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  19381. for ( let i = 0; i < members.length; i ++ ) {
  19382. const snippet = members[ i ].build( builder, output );
  19383. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }`, this );
  19384. }
  19385. return propertyName;
  19386. }
  19387. }
  19388. /**
  19389. * TSL function for creating an output struct node.
  19390. *
  19391. * @function
  19392. * @param {...Node} members - A parameter list of nodes.
  19393. * @returns {OutputStructNode}
  19394. */
  19395. const outputStruct = /*@__PURE__*/ nodeProxy( OutputStructNode );
  19396. /** @module MRTNode **/
  19397. /**
  19398. * Returns the MRT texture index for the given name.
  19399. *
  19400. * @param {Array<Texture>} textures - The textures of a MRT-configured render target.
  19401. * @param {String} name - The name of the MRT texture which index is requested.
  19402. * @return {Number} The texture index.
  19403. */
  19404. function getTextureIndex( textures, name ) {
  19405. for ( let i = 0; i < textures.length; i ++ ) {
  19406. if ( textures[ i ].name === name ) {
  19407. return i;
  19408. }
  19409. }
  19410. return -1;
  19411. }
  19412. /**
  19413. * This node can be used setup a MRT context for rendering. A typical MRT setup for
  19414. * post-processing is shown below:
  19415. * ```js
  19416. * const mrtNode = mrt( {
  19417. * output: output,
  19418. * normal: normalView
  19419. * } ) );
  19420. * ```
  19421. * The MRT output is defined as a dictionary.
  19422. *
  19423. * @augments OutputStructNode
  19424. */
  19425. class MRTNode extends OutputStructNode {
  19426. static get type() {
  19427. return 'MRTNode';
  19428. }
  19429. /**
  19430. * Constructs a new output struct node.
  19431. *
  19432. * @param {Object<String, Node>} outputNodes - The MRT outputs.
  19433. */
  19434. constructor( outputNodes ) {
  19435. super();
  19436. /**
  19437. * A dictionary representing the MRT outputs. The key
  19438. * is the name of the output, the value the node which produces
  19439. * the output result.
  19440. *
  19441. * @type {Object<String, Node>}
  19442. */
  19443. this.outputNodes = outputNodes;
  19444. /**
  19445. * This flag can be used for type testing.
  19446. *
  19447. * @type {Boolean}
  19448. * @readonly
  19449. * @default true
  19450. */
  19451. this.isMRTNode = true;
  19452. }
  19453. /**
  19454. * Returns `true` if the MRT node has an output with the given name.
  19455. *
  19456. * @param {String} name - The name of the output.
  19457. * @return {NodeBuilder} Whether the MRT node has an output for the given name or not.
  19458. */
  19459. has( name ) {
  19460. return this.outputNodes[ name ] !== undefined;
  19461. }
  19462. /**
  19463. * Returns the output node for the given name.
  19464. *
  19465. * @param {String} name - The name of the output.
  19466. * @return {Node} The output node.
  19467. */
  19468. get( name ) {
  19469. return this.outputNodes[ name ];
  19470. }
  19471. /**
  19472. * Merges the outputs of the given MRT node with the outputs of this node.
  19473. *
  19474. * @param {MRTNode} mrtNode - The MRT to merge.
  19475. * @return {MRTNode} A new MRT node with merged outputs..
  19476. */
  19477. merge( mrtNode ) {
  19478. const outputs = { ...this.outputNodes, ...mrtNode.outputNodes };
  19479. return mrt( outputs );
  19480. }
  19481. setup( builder ) {
  19482. const outputNodes = this.outputNodes;
  19483. const mrt = builder.renderer.getRenderTarget();
  19484. const members = [];
  19485. const textures = mrt.textures;
  19486. for ( const name in outputNodes ) {
  19487. const index = getTextureIndex( textures, name );
  19488. members[ index ] = vec4( outputNodes[ name ] );
  19489. }
  19490. this.members = members;
  19491. return super.setup( builder );
  19492. }
  19493. }
  19494. /**
  19495. * TSL function for creating a MRT node.
  19496. *
  19497. * @function
  19498. * @param {Object<String, Node>} outputNodes - The MRT outputs.
  19499. * @returns {MRTNode}
  19500. */
  19501. const mrt = /*@__PURE__*/ nodeProxy( MRTNode );
  19502. /** @module Hash **/
  19503. /**
  19504. * Generates a hash value in the range `[0, 1]` from the given seed.
  19505. *
  19506. * @method
  19507. * @param {Node<float>} seed - The seed.
  19508. * @return {Node<float>} The hash value.
  19509. */
  19510. const hash = /*@__PURE__*/ Fn( ( [ seed ] ) => {
  19511. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  19512. const state = seed.toUint().mul( 747796405 ).add( 2891336453 );
  19513. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  19514. const result = word.shiftRight( 22 ).bitXor( word );
  19515. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  19516. } );
  19517. /** @module MathUtils **/
  19518. /**
  19519. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  19520. * The corners are mapped to `0` and the center to `1`.
  19521. * Reference: {@link https://iquilezles.org/articles/functions/}.
  19522. *
  19523. * @method
  19524. * @param {Node<float>} x - The value to remap.
  19525. * @param {Node<float>} k - Allows to control the remapping functions shape by rising the parabola to a power `k`.
  19526. * @return {Node<float>} The remapped value.
  19527. */
  19528. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  19529. /**
  19530. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  19531. * Expands the sides and compresses the center, and keeps `0.5` mapped to `0.5`.
  19532. * Reference: {@link https://iquilezles.org/articles/functions/}.
  19533. *
  19534. * @method
  19535. * @param {Node<float>} x - The value to remap.
  19536. * @param {Node<float>} k - `k=1` is the identity curve,`k<1` produces the classic `gain()` shape, and `k>1` produces "s" shaped curves.
  19537. * @return {Node<float>} The remapped value.
  19538. */
  19539. 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 ) );
  19540. /**
  19541. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  19542. * A generalization of the `parabola()`. Keeps the corners mapped to 0 but allows the control of the shape one either side of the curve.
  19543. * Reference: {@link https://iquilezles.org/articles/functions/}.
  19544. *
  19545. * @method
  19546. * @param {Node<float>} x - The value to remap.
  19547. * @param {Node<float>} a - First control parameter.
  19548. * @param {Node<float>} b - Second control parameter.
  19549. * @return {Node<float>} The remapped value.
  19550. */
  19551. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  19552. /**
  19553. * A phase shifted sinus curve that starts at zero and ends at zero, with bouncing behavior.
  19554. * Reference: {@link https://iquilezles.org/articles/functions/}.
  19555. *
  19556. * @method
  19557. * @param {Node<float>} x - The value to compute the sin for.
  19558. * @param {Node<float>} k - Controls the amount of bounces.
  19559. * @return {Node<float>} The result value.
  19560. */
  19561. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  19562. // https://github.com/cabbibo/glsl-tri-noise-3d
  19563. /** @module TriNoise3D **/
  19564. const tri = /*@__PURE__*/ Fn( ( [ x ] ) => {
  19565. return x.fract().sub( .5 ).abs();
  19566. } ).setLayout( {
  19567. name: 'tri',
  19568. type: 'float',
  19569. inputs: [
  19570. { name: 'x', type: 'float' }
  19571. ]
  19572. } );
  19573. const tri3 = /*@__PURE__*/ Fn( ( [ p ] ) => {
  19574. 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. ) ) ) ) );
  19575. } ).setLayout( {
  19576. name: 'tri3',
  19577. type: 'vec3',
  19578. inputs: [
  19579. { name: 'p', type: 'vec3' }
  19580. ]
  19581. } );
  19582. /**
  19583. * Generates a noise value from the given position, speed and time parameters.
  19584. *
  19585. * @method
  19586. * @param {Node<vec3>} position - The position.
  19587. * @param {Node<float>} speed - The speed.
  19588. * @param {Node<float>} time - The time.
  19589. * @return {Node<float>} The generated noise.
  19590. */
  19591. const triNoise3D = /*@__PURE__*/ Fn( ( [ position, speed, time ] ) => {
  19592. const p = vec3( position ).toVar();
  19593. const z = float( 1.4 ).toVar();
  19594. const rz = float( 0.0 ).toVar();
  19595. const bp = vec3( p ).toVar();
  19596. Loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  19597. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  19598. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( speed ) ) ) );
  19599. bp.mulAssign( 1.8 );
  19600. z.mulAssign( 1.5 );
  19601. p.mulAssign( 1.2 );
  19602. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  19603. rz.addAssign( t.div( z ) );
  19604. bp.addAssign( 0.14 );
  19605. } );
  19606. return rz;
  19607. } ).setLayout( {
  19608. name: 'triNoise3D',
  19609. type: 'float',
  19610. inputs: [
  19611. { name: 'position', type: 'vec3' },
  19612. { name: 'speed', type: 'float' },
  19613. { name: 'time', type: 'float' }
  19614. ]
  19615. } );
  19616. /** @module FunctionOverloadingNode **/
  19617. /**
  19618. * This class allows to define multiple overloaded versions
  19619. * of the same function. Depending on the parameters of the function
  19620. * call, the node picks the best-fit overloaded version.
  19621. *
  19622. * @augments Node
  19623. */
  19624. class FunctionOverloadingNode extends Node {
  19625. static get type() {
  19626. return 'FunctionOverloadingNode';
  19627. }
  19628. /**
  19629. * Constructs a new function overloading node.
  19630. *
  19631. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  19632. * @param {...Node} parametersNodes - A list of parameter nodes.
  19633. */
  19634. constructor( functionNodes = [], ...parametersNodes ) {
  19635. super();
  19636. /**
  19637. * Array of `Fn` function definitions.
  19638. *
  19639. * @type {Array<Function>}
  19640. */
  19641. this.functionNodes = functionNodes;
  19642. /**
  19643. * A list of parameter nodes.
  19644. *
  19645. * @type {Array<Node>}
  19646. */
  19647. this.parametersNodes = parametersNodes;
  19648. /**
  19649. * The selected overloaded function call.
  19650. *
  19651. * @private
  19652. * @type {ShaderCallNodeInternal}
  19653. */
  19654. this._candidateFnCall = null;
  19655. /**
  19656. * This node is marked as global.
  19657. *
  19658. * @type {Boolean}
  19659. * @default true
  19660. */
  19661. this.global = true;
  19662. }
  19663. /**
  19664. * This method is overwritten since the node type is inferred from
  19665. * the function's return type.
  19666. *
  19667. * @param {NodeBuilder} builder - The current node builder.
  19668. * @return {String} The node type.
  19669. */
  19670. getNodeType() {
  19671. return this.functionNodes[ 0 ].shaderNode.layout.type;
  19672. }
  19673. setup( builder ) {
  19674. const params = this.parametersNodes;
  19675. let candidateFnCall = this._candidateFnCall;
  19676. if ( candidateFnCall === null ) {
  19677. let candidateFn = null;
  19678. let candidateScore = -1;
  19679. for ( const functionNode of this.functionNodes ) {
  19680. const shaderNode = functionNode.shaderNode;
  19681. const layout = shaderNode.layout;
  19682. if ( layout === null ) {
  19683. throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' );
  19684. }
  19685. const inputs = layout.inputs;
  19686. if ( params.length === inputs.length ) {
  19687. let score = 0;
  19688. for ( let i = 0; i < params.length; i ++ ) {
  19689. const param = params[ i ];
  19690. const input = inputs[ i ];
  19691. if ( param.getNodeType( builder ) === input.type ) {
  19692. score ++;
  19693. } else {
  19694. score = 0;
  19695. }
  19696. }
  19697. if ( score > candidateScore ) {
  19698. candidateFn = functionNode;
  19699. candidateScore = score;
  19700. }
  19701. }
  19702. }
  19703. this._candidateFnCall = candidateFnCall = candidateFn( ...params );
  19704. }
  19705. return candidateFnCall;
  19706. }
  19707. }
  19708. const overloadingBaseFn = /*@__PURE__*/ nodeProxy( FunctionOverloadingNode );
  19709. /**
  19710. * TSL function for creating a function overloading node.
  19711. *
  19712. * @function
  19713. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  19714. * @returns {FunctionOverloadingNode}
  19715. */
  19716. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  19717. /** @module Timer **/
  19718. /**
  19719. * Represents the elapsed time in seconds.
  19720. *
  19721. * @type {UniformNode<float>}
  19722. */
  19723. const time = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.time );
  19724. /**
  19725. * Represents the delta time in seconds.
  19726. *
  19727. * @type {UniformNode<float>}
  19728. */
  19729. const deltaTime = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.deltaTime );
  19730. /**
  19731. * Represents the current frame ID.
  19732. *
  19733. * @type {UniformNode<uint>}
  19734. */
  19735. const frameId = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.frameId );
  19736. // Deprecated
  19737. /**
  19738. * @function
  19739. * @deprecated since r170. Use {@link time} instead.
  19740. *
  19741. * @param {Number} [timeScale=1] - The time scale.
  19742. * @returns {UniformNode<float>}
  19743. */
  19744. const timerLocal = ( timeScale = 1 ) => { // @deprecated, r170
  19745. console.warn( 'TSL: timerLocal() is deprecated. Use "time" instead.' );
  19746. return time.mul( timeScale );
  19747. };
  19748. /**
  19749. * @function
  19750. * @deprecated since r170. Use {@link time} instead.
  19751. *
  19752. * @param {Number} [timeScale=1] - The time scale.
  19753. * @returns {UniformNode<float>}
  19754. */
  19755. const timerGlobal = ( timeScale = 1 ) => { // @deprecated, r170
  19756. console.warn( 'TSL: timerGlobal() is deprecated. Use "time" instead.' );
  19757. return time.mul( timeScale );
  19758. };
  19759. /**
  19760. * @function
  19761. * @deprecated since r170. Use {@link deltaTime} instead.
  19762. *
  19763. * @param {Number} [timeScale=1] - The time scale.
  19764. * @returns {UniformNode<float>}
  19765. */
  19766. const timerDelta = ( timeScale = 1 ) => { // @deprecated, r170
  19767. console.warn( 'TSL: timerDelta() is deprecated. Use "deltaTime" instead.' );
  19768. return deltaTime.mul( timeScale );
  19769. };
  19770. /** @module Oscillators **/
  19771. /**
  19772. * Generates a sine wave oscillation based on a timer.
  19773. *
  19774. * @method
  19775. * @param {Node<float>} t - The timer to generate the oscillation with.
  19776. * @return {Node<float>} The oscillation node.
  19777. */
  19778. const oscSine = ( t = time ) => t.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  19779. /**
  19780. * Generates a square wave oscillation based on a timer.
  19781. *
  19782. * @method
  19783. * @param {Node<float>} t - The timer to generate the oscillation with.
  19784. * @return {Node<float>} The oscillation node.
  19785. */
  19786. const oscSquare = ( t = time ) => t.fract().round();
  19787. /**
  19788. * Generates a triangle wave oscillation based on a timer.
  19789. *
  19790. * @method
  19791. * @param {Node<float>} t - The timer to generate the oscillation with.
  19792. * @return {Node<float>} The oscillation node.
  19793. */
  19794. const oscTriangle = ( t = time ) => t.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  19795. /**
  19796. * Generates a sawtooth wave oscillation based on a timer.
  19797. *
  19798. * @method
  19799. * @param {Node<float>} t - The timer to generate the oscillation with.
  19800. * @return {Node<float>} The oscillation node.
  19801. */
  19802. const oscSawtooth = ( t = time ) => t.fract();
  19803. /** @module UVUtils **/
  19804. /**
  19805. * Rotates the given uv coordinates around a center point
  19806. *
  19807. * @method
  19808. * @param {Node<vec2>} uv - The uv coordinates.
  19809. * @param {Node<float>} rotation - The rotation defined in radians.
  19810. * @param {Node<vec2>} center - The center of rotation
  19811. * @return {Node<vec2>} The rotated uv coordinates.
  19812. */
  19813. const rotateUV = /*@__PURE__*/ Fn( ( [ uv, rotation, center = vec2( 0.5 ) ] ) => {
  19814. return rotate( uv.sub( center ), rotation ).add( center );
  19815. } );
  19816. /**
  19817. * Applies a spherical warping effect to the given uv coordinates.
  19818. *
  19819. * @method
  19820. * @param {Node<vec2>} uv - The uv coordinates.
  19821. * @param {Node<float>} strength - The strength of the effect.
  19822. * @param {Node<vec2>} center - The center point
  19823. * @return {Node<vec2>} The updated uv coordinates.
  19824. */
  19825. const spherizeUV = /*@__PURE__*/ Fn( ( [ uv, strength, center = vec2( 0.5 ) ] ) => {
  19826. const delta = uv.sub( center );
  19827. const delta2 = delta.dot( delta );
  19828. const delta4 = delta2.mul( delta2 );
  19829. const deltaOffset = delta4.mul( strength );
  19830. return uv.add( delta.mul( deltaOffset ) );
  19831. } );
  19832. /** @module SpriteUtils **/
  19833. /**
  19834. * This can be used to achieve a billboarding behavior for flat meshes. That means they are
  19835. * oriented always towards the camera.
  19836. *
  19837. * ```js
  19838. * material.vertexNode = billboarding();
  19839. * ```
  19840. *
  19841. * @method
  19842. * @param {Object} config - The configuration object.
  19843. * @param {Node<vec3>?} [config.position=null] - Can be used to define the vertex positions in world space.
  19844. * @param {Boolean} [config.horizontal=true] - Whether to follow the camera rotation horizontally or not.
  19845. * @param {Boolean} [config.vertical=false] - Whether to follow the camera rotation vertically or not.
  19846. * @return {Node<vec3>} The updated vertex position in clip space.
  19847. */
  19848. const billboarding = /*@__PURE__*/ Fn( ( { position = null, horizontal = true, vertical = false } ) => {
  19849. let worldMatrix;
  19850. if ( position !== null ) {
  19851. worldMatrix = modelWorldMatrix.toVar();
  19852. worldMatrix[ 3 ][ 0 ] = position.x;
  19853. worldMatrix[ 3 ][ 1 ] = position.y;
  19854. worldMatrix[ 3 ][ 2 ] = position.z;
  19855. } else {
  19856. worldMatrix = modelWorldMatrix;
  19857. }
  19858. const modelViewMatrix = cameraViewMatrix.mul( worldMatrix );
  19859. if ( defined( horizontal ) ) {
  19860. modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length();
  19861. modelViewMatrix[ 0 ][ 1 ] = 0;
  19862. modelViewMatrix[ 0 ][ 2 ] = 0;
  19863. }
  19864. if ( defined( vertical ) ) {
  19865. modelViewMatrix[ 1 ][ 0 ] = 0;
  19866. modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length();
  19867. modelViewMatrix[ 1 ][ 2 ] = 0;
  19868. }
  19869. modelViewMatrix[ 2 ][ 0 ] = 0;
  19870. modelViewMatrix[ 2 ][ 1 ] = 0;
  19871. modelViewMatrix[ 2 ][ 2 ] = 1;
  19872. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  19873. } );
  19874. /** @module ViewportUtils **/
  19875. /**
  19876. * A special version of a screen uv function that involves a depth comparison
  19877. * when computing the final uvs. The function mitigates visual errors when
  19878. * using viewport texture nodes for refraction purposes. Without this function
  19879. * objects in front of a refractive surface might appear on the refractive surface
  19880. * which is incorrect.
  19881. *
  19882. * @method
  19883. * @param {Node<vec2>?} uv - Optional uv coordinates. By default `screenUV` is used.
  19884. * @return {Node<vec2>} The update uv coordinates.
  19885. */
  19886. const viewportSafeUV = /*@__PURE__*/ Fn( ( [ uv = null ] ) => {
  19887. const depth = linearDepth();
  19888. const depthDiff = linearDepth( viewportDepthTexture( uv ) ).sub( depth );
  19889. const finalUV = depthDiff.lessThan( 0 ).select( screenUV, uv );
  19890. return finalUV;
  19891. } );
  19892. /** @module SpriteSheetUVNode **/
  19893. /**
  19894. * Can be used to compute texture coordinates for animated sprite sheets.
  19895. *
  19896. * ```js
  19897. * const uvNode = spritesheetUV( vec2( 6, 6 ), uv(), time.mul( animationSpeed ) );
  19898. *
  19899. * material.colorNode = texture( spriteSheet, uvNode );
  19900. * ```
  19901. *
  19902. * @augments Node
  19903. */
  19904. class SpriteSheetUVNode extends Node {
  19905. static get type() {
  19906. return 'SpriteSheetUVNode';
  19907. }
  19908. /**
  19909. * Constructs a new sprite sheet uv node.
  19910. *
  19911. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  19912. * @param {Node<vec2>} [uvNode=uv()] - The uv node.
  19913. * @param {Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  19914. */
  19915. constructor( countNode, uvNode = uv(), frameNode = float( 0 ) ) {
  19916. super( 'vec2' );
  19917. /**
  19918. * The node that defines the number of sprites in the x and y direction (e.g 6x6).
  19919. *
  19920. * @type {Node<vec2>}
  19921. */
  19922. this.countNode = countNode;
  19923. /**
  19924. * The uv node.
  19925. *
  19926. * @type {Node<vec2>}
  19927. */
  19928. this.uvNode = uvNode;
  19929. /**
  19930. * The node that defines the current frame/sprite.
  19931. *
  19932. * @type {Node<float>}
  19933. */
  19934. this.frameNode = frameNode;
  19935. }
  19936. setup() {
  19937. const { frameNode, uvNode, countNode } = this;
  19938. const { width, height } = countNode;
  19939. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  19940. const column = frameNum.mod( width );
  19941. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  19942. const scale = countNode.reciprocal();
  19943. const uvFrameOffset = vec2( column, row );
  19944. return uvNode.add( uvFrameOffset ).mul( scale );
  19945. }
  19946. }
  19947. /**
  19948. * TSL function for creating a sprite sheet uv node.
  19949. *
  19950. * @function
  19951. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  19952. * @param {Node<vec2>} [uvNode=uv()] - The uv node.
  19953. * @param {Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  19954. * @returns {SpriteSheetUVNode}
  19955. */
  19956. const spritesheetUV = /*@__PURE__*/ nodeProxy( SpriteSheetUVNode );
  19957. /** @module TriplanarTexturesNode **/
  19958. /**
  19959. * Can be used for triplanar texture mapping.
  19960. *
  19961. * ```js
  19962. * material.colorNode = triplanarTexture( texture( diffuseMap ) );
  19963. * ```
  19964. *
  19965. * @augments Node
  19966. */
  19967. class TriplanarTexturesNode extends Node {
  19968. static get type() {
  19969. return 'TriplanarTexturesNode';
  19970. }
  19971. /**
  19972. * Constructs a new triplanar textures node.
  19973. *
  19974. * @param {Node} textureXNode - First texture node.
  19975. * @param {Node?} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  19976. * @param {Node?} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  19977. * @param {Node<float>?} [scaleNode=float(1)] - The scale node.
  19978. * @param {Node<vec3>?} [positionNode=positionLocal] - Vertex positions in local space.
  19979. * @param {Node<vec3>?} [normalNode=normalLocal] - Normals in local space.
  19980. */
  19981. constructor( textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ) {
  19982. super( 'vec4' );
  19983. /**
  19984. * First texture node.
  19985. *
  19986. * @type {Node}
  19987. */
  19988. this.textureXNode = textureXNode;
  19989. /**
  19990. * Second texture node. When not set, the shader will sample from `textureXNode` instead.
  19991. *
  19992. * @type {Node}
  19993. * @default null
  19994. */
  19995. this.textureYNode = textureYNode;
  19996. /**
  19997. * Third texture node. When not set, the shader will sample from `textureXNode` instead.
  19998. *
  19999. * @type {Node}
  20000. * @default null
  20001. */
  20002. this.textureZNode = textureZNode;
  20003. /**
  20004. * The scale node.
  20005. *
  20006. * @type {Node<float>}
  20007. * @default float(1)
  20008. */
  20009. this.scaleNode = scaleNode;
  20010. /**
  20011. * Vertex positions in local space.
  20012. *
  20013. * @type {Node<vec3>}
  20014. * @default positionLocal
  20015. */
  20016. this.positionNode = positionNode;
  20017. /**
  20018. * Normals in local space.
  20019. *
  20020. * @type {Node<vec3>}
  20021. * @default normalLocal
  20022. */
  20023. this.normalNode = normalNode;
  20024. }
  20025. setup() {
  20026. const { textureXNode, textureYNode, textureZNode, scaleNode, positionNode, normalNode } = this;
  20027. // Ref: https://github.com/keijiro/StandardTriplanar
  20028. // Blending factor of triplanar mapping
  20029. let bf = normalNode.abs().normalize();
  20030. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  20031. // Triplanar mapping
  20032. const tx = positionNode.yz.mul( scaleNode );
  20033. const ty = positionNode.zx.mul( scaleNode );
  20034. const tz = positionNode.xy.mul( scaleNode );
  20035. // Base color
  20036. const textureX = textureXNode.value;
  20037. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  20038. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  20039. const cx = texture( textureX, tx ).mul( bf.x );
  20040. const cy = texture( textureY, ty ).mul( bf.y );
  20041. const cz = texture( textureZ, tz ).mul( bf.z );
  20042. return add( cx, cy, cz );
  20043. }
  20044. }
  20045. /**
  20046. * TSL function for creating a triplanar textures node.
  20047. *
  20048. * @function
  20049. * @param {Node} textureXNode - First texture node.
  20050. * @param {Node?} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  20051. * @param {Node?} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  20052. * @param {Node<float>?} [scaleNode=float(1)] - The scale node.
  20053. * @param {Node<vec3>?} [positionNode=positionLocal] - Vertex positions in local space.
  20054. * @param {Node<vec3>?} [normalNode=normalLocal] - Normals in local space.
  20055. * @returns {TriplanarTexturesNode}
  20056. */
  20057. const triplanarTextures = /*@__PURE__*/ nodeProxy( TriplanarTexturesNode );
  20058. /**
  20059. * TSL function for creating a triplanar textures node.
  20060. *
  20061. * @function
  20062. * @param {Node} textureXNode - First texture node.
  20063. * @param {Node?} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  20064. * @param {Node?} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  20065. * @param {Node<float>?} [scaleNode=float(1)] - The scale node.
  20066. * @param {Node<vec3>?} [positionNode=positionLocal] - Vertex positions in local space.
  20067. * @param {Node<vec3>?} [normalNode=normalLocal] - Normals in local space.
  20068. * @returns {TriplanarTexturesNode}
  20069. */
  20070. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  20071. /** @module ReflectorNode **/
  20072. const _reflectorPlane = new Plane();
  20073. const _normal = new Vector3();
  20074. const _reflectorWorldPosition = new Vector3();
  20075. const _cameraWorldPosition = new Vector3();
  20076. const _rotationMatrix = new Matrix4();
  20077. const _lookAtPosition = new Vector3( 0, 0, -1 );
  20078. const clipPlane = new Vector4();
  20079. const _view = new Vector3();
  20080. const _target = new Vector3();
  20081. const _q = new Vector4();
  20082. const _size$2 = new Vector2();
  20083. const _defaultRT = new RenderTarget();
  20084. const _defaultUV = screenUV.flipX();
  20085. _defaultRT.depthTexture = new DepthTexture( 1, 1 );
  20086. let _inReflector = false;
  20087. /**
  20088. * This node can be used to implement mirror-like flat reflective surfaces.
  20089. *
  20090. * ```js
  20091. * const groundReflector = reflector();
  20092. * material.colorNode = groundReflector;
  20093. *
  20094. * const plane = new Mesh( geometry, material );
  20095. * plane.add( groundReflector.target );
  20096. * ```
  20097. *
  20098. * @augments module:TextureNode~TextureNode
  20099. */
  20100. class ReflectorNode extends TextureNode {
  20101. static get type() {
  20102. return 'ReflectorNode';
  20103. }
  20104. /**
  20105. * Constructs a new reflector node.
  20106. *
  20107. * @param {Object} [parameters={}] - An object holding configuration parameters.
  20108. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  20109. * @param {Number} [parameters.resolution=1] - The resolution scale.
  20110. * @param {Boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  20111. * @param {Boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  20112. * @param {Boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  20113. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  20114. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  20115. */
  20116. constructor( parameters = {} ) {
  20117. super( parameters.defaultTexture || _defaultRT.texture, _defaultUV );
  20118. /**
  20119. * A reference to the internal reflector base node which holds the actual implementation.
  20120. *
  20121. * @private
  20122. * @type {ReflectorBaseNode?}
  20123. * @default null
  20124. */
  20125. this._reflectorBaseNode = parameters.reflector || new ReflectorBaseNode( this, parameters );
  20126. /**
  20127. * A reference to the internal depth node.
  20128. *
  20129. * @private
  20130. * @type {Node?}
  20131. * @default null
  20132. */
  20133. this._depthNode = null;
  20134. this.setUpdateMatrix( false );
  20135. }
  20136. /**
  20137. * A reference to the internal reflector node.
  20138. *
  20139. * @type {ReflectorBaseNode}
  20140. */
  20141. get reflector() {
  20142. return this._reflectorBaseNode;
  20143. }
  20144. /**
  20145. * A reference to 3D object the reflector is linked to.
  20146. *
  20147. * @type {Object3D}
  20148. */
  20149. get target() {
  20150. return this._reflectorBaseNode.target;
  20151. }
  20152. /**
  20153. * Returns a node representing the mirror's depth. That can be used
  20154. * to implement more advanced reflection effects like distance attenuation.
  20155. *
  20156. * @return {Node} The depth node.
  20157. */
  20158. getDepthNode() {
  20159. if ( this._depthNode === null ) {
  20160. if ( this._reflectorBaseNode.depth !== true ) {
  20161. throw new Error( 'THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ' );
  20162. }
  20163. this._depthNode = nodeObject( new ReflectorNode( {
  20164. defaultTexture: _defaultRT.depthTexture,
  20165. reflector: this._reflectorBaseNode
  20166. } ) );
  20167. }
  20168. return this._depthNode;
  20169. }
  20170. setup( builder ) {
  20171. // ignore if used in post-processing
  20172. if ( ! builder.object.isQuadMesh ) this._reflectorBaseNode.build( builder );
  20173. return super.setup( builder );
  20174. }
  20175. clone() {
  20176. const texture = new this.constructor( this.reflectorNode );
  20177. texture._reflectorBaseNode = this._reflectorBaseNode;
  20178. return texture;
  20179. }
  20180. }
  20181. /**
  20182. * Holds the actual implementation of the reflector.
  20183. *
  20184. * TODO: Explain why `ReflectorBaseNode`. Originally the entire logic was implemented
  20185. * in `ReflectorNode`, see #29619.
  20186. *
  20187. * @private
  20188. * @augments Node
  20189. */
  20190. class ReflectorBaseNode extends Node {
  20191. static get type() {
  20192. return 'ReflectorBaseNode';
  20193. }
  20194. /**
  20195. * Constructs a new reflector base node.
  20196. *
  20197. * @param {TextureNode} textureNode - Represents the rendered reflections as a texture node.
  20198. * @param {Object} [parameters={}] - An object holding configuration parameters.
  20199. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  20200. * @param {Number} [parameters.resolution=1] - The resolution scale.
  20201. * @param {Boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  20202. * @param {Boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  20203. * @param {Boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  20204. */
  20205. constructor( textureNode, parameters = {} ) {
  20206. super();
  20207. const {
  20208. target = new Object3D(),
  20209. resolution = 1,
  20210. generateMipmaps = false,
  20211. bounces = true,
  20212. depth = false
  20213. } = parameters;
  20214. /**
  20215. * Represents the rendered reflections as a texture node.
  20216. *
  20217. * @type {TextureNode}
  20218. */
  20219. this.textureNode = textureNode;
  20220. /**
  20221. * The 3D object the reflector is linked to.
  20222. *
  20223. * @type {Object3D}
  20224. * @default {new Object3D()}
  20225. */
  20226. this.target = target;
  20227. /**
  20228. * The resolution scale.
  20229. *
  20230. * @type {Number}
  20231. * @default {1}
  20232. */
  20233. this.resolution = resolution;
  20234. /**
  20235. * Whether mipmaps should be generated or not.
  20236. *
  20237. * @type {Boolean}
  20238. * @default {false}
  20239. */
  20240. this.generateMipmaps = generateMipmaps;
  20241. /**
  20242. * Whether reflectors can render other reflector nodes or not.
  20243. *
  20244. * @type {Boolean}
  20245. * @default {true}
  20246. */
  20247. this.bounces = bounces;
  20248. /**
  20249. * Whether depth data should be generated or not.
  20250. *
  20251. * @type {Boolean}
  20252. * @default {false}
  20253. */
  20254. this.depth = depth;
  20255. /**
  20256. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` when {@link ReflectorBaseNode#bounces}
  20257. * is `true`. Otherwise it's `NodeUpdateType.FRAME`.
  20258. *
  20259. * @type {String}
  20260. * @default 'render'
  20261. */
  20262. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  20263. /**
  20264. * Weak map for managing virtual cameras.
  20265. *
  20266. * @type {WeakMap<Camera, Camera>}
  20267. */
  20268. this.virtualCameras = new WeakMap();
  20269. /**
  20270. * Weak map for managing render targets.
  20271. *
  20272. * @type {WeakMap<Camera, RenderTarget>}
  20273. */
  20274. this.renderTargets = new WeakMap();
  20275. }
  20276. /**
  20277. * Updates the resolution of the internal render target.
  20278. *
  20279. * @private
  20280. * @param {RenderTarget} renderTarget - The render target to resize.
  20281. * @param {Renderer} renderer - The renderer that is used to determine the new size.
  20282. */
  20283. _updateResolution( renderTarget, renderer ) {
  20284. const resolution = this.resolution;
  20285. renderer.getDrawingBufferSize( _size$2 );
  20286. renderTarget.setSize( Math.round( _size$2.width * resolution ), Math.round( _size$2.height * resolution ) );
  20287. }
  20288. setup( builder ) {
  20289. this._updateResolution( _defaultRT, builder.renderer );
  20290. return super.setup( builder );
  20291. }
  20292. /**
  20293. * Returns a virtual camera for the given camera. The virtual camera is used to
  20294. * render the scene from the reflector's view so correct reflections can be produced.
  20295. *
  20296. * @param {Camera} camera - The scene's camera.
  20297. * @return {Camera} The corresponding virtual camera.
  20298. */
  20299. getVirtualCamera( camera ) {
  20300. let virtualCamera = this.virtualCameras.get( camera );
  20301. if ( virtualCamera === undefined ) {
  20302. virtualCamera = camera.clone();
  20303. this.virtualCameras.set( camera, virtualCamera );
  20304. }
  20305. return virtualCamera;
  20306. }
  20307. /**
  20308. * Returns a render target for the given camera. The reflections are rendered
  20309. * into this render target.
  20310. *
  20311. * @param {Camera} camera - The scene's camera.
  20312. * @return {RenderTarget} The render target.
  20313. */
  20314. getRenderTarget( camera ) {
  20315. let renderTarget = this.renderTargets.get( camera );
  20316. if ( renderTarget === undefined ) {
  20317. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType } );
  20318. if ( this.generateMipmaps === true ) {
  20319. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  20320. renderTarget.texture.generateMipmaps = true;
  20321. }
  20322. if ( this.depth === true ) {
  20323. renderTarget.depthTexture = new DepthTexture();
  20324. }
  20325. this.renderTargets.set( camera, renderTarget );
  20326. }
  20327. return renderTarget;
  20328. }
  20329. updateBefore( frame ) {
  20330. if ( this.bounces === false && _inReflector ) return false;
  20331. _inReflector = true;
  20332. const { scene, camera, renderer, material } = frame;
  20333. const { target } = this;
  20334. const virtualCamera = this.getVirtualCamera( camera );
  20335. const renderTarget = this.getRenderTarget( virtualCamera );
  20336. renderer.getDrawingBufferSize( _size$2 );
  20337. this._updateResolution( renderTarget, renderer );
  20338. //
  20339. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  20340. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  20341. _rotationMatrix.extractRotation( target.matrixWorld );
  20342. _normal.set( 0, 0, 1 );
  20343. _normal.applyMatrix4( _rotationMatrix );
  20344. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  20345. // Avoid rendering when reflector is facing away
  20346. if ( _view.dot( _normal ) > 0 ) return;
  20347. _view.reflect( _normal ).negate();
  20348. _view.add( _reflectorWorldPosition );
  20349. _rotationMatrix.extractRotation( camera.matrixWorld );
  20350. _lookAtPosition.set( 0, 0, -1 );
  20351. _lookAtPosition.applyMatrix4( _rotationMatrix );
  20352. _lookAtPosition.add( _cameraWorldPosition );
  20353. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  20354. _target.reflect( _normal ).negate();
  20355. _target.add( _reflectorWorldPosition );
  20356. //
  20357. virtualCamera.coordinateSystem = camera.coordinateSystem;
  20358. virtualCamera.position.copy( _view );
  20359. virtualCamera.up.set( 0, 1, 0 );
  20360. virtualCamera.up.applyMatrix4( _rotationMatrix );
  20361. virtualCamera.up.reflect( _normal );
  20362. virtualCamera.lookAt( _target );
  20363. virtualCamera.near = camera.near;
  20364. virtualCamera.far = camera.far;
  20365. virtualCamera.updateMatrixWorld();
  20366. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  20367. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  20368. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  20369. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  20370. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  20371. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  20372. const projectionMatrix = virtualCamera.projectionMatrix;
  20373. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  20374. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  20375. _q.z = -1;
  20376. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  20377. // Calculate the scaled plane vector
  20378. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  20379. const clipBias = 0;
  20380. // Replacing the third row of the projection matrix
  20381. projectionMatrix.elements[ 2 ] = clipPlane.x;
  20382. projectionMatrix.elements[ 6 ] = clipPlane.y;
  20383. projectionMatrix.elements[ 10 ] = ( renderer.coordinateSystem === WebGPUCoordinateSystem ) ? ( clipPlane.z - clipBias ) : ( clipPlane.z + 1.0 - clipBias );
  20384. projectionMatrix.elements[ 14 ] = clipPlane.w;
  20385. //
  20386. this.textureNode.value = renderTarget.texture;
  20387. if ( this.depth === true ) {
  20388. this.textureNode.getDepthNode().value = renderTarget.depthTexture;
  20389. }
  20390. material.visible = false;
  20391. const currentRenderTarget = renderer.getRenderTarget();
  20392. const currentMRT = renderer.getMRT();
  20393. const currentAutoClear = renderer.autoClear;
  20394. renderer.setMRT( null );
  20395. renderer.setRenderTarget( renderTarget );
  20396. renderer.autoClear = true;
  20397. renderer.render( scene, virtualCamera );
  20398. renderer.setMRT( currentMRT );
  20399. renderer.setRenderTarget( currentRenderTarget );
  20400. renderer.autoClear = currentAutoClear;
  20401. material.visible = true;
  20402. _inReflector = false;
  20403. }
  20404. }
  20405. /**
  20406. * TSL function for creating a reflector node.
  20407. *
  20408. * @function
  20409. * @param {Object} [parameters={}] - An object holding configuration parameters.
  20410. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  20411. * @param {Number} [parameters.resolution=1] - The resolution scale.
  20412. * @param {Boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  20413. * @param {Boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  20414. * @param {Boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  20415. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  20416. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  20417. * @returns {ReflectorNode}
  20418. */
  20419. const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) );
  20420. const _camera = /*@__PURE__*/ new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  20421. /**
  20422. * The purpose of this special geometry is to fill the entire viewport with a single triangle.
  20423. *
  20424. * Reference: {@link https://github.com/mrdoob/three.js/pull/21358}
  20425. *
  20426. * @private
  20427. * @augments BufferGeometry
  20428. */
  20429. class QuadGeometry extends BufferGeometry {
  20430. /**
  20431. * Constructs a new quad geometry.
  20432. *
  20433. * @param {Boolean} [flipY=false] - Whether the uv coordinates should be flipped along the vertical axis or not.
  20434. */
  20435. constructor( flipY = false ) {
  20436. super();
  20437. const uv = flipY === false ? [ 0, -1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  20438. this.setAttribute( 'position', new Float32BufferAttribute( [ -1, 3, 0, -1, -1, 0, 3, -1, 0 ], 3 ) );
  20439. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  20440. }
  20441. }
  20442. const _geometry = /*@__PURE__*/ new QuadGeometry();
  20443. /**
  20444. * This module is a helper for passes which need to render a full
  20445. * screen effect which is quite common in context of post processing.
  20446. *
  20447. * The intended usage is to reuse a single quad mesh for rendering
  20448. * subsequent passes by just reassigning the `material` reference.
  20449. *
  20450. * @augments Mesh
  20451. */
  20452. class QuadMesh extends Mesh {
  20453. /**
  20454. * Constructs a new quad mesh.
  20455. *
  20456. * @param {Material?} [material=null] - The material to render the quad mesh with.
  20457. */
  20458. constructor( material = null ) {
  20459. super( _geometry, material );
  20460. /**
  20461. * The camera to render the quad mesh with.
  20462. *
  20463. * @type {OrthographicCamera}
  20464. * @readonly
  20465. */
  20466. this.camera = _camera;
  20467. /**
  20468. * This flag can be used for type testing.
  20469. *
  20470. * @type {Boolean}
  20471. * @readonly
  20472. * @default true
  20473. */
  20474. this.isQuadMesh = true;
  20475. }
  20476. /**
  20477. * Async version of `render()`.
  20478. *
  20479. * @async
  20480. * @param {Renderer} renderer - The renderer.
  20481. * @return {Promise} A Promise that resolves when the render has been finished.
  20482. */
  20483. async renderAsync( renderer ) {
  20484. return renderer.renderAsync( this, _camera );
  20485. }
  20486. /**
  20487. * Renders the quad mesh
  20488. *
  20489. * @param {Renderer} renderer - The renderer.
  20490. */
  20491. render( renderer ) {
  20492. renderer.render( this, _camera );
  20493. }
  20494. }
  20495. /** @module RTTNode **/
  20496. const _size$1 = /*@__PURE__*/ new Vector2();
  20497. /**
  20498. * `RTTNode` takes another node and uses it with a `QuadMesh` to render into a texture (RTT).
  20499. * This module is especially relevant in context of post processing where certain nodes require
  20500. * texture input for their effects. With the helper function `convertToTexture()` which is based
  20501. * on this module, the node system can automatically ensure texture input if required.
  20502. *
  20503. * @augments module:TextureNode~TextureNode
  20504. */
  20505. class RTTNode extends TextureNode {
  20506. static get type() {
  20507. return 'RTTNode';
  20508. }
  20509. /**
  20510. * Constructs a new RTT node.
  20511. *
  20512. * @param {Node} node - The node to render a texture with.
  20513. * @param {Number?} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  20514. * @param {Number?} [height=null] - The height of the internal render target.
  20515. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  20516. */
  20517. constructor( node, width = null, height = null, options = { type: HalfFloatType } ) {
  20518. const renderTarget = new RenderTarget( width, height, options );
  20519. super( renderTarget.texture, uv() );
  20520. /**
  20521. * The node to render a texture with.
  20522. *
  20523. * @type {Node}
  20524. */
  20525. this.node = node;
  20526. /**
  20527. * The width of the internal render target.
  20528. * If not width is applied, the render target is automatically resized.
  20529. *
  20530. * @type {Number?}
  20531. * @default null
  20532. */
  20533. this.width = width;
  20534. /**
  20535. * The height of the internal render target.
  20536. *
  20537. * @type {Number?}
  20538. * @default null
  20539. */
  20540. this.height = height;
  20541. /**
  20542. * The pixel ratio
  20543. *
  20544. * @type {Number}
  20545. * @default 1
  20546. */
  20547. this.pixelRatio = 1;
  20548. /**
  20549. * The render target
  20550. *
  20551. * @type {RenderTarget}
  20552. */
  20553. this.renderTarget = renderTarget;
  20554. /**
  20555. * Whether the texture requires an update or not.
  20556. *
  20557. * @type {Boolean}
  20558. * @default true
  20559. */
  20560. this.textureNeedsUpdate = true;
  20561. /**
  20562. * Whether the texture should automatically be updated or not.
  20563. *
  20564. * @type {Boolean}
  20565. * @default true
  20566. */
  20567. this.autoUpdate = true;
  20568. /**
  20569. * The node which is used with the quad mesh for RTT.
  20570. *
  20571. * @private
  20572. * @type {Node}
  20573. * @default null
  20574. */
  20575. this._rttNode = null;
  20576. /**
  20577. * The internal quad mesh for RTT.
  20578. *
  20579. * @private
  20580. * @type {QuadMesh}
  20581. */
  20582. this._quadMesh = new QuadMesh( new NodeMaterial() );
  20583. /**
  20584. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  20585. * the texture once per render in its {@link RTTNode#updateBefore} method.
  20586. *
  20587. * @type {String}
  20588. * @default 'render'
  20589. */
  20590. this.updateBeforeType = NodeUpdateType.RENDER;
  20591. }
  20592. /**
  20593. * Whether the internal render target should automatically be resized or not.
  20594. *
  20595. * @type {Boolean}
  20596. * @readonly
  20597. * @default true
  20598. */
  20599. get autoSize() {
  20600. return this.width === null;
  20601. }
  20602. setup( builder ) {
  20603. this._rttNode = this.node.context( builder.getSharedContext() );
  20604. this._quadMesh.material.name = 'RTT';
  20605. this._quadMesh.material.needsUpdate = true;
  20606. return super.setup( builder );
  20607. }
  20608. /**
  20609. * Sets the size of the internal render target
  20610. *
  20611. * @param {Number} width - The width to set.
  20612. * @param {Number} height - The width to set.
  20613. */
  20614. setSize( width, height ) {
  20615. this.width = width;
  20616. this.height = height;
  20617. const effectiveWidth = width * this.pixelRatio;
  20618. const effectiveHeight = height * this.pixelRatio;
  20619. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  20620. this.textureNeedsUpdate = true;
  20621. }
  20622. /**
  20623. * Sets the pixel ratio. This will also resize the render target.
  20624. *
  20625. * @param {Number} pixelRatio - The pixel ratio to set.
  20626. */
  20627. setPixelRatio( pixelRatio ) {
  20628. this.pixelRatio = pixelRatio;
  20629. this.setSize( this.width, this.height );
  20630. }
  20631. updateBefore( { renderer } ) {
  20632. if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return;
  20633. this.textureNeedsUpdate = false;
  20634. //
  20635. if ( this.autoSize === true ) {
  20636. this.pixelRatio = renderer.getPixelRatio();
  20637. const size = renderer.getSize( _size$1 );
  20638. this.setSize( size.width, size.height );
  20639. }
  20640. //
  20641. this._quadMesh.material.fragmentNode = this._rttNode;
  20642. //
  20643. const currentRenderTarget = renderer.getRenderTarget();
  20644. renderer.setRenderTarget( this.renderTarget );
  20645. this._quadMesh.render( renderer );
  20646. renderer.setRenderTarget( currentRenderTarget );
  20647. }
  20648. clone() {
  20649. const newNode = new TextureNode( this.value, this.uvNode, this.levelNode );
  20650. newNode.sampler = this.sampler;
  20651. newNode.referenceNode = this;
  20652. return newNode;
  20653. }
  20654. }
  20655. /**
  20656. * TSL function for creating a RTT node.
  20657. *
  20658. * @function
  20659. * @param {Node} node - The node to render a texture with.
  20660. * @param {Number?} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  20661. * @param {Number?} [height=null] - The height of the internal render target.
  20662. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  20663. * @returns {RTTNode}
  20664. */
  20665. const rtt = ( node, ...params ) => nodeObject( new RTTNode( nodeObject( node ), ...params ) );
  20666. /**
  20667. * TSL function for converting nodes to textures nodes.
  20668. *
  20669. * @function
  20670. * @param {Node} node - The node to render a texture with.
  20671. * @param {Number?} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  20672. * @param {Number?} [height=null] - The height of the internal render target.
  20673. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  20674. * @returns {RTTNode}
  20675. */
  20676. const convertToTexture = ( node, ...params ) => {
  20677. if ( node.isTextureNode ) return node;
  20678. if ( node.isPassNode ) return node.getTextureNode();
  20679. return rtt( node, ...params );
  20680. };
  20681. /** @module PostProcessingUtils **/
  20682. /**
  20683. * Computes a position in view space based on a fragment's screen position expressed as uv coordinates, the fragments
  20684. * depth value and the camera's inverse projection matrix.
  20685. *
  20686. * @method
  20687. * @param {Node<vec2>} screenPosition - The fragment's screen position expressed as uv coordinates.
  20688. * @param {Node<float>} depth - The fragment's depth value.
  20689. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  20690. * @return {Node<vec3>} The fragments position in view space.
  20691. */
  20692. const getViewPosition = /*@__PURE__*/ Fn( ( [ screenPosition, depth, projectionMatrixInverse ], builder ) => {
  20693. let clipSpacePosition;
  20694. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  20695. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  20696. clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  20697. } else {
  20698. clipSpacePosition = vec4( vec3( screenPosition.x, screenPosition.y.oneMinus(), depth ).mul( 2.0 ).sub( 1.0 ), 1.0 );
  20699. }
  20700. const viewSpacePosition = vec4( projectionMatrixInverse.mul( clipSpacePosition ) );
  20701. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  20702. } );
  20703. /**
  20704. * Computes a screen position expressed as uv coordinates based on a fragment's position in view space
  20705. * and the camera's projection matrix
  20706. *
  20707. * @method
  20708. * @param {Node<vec3>} viewPosition - The fragments position in view space.
  20709. * @param {Node<mat4>} projectionMatrix - The camera's projection matrix.
  20710. * @return {Node<vec2>} The fragment's screen position expressed as uv coordinates.
  20711. */
  20712. const getScreenPosition = /*@__PURE__*/ Fn( ( [ viewPosition, projectionMatrix ] ) => {
  20713. const sampleClipPos = projectionMatrix.mul( vec4( viewPosition, 1.0 ) );
  20714. const sampleUv = sampleClipPos.xy.div( sampleClipPos.w ).mul( 0.5 ).add( 0.5 ).toVar();
  20715. return vec2( sampleUv.x, sampleUv.y.oneMinus() );
  20716. } );
  20717. /**
  20718. * Computes a normal vector based on depth data. Can be used as a fallback when no normal render
  20719. * target is available or if flat surface normals are required.
  20720. *
  20721. * @method
  20722. * @param {Node<vec2>} uv - The texture coordinate.
  20723. * @param {DepthTexture} depthTexture - The depth texture.
  20724. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  20725. * @return {Node<vec3>} The computed normal vector.
  20726. */
  20727. const getNormalFromDepth = /*@__PURE__*/ Fn( ( [ uv, depthTexture, projectionMatrixInverse ] ) => {
  20728. const size = textureSize( textureLoad( depthTexture ) );
  20729. const p = ivec2( uv.mul( size ) ).toVar();
  20730. const c0 = textureLoad( depthTexture, p ).toVar();
  20731. const l2 = textureLoad( depthTexture, p.sub( ivec2( 2, 0 ) ) ).toVar();
  20732. const l1 = textureLoad( depthTexture, p.sub( ivec2( 1, 0 ) ) ).toVar();
  20733. const r1 = textureLoad( depthTexture, p.add( ivec2( 1, 0 ) ) ).toVar();
  20734. const r2 = textureLoad( depthTexture, p.add( ivec2( 2, 0 ) ) ).toVar();
  20735. const b2 = textureLoad( depthTexture, p.add( ivec2( 0, 2 ) ) ).toVar();
  20736. const b1 = textureLoad( depthTexture, p.add( ivec2( 0, 1 ) ) ).toVar();
  20737. const t1 = textureLoad( depthTexture, p.sub( ivec2( 0, 1 ) ) ).toVar();
  20738. const t2 = textureLoad( depthTexture, p.sub( ivec2( 0, 2 ) ) ).toVar();
  20739. const dl = abs( sub( float( 2 ).mul( l1 ).sub( l2 ), c0 ) ).toVar();
  20740. const dr = abs( sub( float( 2 ).mul( r1 ).sub( r2 ), c0 ) ).toVar();
  20741. const db = abs( sub( float( 2 ).mul( b1 ).sub( b2 ), c0 ) ).toVar();
  20742. const dt = abs( sub( float( 2 ).mul( t1 ).sub( t2 ), c0 ) ).toVar();
  20743. const ce = getViewPosition( uv, c0, projectionMatrixInverse ).toVar();
  20744. 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 ) ) );
  20745. 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 ) ) );
  20746. return normalize( cross( dpdx, dpdy ) );
  20747. } );
  20748. /**
  20749. * This special type of instanced buffer attribute is intended for compute shaders.
  20750. * In earlier three.js versions it was only possible to update attribute data
  20751. * on the CPU via JavaScript and then upload the data to the GPU. With the
  20752. * new material system and renderer it is now possible to use compute shaders
  20753. * to compute the data for an attribute more efficiently on the GPU.
  20754. *
  20755. * The idea is to create an instance of this class and provide it as an input
  20756. * to {@link module:StorageBufferNode}.
  20757. *
  20758. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  20759. *
  20760. * @augments InstancedBufferAttribute
  20761. */
  20762. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  20763. /**
  20764. * Constructs a new storage instanced buffer attribute.
  20765. *
  20766. * @param {Number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  20767. * The subsequent parameters are then obsolete.
  20768. * @param {Number} itemSize - The item size.
  20769. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  20770. */
  20771. constructor( count, itemSize, typeClass = Float32Array ) {
  20772. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  20773. super( array, itemSize );
  20774. /**
  20775. * This flag can be used for type testing.
  20776. *
  20777. * @type {Boolean}
  20778. * @readonly
  20779. * @default true
  20780. */
  20781. this.isStorageInstancedBufferAttribute = true;
  20782. }
  20783. }
  20784. /**
  20785. * This special type of buffer attribute is intended for compute shaders.
  20786. * In earlier three.js versions it was only possible to update attribute data
  20787. * on the CPU via JavaScript and then upload the data to the GPU. With the
  20788. * new material system and renderer it is now possible to use compute shaders
  20789. * to compute the data for an attribute more efficiently on the GPU.
  20790. *
  20791. * The idea is to create an instance of this class and provide it as an input
  20792. * to {@link module:StorageBufferNode}.
  20793. *
  20794. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  20795. *
  20796. * @augments BufferAttribute
  20797. */
  20798. class StorageBufferAttribute extends BufferAttribute {
  20799. /**
  20800. * Constructs a new storage buffer attribute.
  20801. *
  20802. * @param {Number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  20803. * The subsequent parameters are then obsolete.
  20804. * @param {Number} itemSize - The item size.
  20805. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  20806. */
  20807. constructor( count, itemSize, typeClass = Float32Array ) {
  20808. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  20809. super( array, itemSize );
  20810. /**
  20811. * This flag can be used for type testing.
  20812. *
  20813. * @type {Boolean}
  20814. * @readonly
  20815. * @default true
  20816. */
  20817. this.isStorageBufferAttribute = true;
  20818. }
  20819. }
  20820. /** @module StorageArrayElementNode **/
  20821. /**
  20822. * This class enables element access on instances of {@link StorageBufferNode}.
  20823. * In most cases, it is indirectly used when accessing elements with the
  20824. * {@link StorageBufferNode#element} method.
  20825. *
  20826. * ```js
  20827. * const position = positionStorage.element( instanceIndex );
  20828. * ```
  20829. *
  20830. * @augments ArrayElementNode
  20831. */
  20832. class StorageArrayElementNode extends ArrayElementNode {
  20833. static get type() {
  20834. return 'StorageArrayElementNode';
  20835. }
  20836. /**
  20837. * Constructs storage buffer element node.
  20838. *
  20839. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  20840. * @param {Node} indexNode - The index node that defines the element access.
  20841. */
  20842. constructor( storageBufferNode, indexNode ) {
  20843. super( storageBufferNode, indexNode );
  20844. /**
  20845. * This flag can be used for type testing.
  20846. *
  20847. * @type {Boolean}
  20848. * @readonly
  20849. * @default true
  20850. */
  20851. this.isStorageArrayElementNode = true;
  20852. }
  20853. /**
  20854. * The storage buffer node.
  20855. *
  20856. * @param {Node} value
  20857. * @type {StorageBufferNode}
  20858. */
  20859. set storageBufferNode( value ) {
  20860. this.node = value;
  20861. }
  20862. get storageBufferNode() {
  20863. return this.node;
  20864. }
  20865. setup( builder ) {
  20866. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  20867. if ( this.node.isPBO === true ) {
  20868. builder.setupPBO( this.node );
  20869. }
  20870. }
  20871. return super.setup( builder );
  20872. }
  20873. generate( builder, output ) {
  20874. let snippet;
  20875. const isAssignContext = builder.context.assign;
  20876. //
  20877. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  20878. if ( this.node.isPBO === true && isAssignContext !== true && ( this.node.value.isInstancedBufferAttribute || builder.shaderStage !== 'compute' ) ) {
  20879. snippet = builder.generatePBO( this );
  20880. } else {
  20881. snippet = this.node.build( builder );
  20882. }
  20883. } else {
  20884. snippet = super.generate( builder );
  20885. }
  20886. if ( isAssignContext !== true ) {
  20887. const type = this.getNodeType( builder );
  20888. snippet = builder.format( snippet, type, output );
  20889. }
  20890. return snippet;
  20891. }
  20892. }
  20893. /**
  20894. * TSL function for creating a storage element node.
  20895. *
  20896. * @function
  20897. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  20898. * @param {Node} indexNode - The index node that defines the element access.
  20899. * @returns {StorageArrayElementNode}
  20900. */
  20901. const storageElement = /*@__PURE__*/ nodeProxy( StorageArrayElementNode );
  20902. /** @module StorageBufferNode **/
  20903. /**
  20904. * This node is used in context of compute shaders and allows to define a
  20905. * storage buffer for data. A typical workflow is to create instances of
  20906. * this node with the convenience functions `attributeArray()` or `instancedArray()`,
  20907. * setup up a compute shader that writes into the buffers and then convert
  20908. * the storage buffers to attribute nodes for rendering.
  20909. *
  20910. * ```js
  20911. * const positionBuffer = instancedArray( particleCount, 'vec3' ); // the storage buffer node
  20912. *
  20913. * const computeInit = Fn( () => { // the compute shader
  20914. *
  20915. * const position = positionBuffer.element( instanceIndex );
  20916. *
  20917. * // compute position data
  20918. *
  20919. * position.x = 1;
  20920. * position.y = 1;
  20921. * position.z = 1;
  20922. *
  20923. * } )().compute( particleCount );
  20924. *
  20925. * const particleMaterial = new THREE.SpriteNodeMaterial();
  20926. * particleMaterial.positionNode = positionBuffer.toAttribute();
  20927. *
  20928. * renderer.computeAsync( computeInit );
  20929. *
  20930. * ```
  20931. *
  20932. * @augments BufferNode
  20933. */
  20934. class StorageBufferNode extends BufferNode {
  20935. static get type() {
  20936. return 'StorageBufferNode';
  20937. }
  20938. /**
  20939. * Constructs a new storage buffer node.
  20940. *
  20941. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  20942. * @param {String?} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  20943. * @param {Number} [bufferCount=0] - The buffer count.
  20944. */
  20945. constructor( value, bufferType = null, bufferCount = 0 ) {
  20946. if ( bufferType === null && ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) ) {
  20947. bufferType = getTypeFromLength( value.itemSize );
  20948. bufferCount = value.count;
  20949. }
  20950. super( value, bufferType, bufferCount );
  20951. /**
  20952. * This flag can be used for type testing.
  20953. *
  20954. * @type {Boolean}
  20955. * @readonly
  20956. * @default true
  20957. */
  20958. this.isStorageBufferNode = true;
  20959. /**
  20960. * The access type of the texture node.
  20961. *
  20962. * @type {String}
  20963. * @default 'readWrite'
  20964. */
  20965. this.access = NodeAccess.READ_WRITE;
  20966. /**
  20967. * Whether the node is atomic or not.
  20968. *
  20969. * @type {Boolean}
  20970. * @default false
  20971. */
  20972. this.isAtomic = false;
  20973. /**
  20974. * Whether the node represents a PBO or not.
  20975. * Only relevant for WebGL.
  20976. *
  20977. * @type {Boolean}
  20978. * @default false
  20979. */
  20980. this.isPBO = false;
  20981. /**
  20982. * A reference to the internal buffer attribute node.
  20983. *
  20984. * @type {BufferAttributeNode?}
  20985. * @default null
  20986. */
  20987. this._attribute = null;
  20988. /**
  20989. * A reference to the internal varying node.
  20990. *
  20991. * @type {VaryingNode?}
  20992. * @default null
  20993. */
  20994. this._varying = null;
  20995. /**
  20996. * `StorageBufferNode` sets this property to `true` by default.
  20997. *
  20998. * @type {Boolean}
  20999. * @default true
  21000. */
  21001. this.global = true;
  21002. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  21003. // TODO: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  21004. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  21005. else value.isStorageBufferAttribute = true;
  21006. }
  21007. }
  21008. /**
  21009. * This method is overwritten since the buffer data might be shared
  21010. * and thus the hash should be shared as well.
  21011. *
  21012. * @param {NodeBuilder} builder - The current node builder.
  21013. * @return {String} The hash.
  21014. */
  21015. getHash( builder ) {
  21016. if ( this.bufferCount === 0 ) {
  21017. let bufferData = builder.globalCache.getData( this.value );
  21018. if ( bufferData === undefined ) {
  21019. bufferData = {
  21020. node: this
  21021. };
  21022. builder.globalCache.setData( this.value, bufferData );
  21023. }
  21024. return bufferData.node.uuid;
  21025. }
  21026. return this.uuid;
  21027. }
  21028. /**
  21029. * Overwrites the default implementation to return a fixed value `'indirectStorageBuffer'` or `'storageBuffer'`.
  21030. *
  21031. * @param {NodeBuilder} builder - The current node builder.
  21032. * @return {String} The input type.
  21033. */
  21034. getInputType( /*builder*/ ) {
  21035. return this.value.isIndirectStorageBufferAttribute ? 'indirectStorageBuffer' : 'storageBuffer';
  21036. }
  21037. /**
  21038. * Enables element access with the given index node.
  21039. *
  21040. * @param {IndexNode} indexNode - The index node.
  21041. * @return {StorageArrayElementNode} A node representing the element access.
  21042. */
  21043. element( indexNode ) {
  21044. return storageElement( this, indexNode );
  21045. }
  21046. /**
  21047. * Defines whether this node is a PBO or not. Only relevant for WebGL.
  21048. *
  21049. * @param {Boolean} value - The value so set.
  21050. * @return {StorageBufferNode} A reference to this node.
  21051. */
  21052. setPBO( value ) {
  21053. this.isPBO = value;
  21054. return this;
  21055. }
  21056. /**
  21057. * Returns the `isPBO` value.
  21058. *
  21059. * @return {Boolean} Whether the node represents a PBO or not.
  21060. */
  21061. getPBO() {
  21062. return this.isPBO;
  21063. }
  21064. /**
  21065. * Defines the node access.
  21066. *
  21067. * @param {String} value - The node access.
  21068. * @return {StorageBufferNode} A reference to this node.
  21069. */
  21070. setAccess( value ) {
  21071. this.access = value;
  21072. return this;
  21073. }
  21074. /**
  21075. * Convenience method for configuring a read-only node access.
  21076. *
  21077. * @return {StorageBufferNode} A reference to this node.
  21078. */
  21079. toReadOnly() {
  21080. return this.setAccess( NodeAccess.READ_ONLY );
  21081. }
  21082. /**
  21083. * Defines whether the node is atomic or not.
  21084. *
  21085. * @param {Boolean} value - The atomic flag.
  21086. * @return {StorageBufferNode} A reference to this node.
  21087. */
  21088. setAtomic( value ) {
  21089. this.isAtomic = value;
  21090. return this;
  21091. }
  21092. /**
  21093. * Convenience method for making this node atomic.
  21094. *
  21095. * @return {StorageBufferNode} A reference to this node.
  21096. */
  21097. toAtomic() {
  21098. return this.setAtomic( true );
  21099. }
  21100. /**
  21101. * Returns attribute data for this storage buffer node.
  21102. *
  21103. * @return {{attribute: BufferAttributeNode, varying: VaryingNode}} The attribute data.
  21104. */
  21105. getAttributeData() {
  21106. if ( this._attribute === null ) {
  21107. this._attribute = bufferAttribute( this.value );
  21108. this._varying = varying( this._attribute );
  21109. }
  21110. return {
  21111. attribute: this._attribute,
  21112. varying: this._varying
  21113. };
  21114. }
  21115. /**
  21116. * This method is overwritten since the node type from the availability of storage buffers
  21117. * and the attribute data.
  21118. *
  21119. * @param {NodeBuilder} builder - The current node builder.
  21120. * @return {String} The node type.
  21121. */
  21122. getNodeType( builder ) {
  21123. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  21124. return super.getNodeType( builder );
  21125. }
  21126. const { attribute } = this.getAttributeData();
  21127. return attribute.getNodeType( builder );
  21128. }
  21129. /**
  21130. * Generates the code snippet of the storage buffer node.
  21131. *
  21132. * @param {NodeBuilder} builder - The current node builder.
  21133. * @return {String} The generated code snippet.
  21134. */
  21135. generate( builder ) {
  21136. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  21137. return super.generate( builder );
  21138. }
  21139. const { attribute, varying } = this.getAttributeData();
  21140. const output = varying.build( builder );
  21141. builder.registerTransform( output, attribute );
  21142. return output;
  21143. }
  21144. }
  21145. /**
  21146. * TSL function for creating a storage buffer node.
  21147. *
  21148. * @function
  21149. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  21150. * @param {String?} [type=null] - The buffer type (e.g. `'vec3'`).
  21151. * @param {Number} [count=0] - The buffer count.
  21152. * @returns {StorageBufferNode}
  21153. */
  21154. const storage = ( value, type = null, count = 0 ) => nodeObject( new StorageBufferNode( value, type, count ) );
  21155. /**
  21156. * @function
  21157. * @deprecated since r171. Use `storage().setPBO( true )` instead.
  21158. *
  21159. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  21160. * @param {String?} type - The buffer type (e.g. `'vec3'`).
  21161. * @param {Number} count - The buffer count.
  21162. * @returns {StorageBufferNode}
  21163. */
  21164. const storageObject = ( value, type, count ) => { // @deprecated, r171
  21165. console.warn( 'THREE.TSL: "storageObject()" is deprecated. Use "storage().setPBO( true )" instead.' );
  21166. return storage( value, type, count ).setPBO( true );
  21167. };
  21168. /** @module Arrays **/
  21169. /**
  21170. * TSL function for creating a storage buffer node with a configured `StorageBufferAttribute`.
  21171. *
  21172. * @function
  21173. * @param {Number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  21174. * @param {String} [type='float'] - The data type.
  21175. * @returns {StorageBufferNode}
  21176. */
  21177. const attributeArray = ( count, type = 'float' ) => {
  21178. const itemSize = getLengthFromType( type );
  21179. const typedArray = getTypedArrayFromType( type );
  21180. const buffer = new StorageBufferAttribute( count, itemSize, typedArray );
  21181. const node = storage( buffer, type, count );
  21182. return node;
  21183. };
  21184. /**
  21185. * TSL function for creating a storage buffer node with a configured `StorageInstancedBufferAttribute`.
  21186. *
  21187. * @function
  21188. * @param {Number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  21189. * @param {String} [type='float'] - The data type.
  21190. * @returns {StorageBufferNode}
  21191. */
  21192. const instancedArray = ( count, type = 'float' ) => {
  21193. const itemSize = getLengthFromType( type );
  21194. const typedArray = getTypedArrayFromType( type );
  21195. const buffer = new StorageInstancedBufferAttribute( count, itemSize, typedArray );
  21196. const node = storage( buffer, type, count );
  21197. return node;
  21198. };
  21199. /** @module VertexColorNode **/
  21200. /**
  21201. * An attribute node for representing vertex colors.
  21202. *
  21203. * @augments module:AttributeNode~AttributeNode
  21204. */
  21205. class VertexColorNode extends AttributeNode {
  21206. static get type() {
  21207. return 'VertexColorNode';
  21208. }
  21209. /**
  21210. * Constructs a new vertex color node.
  21211. *
  21212. * @param {Number} [index=0] - The attribute index.
  21213. */
  21214. constructor( index = 0 ) {
  21215. super( null, 'vec4' );
  21216. /**
  21217. * This flag can be used for type testing.
  21218. *
  21219. * @type {Boolean}
  21220. * @readonly
  21221. * @default true
  21222. */
  21223. this.isVertexColorNode = true;
  21224. /**
  21225. * The attribute index to enable more than one sets of vertex colors.
  21226. *
  21227. * @type {Number}
  21228. * @default 0
  21229. */
  21230. this.index = index;
  21231. }
  21232. /**
  21233. * Overwrites the default implementation by honoring the attribute index.
  21234. *
  21235. * @param {NodeBuilder} builder - The current node builder.
  21236. * @return {String} The attribute name.
  21237. */
  21238. getAttributeName( /*builder*/ ) {
  21239. const index = this.index;
  21240. return 'color' + ( index > 0 ? index : '' );
  21241. }
  21242. generate( builder ) {
  21243. const attributeName = this.getAttributeName( builder );
  21244. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  21245. let result;
  21246. if ( geometryAttribute === true ) {
  21247. result = super.generate( builder );
  21248. } else {
  21249. // Vertex color fallback should be white
  21250. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  21251. }
  21252. return result;
  21253. }
  21254. serialize( data ) {
  21255. super.serialize( data );
  21256. data.index = this.index;
  21257. }
  21258. deserialize( data ) {
  21259. super.deserialize( data );
  21260. this.index = data.index;
  21261. }
  21262. }
  21263. /**
  21264. * TSL function for creating a reference node.
  21265. *
  21266. * @function
  21267. * @param {Number} index - The attribute index.
  21268. * @returns {VertexColorNode}
  21269. */
  21270. const vertexColor = ( index ) => nodeObject( new VertexColorNode( index ) );
  21271. /** @module PointUVNode **/
  21272. /**
  21273. * A node for representing the uv coordinates of points.
  21274. *
  21275. * Can only be used with a WebGL backend. In WebGPU, point
  21276. * primitives always have the size of one pixel and can thus
  21277. * can't be used as sprite-like objects that display textures.
  21278. *
  21279. * @augments Node
  21280. */
  21281. class PointUVNode extends Node {
  21282. static get type() {
  21283. return 'PointUVNode';
  21284. }
  21285. /**
  21286. * Constructs a new point uv node.
  21287. */
  21288. constructor() {
  21289. super( 'vec2' );
  21290. /**
  21291. * This flag can be used for type testing.
  21292. *
  21293. * @type {Boolean}
  21294. * @readonly
  21295. * @default true
  21296. */
  21297. this.isPointUVNode = true;
  21298. }
  21299. generate( /*builder*/ ) {
  21300. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  21301. }
  21302. }
  21303. /**
  21304. * TSL object that represents the uv coordinates of points.
  21305. *
  21306. * @type {PointUVNode}
  21307. */
  21308. const pointUV = /*@__PURE__*/ nodeImmutable( PointUVNode );
  21309. const _e1 = /*@__PURE__*/ new Euler();
  21310. const _m1 = /*@__PURE__*/ new Matrix4();
  21311. /** @module SceneNode **/
  21312. /**
  21313. * This module allows access to a collection of scene properties. The following predefined TSL objects
  21314. * are available for easier use:
  21315. *
  21316. * - `backgroundBlurriness`: A node that represents the scene's background blurriness.
  21317. * - `backgroundIntensity`: A node that represents the scene's background intensity.
  21318. * - `backgroundRotation`: A node that represents the scene's background rotation.
  21319. *
  21320. * @augments Node
  21321. */
  21322. class SceneNode extends Node {
  21323. static get type() {
  21324. return 'SceneNode';
  21325. }
  21326. /**
  21327. * Constructs a new scene node.
  21328. *
  21329. * @param {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')} scope - The scope defines the type of scene property that is accessed.
  21330. * @param {Scene?} [scene=null] - A reference to the scene.
  21331. */
  21332. constructor( scope = SceneNode.BACKGROUND_BLURRINESS, scene = null ) {
  21333. super();
  21334. /**
  21335. * The scope defines the type of scene property that is accessed.
  21336. *
  21337. * @type {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')}
  21338. */
  21339. this.scope = scope;
  21340. /**
  21341. * A reference to the scene that is going to be accessed.
  21342. *
  21343. * @type {Scene?}
  21344. * @default null
  21345. */
  21346. this.scene = scene;
  21347. }
  21348. /**
  21349. * Depending on the scope, the method returns a different type of node that represents
  21350. * the respective scene property.
  21351. *
  21352. * @param {NodeBuilder} builder - The current node builder.
  21353. * @return {Node} The output node.
  21354. */
  21355. setup( builder ) {
  21356. const scope = this.scope;
  21357. const scene = this.scene !== null ? this.scene : builder.scene;
  21358. let output;
  21359. if ( scope === SceneNode.BACKGROUND_BLURRINESS ) {
  21360. output = reference( 'backgroundBlurriness', 'float', scene );
  21361. } else if ( scope === SceneNode.BACKGROUND_INTENSITY ) {
  21362. output = reference( 'backgroundIntensity', 'float', scene );
  21363. } else if ( scope === SceneNode.BACKGROUND_ROTATION ) {
  21364. output = uniform( 'mat4' ).label( 'backgroundRotation' ).setGroup( renderGroup ).onRenderUpdate( () => {
  21365. const background = scene.background;
  21366. if ( background !== null && background.isTexture && background.mapping !== UVMapping ) {
  21367. _e1.copy( scene.backgroundRotation );
  21368. // accommodate left-handed frame
  21369. _e1.x *= -1; _e1.y *= -1; _e1.z *= -1;
  21370. _m1.makeRotationFromEuler( _e1 );
  21371. } else {
  21372. _m1.identity();
  21373. }
  21374. return _m1;
  21375. } );
  21376. } else {
  21377. console.error( 'THREE.SceneNode: Unknown scope:', scope );
  21378. }
  21379. return output;
  21380. }
  21381. }
  21382. SceneNode.BACKGROUND_BLURRINESS = 'backgroundBlurriness';
  21383. SceneNode.BACKGROUND_INTENSITY = 'backgroundIntensity';
  21384. SceneNode.BACKGROUND_ROTATION = 'backgroundRotation';
  21385. /**
  21386. * TSL object that represents the scene's background blurriness.
  21387. *
  21388. * @type {SceneNode}
  21389. */
  21390. const backgroundBlurriness = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_BLURRINESS );
  21391. /**
  21392. * TSL object that represents the scene's background intensity.
  21393. *
  21394. * @type {SceneNode}
  21395. */
  21396. const backgroundIntensity = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_INTENSITY );
  21397. /**
  21398. * TSL object that represents the scene's background rotation.
  21399. *
  21400. * @type {SceneNode}
  21401. */
  21402. const backgroundRotation = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_ROTATION );
  21403. /** @module StorageTextureNode **/
  21404. /**
  21405. * This special version of a texture node can be used to
  21406. * write data into a storage texture with a compute shader.
  21407. *
  21408. * ```js
  21409. * const storageTexture = new THREE.StorageTexture( width, height );
  21410. *
  21411. * const computeTexture = Fn( ( { storageTexture } ) => {
  21412. *
  21413. * const posX = instanceIndex.modInt( width );
  21414. * const posY = instanceIndex.div( width );
  21415. * const indexUV = uvec2( posX, posY );
  21416. *
  21417. * // generate RGB values
  21418. *
  21419. * const r = 1;
  21420. * const g = 1;
  21421. * const b = 1;
  21422. *
  21423. * textureStore( storageTexture, indexUV, vec4( r, g, b, 1 ) ).toWriteOnly();
  21424. *
  21425. * } );
  21426. *
  21427. * const computeNode = computeTexture( { storageTexture } ).compute( width * height );
  21428. * renderer.computeAsync( computeNode );
  21429. * ```
  21430. *
  21431. * This node can only be used with a WebGPU backend.
  21432. *
  21433. * @augments module:TextureNode~TextureNode
  21434. */
  21435. class StorageTextureNode extends TextureNode {
  21436. static get type() {
  21437. return 'StorageTextureNode';
  21438. }
  21439. /**
  21440. * Constructs a new storage texture node.
  21441. *
  21442. * @param {StorageTexture} value - The storage texture.
  21443. * @param {Node<vec2|vec3>} uvNode - The uv node.
  21444. * @param {Node?} [storeNode=null] - The value node that should be stored in the texture.
  21445. */
  21446. constructor( value, uvNode, storeNode = null ) {
  21447. super( value, uvNode );
  21448. /**
  21449. * The value node that should be stored in the texture.
  21450. *
  21451. * @type {Node?}
  21452. * @default null
  21453. */
  21454. this.storeNode = storeNode;
  21455. /**
  21456. * This flag can be used for type testing.
  21457. *
  21458. * @type {Boolean}
  21459. * @readonly
  21460. * @default true
  21461. */
  21462. this.isStorageTextureNode = true;
  21463. /**
  21464. * The access type of the texture node.
  21465. *
  21466. * @type {String}
  21467. * @default 'writeOnly'
  21468. */
  21469. this.access = NodeAccess.WRITE_ONLY;
  21470. }
  21471. /**
  21472. * Overwrites the default implementation to return a fixed value `'storageTexture'`.
  21473. *
  21474. * @param {NodeBuilder} builder - The current node builder.
  21475. * @return {String} The input type.
  21476. */
  21477. getInputType( /*builder*/ ) {
  21478. return 'storageTexture';
  21479. }
  21480. setup( builder ) {
  21481. super.setup( builder );
  21482. const properties = builder.getNodeProperties( this );
  21483. properties.storeNode = this.storeNode;
  21484. }
  21485. /**
  21486. * Defines the node access.
  21487. *
  21488. * @param {String} value - The node access.
  21489. * @return {StorageTextureNode} A reference to this node.
  21490. */
  21491. setAccess( value ) {
  21492. this.access = value;
  21493. return this;
  21494. }
  21495. /**
  21496. * Generates the code snippet of the stroge node. If no `storeNode`
  21497. * is defined, the texture node is generated as normal texture.
  21498. *
  21499. * @param {NodeBuilder} builder - The current node builder.
  21500. * @param {String} output - The current output.
  21501. * @return {String} The generated code snippet.
  21502. */
  21503. generate( builder, output ) {
  21504. let snippet;
  21505. if ( this.storeNode !== null ) {
  21506. snippet = this.generateStore( builder );
  21507. } else {
  21508. snippet = super.generate( builder, output );
  21509. }
  21510. return snippet;
  21511. }
  21512. /**
  21513. * Convenience method for configuring a read/write node access.
  21514. *
  21515. * @return {StorageTextureNode} A reference to this node.
  21516. */
  21517. toReadWrite() {
  21518. return this.setAccess( NodeAccess.READ_WRITE );
  21519. }
  21520. /**
  21521. * Convenience method for configuring a read-only node access.
  21522. *
  21523. * @return {StorageTextureNode} A reference to this node.
  21524. */
  21525. toReadOnly() {
  21526. return this.setAccess( NodeAccess.READ_ONLY );
  21527. }
  21528. /**
  21529. * Convenience method for configuring a write-only node access.
  21530. *
  21531. * @return {StorageTextureNode} A reference to this node.
  21532. */
  21533. toWriteOnly() {
  21534. return this.setAccess( NodeAccess.WRITE_ONLY );
  21535. }
  21536. /**
  21537. * Generates the code snippet of the storage texture node.
  21538. *
  21539. * @param {NodeBuilder} builder - The current node builder.
  21540. */
  21541. generateStore( builder ) {
  21542. const properties = builder.getNodeProperties( this );
  21543. const { uvNode, storeNode } = properties;
  21544. const textureProperty = super.generate( builder, 'property' );
  21545. const uvSnippet = uvNode.build( builder, 'uvec2' );
  21546. const storeSnippet = storeNode.build( builder, 'vec4' );
  21547. const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, storeSnippet );
  21548. builder.addLineFlowCode( snippet, this );
  21549. }
  21550. }
  21551. /**
  21552. * TSL function for creating a storage texture node.
  21553. *
  21554. * @function
  21555. * @param {StorageTexture} value - The storage texture.
  21556. * @param {Node<vec2|vec3>} uvNode - The uv node.
  21557. * @param {Node?} [storeNode=null] - The value node that should be stored in the texture.
  21558. * @returns {StorageTextureNode}
  21559. */
  21560. const storageTexture = /*@__PURE__*/ nodeProxy( StorageTextureNode );
  21561. /**
  21562. * TODO: Explain difference to `storageTexture()`.
  21563. *
  21564. * @function
  21565. * @param {StorageTexture} value - The storage texture.
  21566. * @param {Node<vec2|vec3>} uvNode - The uv node.
  21567. * @param {Node?} [storeNode=null] - The value node that should be stored in the texture.
  21568. * @returns {StorageTextureNode}
  21569. */
  21570. const textureStore = ( value, uvNode, storeNode ) => {
  21571. const node = storageTexture( value, uvNode, storeNode );
  21572. if ( storeNode !== null ) node.append();
  21573. return node;
  21574. };
  21575. /** @module UserDataNode **/
  21576. /**
  21577. * A special type of reference node that allows to link values in
  21578. * `userData` fields to node objects.
  21579. * ```js
  21580. * sprite.userData.rotation = 1; // stores individual rotation per sprite
  21581. *
  21582. * const material = new THREE.SpriteNodeMaterial();
  21583. * material.rotationNode = userData( 'rotation', 'float' );
  21584. * ```
  21585. * Since `UserDataNode` is extended from {@link module:ReferenceNode~ReferenceNode}, the node value
  21586. * will automatically be updated when the `rotation` user data field changes.
  21587. *
  21588. * @augments module:ReferenceNode~ReferenceNode
  21589. */
  21590. class UserDataNode extends ReferenceNode {
  21591. static get type() {
  21592. return 'UserDataNode';
  21593. }
  21594. /**
  21595. * Constructs a new user data node.
  21596. *
  21597. * @param {String} property - The property name that should be referenced by the node.
  21598. * @param {String} inputType - The node data type of the reference.
  21599. * @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.
  21600. */
  21601. constructor( property, inputType, userData = null ) {
  21602. super( property, inputType, userData );
  21603. /**
  21604. * A reference to the `userData` object. If not provided, the `userData`
  21605. * property of the 3D object that uses the node material is evaluated.
  21606. *
  21607. * @type {Object?}
  21608. * @default null
  21609. */
  21610. this.userData = userData;
  21611. }
  21612. /**
  21613. * Overwritten to make sure {@link module:ReferenceNode~ReferenceNode#reference} points to the correct
  21614. * `userData` field.
  21615. *
  21616. * @param {(NodeFrame|NodeBuilder)} state - The current state to evaluate.
  21617. * @return {Object} A reference to the `userData` field.
  21618. */
  21619. updateReference( state ) {
  21620. this.reference = this.userData !== null ? this.userData : state.object.userData;
  21621. return this.reference;
  21622. }
  21623. }
  21624. /**
  21625. * TSL function for creating a user data node.
  21626. *
  21627. * @function
  21628. * @param {String} name - The property name that should be referenced by the node.
  21629. * @param {String} inputType - The node data type of the reference.
  21630. * @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.
  21631. * @returns {UserDataNode}
  21632. */
  21633. const userData = ( name, inputType, userData ) => nodeObject( new UserDataNode( name, inputType, userData ) );
  21634. const _objectData = new WeakMap();
  21635. /** @module VelocityNode **/
  21636. /**
  21637. * A node for representing motion or velocity vectors. Foundation
  21638. * for advanced post processing effects like motion blur or TRAA.
  21639. *
  21640. * The node keeps track of the model, view and projection matrices
  21641. * of the previous frame and uses them to compute offsets in NDC space.
  21642. * These offsets represent the final velocity.
  21643. *
  21644. * @augments TempNode
  21645. */
  21646. class VelocityNode extends TempNode {
  21647. static get type() {
  21648. return 'VelocityNode';
  21649. }
  21650. /**
  21651. * Constructs a new vertex color node.
  21652. */
  21653. constructor() {
  21654. super( 'vec2' );
  21655. /**
  21656. * The current projection matrix.
  21657. *
  21658. * @type {Matrix4?}
  21659. * @default null
  21660. */
  21661. this.projectionMatrix = null;
  21662. /**
  21663. * Overwritten since velocity nodes are updated per object.
  21664. *
  21665. * @type {String}
  21666. * @default 'object'
  21667. */
  21668. this.updateType = NodeUpdateType.OBJECT;
  21669. /**
  21670. * Overwritten since velocity nodes save data after the update.
  21671. *
  21672. * @type {String}
  21673. * @default 'object'
  21674. */
  21675. this.updateAfterType = NodeUpdateType.OBJECT;
  21676. /**
  21677. * Uniform node representing the previous model matrix in world space.
  21678. *
  21679. * @type {UniformNode<mat4>}
  21680. * @default null
  21681. */
  21682. this.previousModelWorldMatrix = uniform( new Matrix4() );
  21683. /**
  21684. * Uniform node representing the previous projection matrix.
  21685. *
  21686. * @type {UniformNode<mat4>}
  21687. * @default null
  21688. */
  21689. this.previousProjectionMatrix = uniform( new Matrix4() ).setGroup( renderGroup );
  21690. /**
  21691. * Uniform node representing the previous view matrix.
  21692. *
  21693. * @type {UniformNode<mat4>}
  21694. * @default null
  21695. */
  21696. this.previousCameraViewMatrix = uniform( new Matrix4() );
  21697. }
  21698. /**
  21699. * Sets the given projection matrix.
  21700. *
  21701. * @param {Matrix4} projectionMatrix - The projection matrix to set.
  21702. */
  21703. setProjectionMatrix( projectionMatrix ) {
  21704. this.projectionMatrix = projectionMatrix;
  21705. }
  21706. /**
  21707. * Updates velocity specific uniforms.
  21708. *
  21709. * @param {NodeFrame} frame - A reference to the current node frame.
  21710. */
  21711. update( { frameId, camera, object } ) {
  21712. const previousModelMatrix = getPreviousMatrix( object );
  21713. this.previousModelWorldMatrix.value.copy( previousModelMatrix );
  21714. //
  21715. const cameraData = getData( camera );
  21716. if ( cameraData.frameId !== frameId ) {
  21717. cameraData.frameId = frameId;
  21718. if ( cameraData.previousProjectionMatrix === undefined ) {
  21719. cameraData.previousProjectionMatrix = new Matrix4();
  21720. cameraData.previousCameraViewMatrix = new Matrix4();
  21721. cameraData.currentProjectionMatrix = new Matrix4();
  21722. cameraData.currentCameraViewMatrix = new Matrix4();
  21723. cameraData.previousProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  21724. cameraData.previousCameraViewMatrix.copy( camera.matrixWorldInverse );
  21725. } else {
  21726. cameraData.previousProjectionMatrix.copy( cameraData.currentProjectionMatrix );
  21727. cameraData.previousCameraViewMatrix.copy( cameraData.currentCameraViewMatrix );
  21728. }
  21729. cameraData.currentProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  21730. cameraData.currentCameraViewMatrix.copy( camera.matrixWorldInverse );
  21731. this.previousProjectionMatrix.value.copy( cameraData.previousProjectionMatrix );
  21732. this.previousCameraViewMatrix.value.copy( cameraData.previousCameraViewMatrix );
  21733. }
  21734. }
  21735. /**
  21736. * Overwritten to updated velocity specific uniforms.
  21737. *
  21738. * @param {NodeFrame} frame - A reference to the current node frame.
  21739. */
  21740. updateAfter( { object } ) {
  21741. getPreviousMatrix( object ).copy( object.matrixWorld );
  21742. }
  21743. /**
  21744. * Implements the velocity computation based on the previous and current vertex data.
  21745. *
  21746. * @param {NodeBuilder} builder - A reference to the current node builder.
  21747. * @return {Node<vec2>} The motion vector.
  21748. */
  21749. setup( /*builder*/ ) {
  21750. const projectionMatrix = ( this.projectionMatrix === null ) ? cameraProjectionMatrix : uniform( this.projectionMatrix );
  21751. const previousModelViewMatrix = this.previousCameraViewMatrix.mul( this.previousModelWorldMatrix );
  21752. const clipPositionCurrent = projectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  21753. const clipPositionPrevious = this.previousProjectionMatrix.mul( previousModelViewMatrix ).mul( positionPrevious );
  21754. const ndcPositionCurrent = clipPositionCurrent.xy.div( clipPositionCurrent.w );
  21755. const ndcPositionPrevious = clipPositionPrevious.xy.div( clipPositionPrevious.w );
  21756. const velocity = sub( ndcPositionCurrent, ndcPositionPrevious );
  21757. return velocity;
  21758. }
  21759. }
  21760. function getData( object ) {
  21761. let objectData = _objectData.get( object );
  21762. if ( objectData === undefined ) {
  21763. objectData = {};
  21764. _objectData.set( object, objectData );
  21765. }
  21766. return objectData;
  21767. }
  21768. function getPreviousMatrix( object, index = 0 ) {
  21769. const objectData = getData( object );
  21770. let matrix = objectData[ index ];
  21771. if ( matrix === undefined ) {
  21772. objectData[ index ] = matrix = new Matrix4();
  21773. }
  21774. return matrix;
  21775. }
  21776. /**
  21777. * TSL object that represents the velocity of a render pass.
  21778. *
  21779. * @type {VelocityNode}
  21780. */
  21781. const velocity = /*@__PURE__*/ nodeImmutable( VelocityNode );
  21782. /** @module BlendModes **/
  21783. /**
  21784. * Represents a "Color Burn" blend mode.
  21785. *
  21786. * It's designed to darken the base layer's colors based on the color of the blend layer.
  21787. * It significantly increases the contrast of the base layer, making the colors more vibrant and saturated.
  21788. * The darker the color in the blend layer, the stronger the darkening and contrast effect on the base layer.
  21789. *
  21790. * @method
  21791. * @param {Node<vec3>} base - The base color.
  21792. * @param {Node<vec3>} blend - The blend color. A white (#ffffff) blend color does not alter the base color.
  21793. * @return {Node<vec3>} The result.
  21794. */
  21795. const blendBurn = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  21796. return min$1( 1.0, base.oneMinus().div( blend ) ).oneMinus();
  21797. } ).setLayout( {
  21798. name: 'blendBurn',
  21799. type: 'vec3',
  21800. inputs: [
  21801. { name: 'base', type: 'vec3' },
  21802. { name: 'blend', type: 'vec3' }
  21803. ]
  21804. } );
  21805. /**
  21806. * Represents a "Color Dodge" blend mode.
  21807. *
  21808. * It's designed to lighten the base layer's colors based on the color of the blend layer.
  21809. * It significantly increases the brightness of the base layer, making the colors lighter and more vibrant.
  21810. * The brighter the color in the blend layer, the stronger the lightening and contrast effect on the base layer.
  21811. *
  21812. * @method
  21813. * @param {Node<vec3>} base - The base color.
  21814. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  21815. * @return {Node<vec3>} The result.
  21816. */
  21817. const blendDodge = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  21818. return min$1( base.div( blend.oneMinus() ), 1.0 );
  21819. } ).setLayout( {
  21820. name: 'blendDodge',
  21821. type: 'vec3',
  21822. inputs: [
  21823. { name: 'base', type: 'vec3' },
  21824. { name: 'blend', type: 'vec3' }
  21825. ]
  21826. } );
  21827. /**
  21828. * Represents a "Screen" blend mode.
  21829. *
  21830. * Similar to `blendDodge()`, this mode also lightens the base layer's colors based on the color of the blend layer.
  21831. * The "Screen" blend mode is better for general brightening whereas the "Dodge" results in more subtle and nuanced
  21832. * effects.
  21833. *
  21834. * @method
  21835. * @param {Node<vec3>} base - The base color.
  21836. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  21837. * @return {Node<vec3>} The result.
  21838. */
  21839. const blendScreen = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  21840. return base.oneMinus().mul( blend.oneMinus() ).oneMinus();
  21841. } ).setLayout( {
  21842. name: 'blendScreen',
  21843. type: 'vec3',
  21844. inputs: [
  21845. { name: 'base', type: 'vec3' },
  21846. { name: 'blend', type: 'vec3' }
  21847. ]
  21848. } );
  21849. /**
  21850. * Represents a "Overlay" blend mode.
  21851. *
  21852. * It's designed to increase the contrast of the base layer based on the color of the blend layer.
  21853. * It amplifies the existing colors and contrast in the base layer, making lighter areas lighter and darker areas darker.
  21854. * The color of the blend layer significantly influences the resulting contrast and color shift in the base layer.
  21855. *
  21856. * @method
  21857. * @param {Node<vec3>} base - The base color.
  21858. * @param {Node<vec3>} blend - The blend color
  21859. * @return {Node<vec3>} The result.
  21860. */
  21861. const blendOverlay = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  21862. return mix( base.mul( 2.0 ).mul( blend ), base.oneMinus().mul( 2.0 ).mul( blend.oneMinus() ).oneMinus(), step( 0.5, base ) );
  21863. } ).setLayout( {
  21864. name: 'blendOverlay',
  21865. type: 'vec3',
  21866. inputs: [
  21867. { name: 'base', type: 'vec3' },
  21868. { name: 'blend', type: 'vec3' }
  21869. ]
  21870. } );
  21871. /**
  21872. * This function blends two color based on their alpha values by replicating the behavior of `THREE.NormalBlending`.
  21873. * It assumes both input colors have non-preumiltiplied alpha.
  21874. *
  21875. * @method
  21876. * @param {Node<vec4>} base - The base color.
  21877. * @param {Node<vec4>} blend - The blend color
  21878. * @return {Node<vec4>} The result.
  21879. */
  21880. const blendColor = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  21881. const outAlpha = blend.a.add( base.a.mul( blend.a.oneMinus() ) );
  21882. return vec4( blend.rgb.mul( blend.a ).add( base.rgb.mul( base.a ).mul( blend.a.oneMinus() ) ).div( outAlpha ), outAlpha );
  21883. } ).setLayout( {
  21884. name: 'blendColor',
  21885. type: 'vec4',
  21886. inputs: [
  21887. { name: 'base', type: 'vec4' },
  21888. { name: 'blend', type: 'vec4' }
  21889. ]
  21890. } );
  21891. // Deprecated
  21892. /**
  21893. * @function
  21894. * @deprecated since r171. Use {@link blendBurn} instead.
  21895. *
  21896. * @param {...any} params
  21897. * @returns {Function}
  21898. */
  21899. const burn = ( ...params ) => { // @deprecated, r171
  21900. console.warn( 'THREE.TSL: "burn" has been renamed. Use "blendBurn" instead.' );
  21901. return blendBurn( params );
  21902. };
  21903. /**
  21904. * @function
  21905. * @deprecated since r171. Use {@link blendDodge} instead.
  21906. *
  21907. * @param {...any} params
  21908. * @returns {Function}
  21909. */
  21910. const dodge = ( ...params ) => { // @deprecated, r171
  21911. console.warn( 'THREE.TSL: "dodge" has been renamed. Use "blendDodge" instead.' );
  21912. return blendDodge( params );
  21913. };
  21914. /**
  21915. * @method
  21916. * @deprecated since r171. Use {@link blendScreen} instead.
  21917. *
  21918. * @param {...any} params
  21919. * @returns {Function}
  21920. */
  21921. const screen = ( ...params ) => { // @deprecated, r171
  21922. console.warn( 'THREE.TSL: "screen" has been renamed. Use "blendScreen" instead.' );
  21923. return blendScreen( params );
  21924. };
  21925. /**
  21926. * @method
  21927. * @deprecated since r171. Use {@link blendOverlay} instead.
  21928. *
  21929. * @param {...any} params
  21930. * @returns {Function}
  21931. */
  21932. const overlay = ( ...params ) => { // @deprecated, r171
  21933. console.warn( 'THREE.TSL: "overlay" has been renamed. Use "blendOverlay" instead.' );
  21934. return blendOverlay( params );
  21935. };
  21936. /** @module ColorAdjustment **/
  21937. /**
  21938. * Computes a grayscale value for the given RGB color value.
  21939. *
  21940. * @method
  21941. * @param {Node<vec3>} color - The color value to compute the grayscale for.
  21942. * @return {Node<vec3>} The grayscale color.
  21943. */
  21944. const grayscale = /*@__PURE__*/ Fn( ( [ color ] ) => {
  21945. return luminance( color.rgb );
  21946. } );
  21947. /**
  21948. * Super-saturates or desaturates the given RGB color.
  21949. *
  21950. * @method
  21951. * @param {Node<vec3>} color - The input color.
  21952. * @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.
  21953. * @return {Node<vec3>} The saturated color.
  21954. */
  21955. const saturation = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  21956. return adjustment.mix( luminance( color.rgb ), color.rgb );
  21957. } );
  21958. /**
  21959. * Selectively enhance the intensity of less saturated RGB colors. Can result
  21960. * in a more natural and visually appealing image with enhanced color depth
  21961. * compared to {@link ColorAdjustment#saturation}.
  21962. *
  21963. * @method
  21964. * @param {Node<vec3>} color - The input color.
  21965. * @param {Node<float>} [adjustment=1] - Controls the intensity of the vibrance effect.
  21966. * @return {Node<vec3>} The updated color.
  21967. */
  21968. const vibrance = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  21969. const average = add( color.r, color.g, color.b ).div( 3.0 );
  21970. const mx = color.r.max( color.g.max( color.b ) );
  21971. const amt = mx.sub( average ).mul( adjustment ).mul( -3 );
  21972. return mix( color.rgb, mx, amt );
  21973. } );
  21974. /**
  21975. * Updates the hue component of the given RGB color while preserving its luminance and saturation.
  21976. *
  21977. * @method
  21978. * @param {Node<vec3>} color - The input color.
  21979. * @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.
  21980. * @return {Node<vec3>} The updated color.
  21981. */
  21982. const hue = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  21983. const k = vec3( 0.57735, 0.57735, 0.57735 );
  21984. const cosAngle = adjustment.cos();
  21985. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) );
  21986. } );
  21987. /**
  21988. * Computes the luminance for the given RGB color value.
  21989. *
  21990. * @method
  21991. * @param {Node<vec3>} color - The color value to compute the luminance for.
  21992. * @param {Node<vec3>?} luminanceCoefficients - The luminance coefficients. By default predefined values of the current working color space are used.
  21993. * @return {Node<vec3>} The luminance.
  21994. */
  21995. const luminance = (
  21996. color,
  21997. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3() ) )
  21998. ) => dot( color, luminanceCoefficients );
  21999. /**
  22000. * Color Decision List (CDL) v1.2
  22001. *
  22002. * Compact representation of color grading information, defined by slope, offset, power, and
  22003. * saturation. The CDL should be typically be given input in a log space (such as LogC, ACEScc,
  22004. * or AgX Log), and will return output in the same space. Output may require clamping >=0.
  22005. *
  22006. * @method
  22007. * @param {Node<vec4>} color Input (-Infinity < input < +Infinity)
  22008. * @param {Node<vec3>} slope Slope (0 ≤ slope < +Infinity)
  22009. * @param {Node<vec3>} offset Offset (-Infinity < offset < +Infinity; typically -1 < offset < 1)
  22010. * @param {Node<vec3>} power Power (0 < power < +Infinity)
  22011. * @param {Node<float>} saturation Saturation (0 ≤ saturation < +Infinity; typically 0 ≤ saturation < 4)
  22012. * @param {Node<vec3>} luminanceCoefficients Luminance coefficients for saturation term, typically Rec. 709
  22013. * @return {Node<vec4>} Output, -Infinity < output < +Infinity
  22014. *
  22015. * References:
  22016. * - ASC CDL v1.2
  22017. * - {@link https://blender.stackexchange.com/a/55239/43930}
  22018. * - {@link https://docs.acescentral.com/specifications/acescc/}
  22019. */
  22020. const cdl = /*@__PURE__*/ Fn( ( [
  22021. color,
  22022. slope = vec3( 1 ),
  22023. offset = vec3( 0 ),
  22024. power = vec3( 1 ),
  22025. saturation = float( 1 ),
  22026. // ASC CDL v1.2 explicitly requires Rec. 709 luminance coefficients.
  22027. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3(), LinearSRGBColorSpace ) )
  22028. ] ) => {
  22029. // NOTE: The ASC CDL v1.2 defines a [0, 1] clamp on the slope+offset term, and another on the
  22030. // saturation term. Per the ACEScc specification and Filament, limits may be omitted to support
  22031. // values outside [0, 1], requiring a workaround for negative values in the power expression.
  22032. const luma = color.rgb.dot( vec3( luminanceCoefficients ) );
  22033. const v = max$1( color.rgb.mul( slope ).add( offset ), 0.0 ).toVar();
  22034. const pv = v.pow( power ).toVar();
  22035. If( v.r.greaterThan( 0.0 ), () => { v.r.assign( pv.r ); } ); // eslint-disable-line
  22036. If( v.g.greaterThan( 0.0 ), () => { v.g.assign( pv.g ); } ); // eslint-disable-line
  22037. If( v.b.greaterThan( 0.0 ), () => { v.b.assign( pv.b ); } ); // eslint-disable-line
  22038. v.assign( luma.add( v.sub( luma ).mul( saturation ) ) );
  22039. return vec4( v.rgb, color.a );
  22040. } );
  22041. /** @module PosterizeNode **/
  22042. /**
  22043. * Represents a posterize effect which reduces the number of colors
  22044. * in an image, resulting in a more blocky and stylized appearance.
  22045. *
  22046. * @augments TempNode
  22047. */
  22048. class PosterizeNode extends TempNode {
  22049. static get type() {
  22050. return 'PosterizeNode';
  22051. }
  22052. /**
  22053. * Constructs a new posterize node.
  22054. *
  22055. * @param {Node} sourceNode - The input color.
  22056. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  22057. */
  22058. constructor( sourceNode, stepsNode ) {
  22059. super();
  22060. /**
  22061. * The input color.
  22062. *
  22063. * @type {Node}
  22064. */
  22065. this.sourceNode = sourceNode;
  22066. /**
  22067. * Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  22068. *
  22069. * @type {Node}
  22070. */
  22071. this.stepsNode = stepsNode;
  22072. }
  22073. setup() {
  22074. const { sourceNode, stepsNode } = this;
  22075. return sourceNode.mul( stepsNode ).floor().div( stepsNode );
  22076. }
  22077. }
  22078. /**
  22079. * TSL function for creating a posterize node.
  22080. *
  22081. * @function
  22082. * @param {Node} sourceNode - The input color.
  22083. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  22084. * @returns {PosterizeNode}
  22085. */
  22086. const posterize = /*@__PURE__*/ nodeProxy( PosterizeNode );
  22087. /** @module PassNode **/
  22088. const _size = /*@__PURE__*/ new Vector2();
  22089. /**
  22090. * Represents the texture of a pass node.
  22091. *
  22092. * @augments module:TextureNode~TextureNode
  22093. */
  22094. class PassTextureNode extends TextureNode {
  22095. static get type() {
  22096. return 'PassTextureNode';
  22097. }
  22098. /**
  22099. * Constructs a new pass texture node.
  22100. *
  22101. * @param {PassNode} passNode - The pass node.
  22102. * @param {Texture} texture - The output texture.
  22103. */
  22104. constructor( passNode, texture ) {
  22105. super( texture );
  22106. /**
  22107. * A reference to the pass node.
  22108. *
  22109. * @type {PassNode}
  22110. */
  22111. this.passNode = passNode;
  22112. this.setUpdateMatrix( false );
  22113. }
  22114. setup( builder ) {
  22115. if ( builder.object.isQuadMesh ) this.passNode.build( builder );
  22116. return super.setup( builder );
  22117. }
  22118. clone() {
  22119. return new this.constructor( this.passNode, this.value );
  22120. }
  22121. }
  22122. /**
  22123. * An extension of `PassTextureNode` which allows to manage more than one
  22124. * internal texture. Relevant for the `getPreviousTexture()` related API.
  22125. *
  22126. * @augments module:PassTextureNode~PassTextureNode
  22127. */
  22128. class PassMultipleTextureNode extends PassTextureNode {
  22129. static get type() {
  22130. return 'PassMultipleTextureNode';
  22131. }
  22132. /**
  22133. * Constructs a new pass texture node.
  22134. *
  22135. * @param {PassNode} passNode - The pass node.
  22136. * @param {String} textureName - The output texture name.
  22137. * @param {Boolean} [previousTexture=false] - Whether previous frame data should be used or not.
  22138. */
  22139. constructor( passNode, textureName, previousTexture = false ) {
  22140. // null is passed to the super call since this class does not
  22141. // use an external texture for rendering pass data into. Instead
  22142. // the texture is managed by the pass node itself
  22143. super( passNode, null );
  22144. /**
  22145. * The output texture name.
  22146. *
  22147. * @type {String}
  22148. */
  22149. this.textureName = textureName;
  22150. /**
  22151. * Whether previous frame data should be used or not.
  22152. *
  22153. * @type {Boolean}
  22154. */
  22155. this.previousTexture = previousTexture;
  22156. }
  22157. /**
  22158. * Updates the texture reference of this node.
  22159. */
  22160. updateTexture() {
  22161. this.value = this.previousTexture ? this.passNode.getPreviousTexture( this.textureName ) : this.passNode.getTexture( this.textureName );
  22162. }
  22163. setup( builder ) {
  22164. this.updateTexture();
  22165. return super.setup( builder );
  22166. }
  22167. clone() {
  22168. return new this.constructor( this.passNode, this.textureName, this.previousTexture );
  22169. }
  22170. }
  22171. /**
  22172. * Represents a render pass (sometimes called beauty pass) in context of post processing.
  22173. * This pass produces a render for the given scene and camera and can provide multiple outputs
  22174. * via MRT for further processing.
  22175. *
  22176. * ```js
  22177. * const postProcessing = new PostProcessing( renderer );
  22178. *
  22179. * const scenePass = pass( scene, camera );
  22180. *
  22181. * postProcessing.outputNode = scenePass;
  22182. * ```
  22183. *
  22184. * @augments TempNode
  22185. */
  22186. class PassNode extends TempNode {
  22187. static get type() {
  22188. return 'PassNode';
  22189. }
  22190. /**
  22191. * Constructs a new pass node.
  22192. *
  22193. * @param {('color'|'depth')} scope - The scope of the pass. The scope determines whether the node outputs color or depth.
  22194. * @param {Scene} scene - A reference to the scene.
  22195. * @param {Camera} camera - A reference to the camera.
  22196. * @param {Object} options - Options for the internal render target.
  22197. */
  22198. constructor( scope, scene, camera, options = {} ) {
  22199. super( 'vec4' );
  22200. /**
  22201. * The scope of the pass. The scope determines whether the node outputs color or depth.
  22202. *
  22203. * @type {('color'|'depth')}
  22204. */
  22205. this.scope = scope;
  22206. /**
  22207. * A reference to the scene.
  22208. *
  22209. * @type {Scene}
  22210. */
  22211. this.scene = scene;
  22212. /**
  22213. * A reference to the camera.
  22214. *
  22215. * @type {Camera}
  22216. */
  22217. this.camera = camera;
  22218. /**
  22219. * Options for the internal render target.
  22220. *
  22221. * @type {Object}
  22222. */
  22223. this.options = options;
  22224. /**
  22225. * The pass's pixel ratio. Will be kept automatically kept in sync with the renderer's pixel ratio.
  22226. *
  22227. * @private
  22228. * @type {Number}
  22229. * @default 1
  22230. */
  22231. this._pixelRatio = 1;
  22232. /**
  22233. * The pass's pixel width. Will be kept automatically kept in sync with the renderer's width.
  22234. * @private
  22235. * @type {Number}
  22236. * @default 1
  22237. */
  22238. this._width = 1;
  22239. /**
  22240. * The pass's pixel height. Will be kept automatically kept in sync with the renderer's height.
  22241. * @private
  22242. * @type {Number}
  22243. * @default 1
  22244. */
  22245. this._height = 1;
  22246. const depthTexture = new DepthTexture();
  22247. depthTexture.isRenderTargetTexture = true;
  22248. //depthTexture.type = FloatType;
  22249. depthTexture.name = 'depth';
  22250. const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType, ...options, } );
  22251. renderTarget.texture.name = 'output';
  22252. renderTarget.depthTexture = depthTexture;
  22253. /**
  22254. * The pass's render target.
  22255. *
  22256. * @type {RenderTarget}
  22257. */
  22258. this.renderTarget = renderTarget;
  22259. /**
  22260. * A dictionary holding the internal result textures.
  22261. *
  22262. * @private
  22263. * @type {Object<String, Texture>}
  22264. */
  22265. this._textures = {
  22266. output: renderTarget.texture,
  22267. depth: depthTexture
  22268. };
  22269. /**
  22270. * A dictionary holding the internal texture nodes.
  22271. *
  22272. * @private
  22273. * @type {Object<String, TextureNode>}
  22274. */
  22275. this._textureNodes = {};
  22276. /**
  22277. * A dictionary holding the internal depth nodes.
  22278. *
  22279. * @private
  22280. * @type {Object}
  22281. */
  22282. this._linearDepthNodes = {};
  22283. /**
  22284. * A dictionary holding the internal viewZ nodes.
  22285. *
  22286. * @private
  22287. * @type {Object}
  22288. */
  22289. this._viewZNodes = {};
  22290. /**
  22291. * A dictionary holding the texture data of the previous frame.
  22292. * Used for computing velocity/motion vectors.
  22293. *
  22294. * @private
  22295. * @type {Object<String, Texture>}
  22296. */
  22297. this._previousTextures = {};
  22298. /**
  22299. * A dictionary holding the texture nodes of the previous frame.
  22300. * Used for computing velocity/motion vectors.
  22301. *
  22302. * @private
  22303. * @type {Object<String, TextureNode>}
  22304. */
  22305. this._previousTextureNodes = {};
  22306. /**
  22307. * The `near` property of the camera as a uniform.
  22308. *
  22309. * @private
  22310. * @type {UniformNode}
  22311. */
  22312. this._cameraNear = uniform( 0 );
  22313. /**
  22314. * The `far` property of the camera as a uniform.
  22315. *
  22316. * @private
  22317. * @type {UniformNode}
  22318. */
  22319. this._cameraFar = uniform( 0 );
  22320. /**
  22321. * A MRT node configuring the MRT settings.
  22322. *
  22323. * @private
  22324. * @type {MRTNode?}
  22325. * @default null
  22326. */
  22327. this._mrt = null;
  22328. /**
  22329. * This flag can be used for type testing.
  22330. *
  22331. * @type {Boolean}
  22332. * @readonly
  22333. * @default true
  22334. */
  22335. this.isPassNode = true;
  22336. /**
  22337. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  22338. * scene once per frame in its {@link PassNode#updateBefore} method.
  22339. *
  22340. * @type {String}
  22341. * @default 'frame'
  22342. */
  22343. this.updateBeforeType = NodeUpdateType.FRAME;
  22344. }
  22345. /**
  22346. * Sets the given MRT node to setup MRT for this pass.
  22347. *
  22348. * @param {MRTNode} mrt - The MRT object.
  22349. * @return {PassNode} A reference to this pass.
  22350. */
  22351. setMRT( mrt ) {
  22352. this._mrt = mrt;
  22353. return this;
  22354. }
  22355. /**
  22356. * Returns the current MRT node.
  22357. *
  22358. * @return {MRTNode} The current MRT node.
  22359. */
  22360. getMRT() {
  22361. return this._mrt;
  22362. }
  22363. /**
  22364. * The method is overwritten so it always returns `true`.
  22365. *
  22366. * @return {Boolean} Whether this node is global or not.
  22367. */
  22368. isGlobal() {
  22369. return true;
  22370. }
  22371. /**
  22372. * Returns the texture for the given output name.
  22373. *
  22374. * @param {String} name - The output name to get the texture for.
  22375. * @return {Texture} The texture.
  22376. */
  22377. getTexture( name ) {
  22378. let texture = this._textures[ name ];
  22379. if ( texture === undefined ) {
  22380. const refTexture = this.renderTarget.texture;
  22381. texture = refTexture.clone();
  22382. texture.name = name;
  22383. this._textures[ name ] = texture;
  22384. this.renderTarget.textures.push( texture );
  22385. }
  22386. return texture;
  22387. }
  22388. /**
  22389. * Returns the texture holding the data of the previous frame for the given output name.
  22390. *
  22391. * @param {String} name - The output name to get the texture for.
  22392. * @return {Texture} The texture holding the data of the previous frame.
  22393. */
  22394. getPreviousTexture( name ) {
  22395. let texture = this._previousTextures[ name ];
  22396. if ( texture === undefined ) {
  22397. texture = this.getTexture( name ).clone();
  22398. this._previousTextures[ name ] = texture;
  22399. }
  22400. return texture;
  22401. }
  22402. /**
  22403. * Switches current and previous textures for the given output name.
  22404. *
  22405. * @param {String} name - The output name.
  22406. */
  22407. toggleTexture( name ) {
  22408. const prevTexture = this._previousTextures[ name ];
  22409. if ( prevTexture !== undefined ) {
  22410. const texture = this._textures[ name ];
  22411. const index = this.renderTarget.textures.indexOf( texture );
  22412. this.renderTarget.textures[ index ] = prevTexture;
  22413. this._textures[ name ] = prevTexture;
  22414. this._previousTextures[ name ] = texture;
  22415. this._textureNodes[ name ].updateTexture();
  22416. this._previousTextureNodes[ name ].updateTexture();
  22417. }
  22418. }
  22419. /**
  22420. * Returns the texture node for the given output name.
  22421. *
  22422. * @param {String} [name='output'] - The output name to get the texture node for.
  22423. * @return {TextureNode} The texture node.
  22424. */
  22425. getTextureNode( name = 'output' ) {
  22426. let textureNode = this._textureNodes[ name ];
  22427. if ( textureNode === undefined ) {
  22428. textureNode = nodeObject( new PassMultipleTextureNode( this, name ) );
  22429. textureNode.updateTexture();
  22430. this._textureNodes[ name ] = textureNode;
  22431. }
  22432. return textureNode;
  22433. }
  22434. /**
  22435. * Returns the previous texture node for the given output name.
  22436. *
  22437. * @param {String} [name='output'] - The output name to get the previous texture node for.
  22438. * @return {TextureNode} The previous texture node.
  22439. */
  22440. getPreviousTextureNode( name = 'output' ) {
  22441. let textureNode = this._previousTextureNodes[ name ];
  22442. if ( textureNode === undefined ) {
  22443. if ( this._textureNodes[ name ] === undefined ) this.getTextureNode( name );
  22444. textureNode = nodeObject( new PassMultipleTextureNode( this, name, true ) );
  22445. textureNode.updateTexture();
  22446. this._previousTextureNodes[ name ] = textureNode;
  22447. }
  22448. return textureNode;
  22449. }
  22450. /**
  22451. * Returns a viewZ node of this pass.
  22452. *
  22453. * @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.
  22454. * @return {Node} The viewZ node.
  22455. */
  22456. getViewZNode( name = 'depth' ) {
  22457. let viewZNode = this._viewZNodes[ name ];
  22458. if ( viewZNode === undefined ) {
  22459. const cameraNear = this._cameraNear;
  22460. const cameraFar = this._cameraFar;
  22461. this._viewZNodes[ name ] = viewZNode = perspectiveDepthToViewZ( this.getTextureNode( name ), cameraNear, cameraFar );
  22462. }
  22463. return viewZNode;
  22464. }
  22465. /**
  22466. * Returns a linear depth node of this pass.
  22467. *
  22468. * @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.
  22469. * @return {Node} The linear depth node.
  22470. */
  22471. getLinearDepthNode( name = 'depth' ) {
  22472. let linearDepthNode = this._linearDepthNodes[ name ];
  22473. if ( linearDepthNode === undefined ) {
  22474. const cameraNear = this._cameraNear;
  22475. const cameraFar = this._cameraFar;
  22476. const viewZNode = this.getViewZNode( name );
  22477. // TODO: just if ( builder.camera.isPerspectiveCamera )
  22478. this._linearDepthNodes[ name ] = linearDepthNode = viewZToOrthographicDepth( viewZNode, cameraNear, cameraFar );
  22479. }
  22480. return linearDepthNode;
  22481. }
  22482. setup( { renderer } ) {
  22483. this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples;
  22484. // Disable MSAA for WebGL backend for now
  22485. if ( renderer.backend.isWebGLBackend === true ) {
  22486. this.renderTarget.samples = 0;
  22487. }
  22488. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  22489. }
  22490. updateBefore( frame ) {
  22491. const { renderer } = frame;
  22492. const { scene, camera } = this;
  22493. this._pixelRatio = renderer.getPixelRatio();
  22494. const size = renderer.getSize( _size );
  22495. this.setSize( size.width, size.height );
  22496. const currentRenderTarget = renderer.getRenderTarget();
  22497. const currentMRT = renderer.getMRT();
  22498. this._cameraNear.value = camera.near;
  22499. this._cameraFar.value = camera.far;
  22500. for ( const name in this._previousTextures ) {
  22501. this.toggleTexture( name );
  22502. }
  22503. renderer.setRenderTarget( this.renderTarget );
  22504. renderer.setMRT( this._mrt );
  22505. renderer.render( scene, camera );
  22506. renderer.setRenderTarget( currentRenderTarget );
  22507. renderer.setMRT( currentMRT );
  22508. }
  22509. /**
  22510. * Sets the size of the pass's render target. Honors the pixel ratio.
  22511. *
  22512. * @param {Number} width - The width to set.
  22513. * @param {Number} height - The height to set.
  22514. */
  22515. setSize( width, height ) {
  22516. this._width = width;
  22517. this._height = height;
  22518. const effectiveWidth = this._width * this._pixelRatio;
  22519. const effectiveHeight = this._height * this._pixelRatio;
  22520. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  22521. }
  22522. /**
  22523. * Sets the pixel ratio the pass's render target and updates the size.
  22524. *
  22525. * @param {Number} pixelRatio - The pixel ratio to set.
  22526. */
  22527. setPixelRatio( pixelRatio ) {
  22528. this._pixelRatio = pixelRatio;
  22529. this.setSize( this._width, this._height );
  22530. }
  22531. /**
  22532. * Frees internal resources. Should be called when the node is no longer in use.
  22533. */
  22534. dispose() {
  22535. this.renderTarget.dispose();
  22536. }
  22537. }
  22538. PassNode.COLOR = 'color';
  22539. PassNode.DEPTH = 'depth';
  22540. /**
  22541. * TSL function for creating a pass node.
  22542. *
  22543. * @function
  22544. * @param {Scene} scene - A reference to the scene.
  22545. * @param {Camera} camera - A reference to the camera.
  22546. * @param {Object} options - Options for the internal render target.
  22547. * @returns {PassNode}
  22548. */
  22549. const pass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera, options ) );
  22550. /**
  22551. * TSL function for creating a pass texture node.
  22552. *
  22553. * @function
  22554. * @param {PassNode} pass - The pass node.
  22555. * @param {Texture} texture - The output texture.
  22556. * @returns {PassTextureNode}
  22557. */
  22558. const passTexture = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) );
  22559. /**
  22560. * TSL function for creating a depth pass node.
  22561. *
  22562. * @function
  22563. * @param {Scene} scene - A reference to the scene.
  22564. * @param {Camera} camera - A reference to the camera.
  22565. * @param {Object} options - Options for the internal render target.
  22566. * @returns {PassNode}
  22567. */
  22568. const depthPass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera, options ) );
  22569. /** @module ToonOutlinePassNode **/
  22570. /**
  22571. * Represents a render pass for producing a toon outline effect on compatible objects.
  22572. * Only 3D objects with materials of type `MeshToonMaterial` and `MeshToonNodeMaterial`
  22573. * will receive the outline.
  22574. *
  22575. * ```js
  22576. * const postProcessing = new PostProcessing( renderer );
  22577. *
  22578. * const scenePass = toonOutlinePass( scene, camera );
  22579. *
  22580. * postProcessing.outputNode = scenePass;
  22581. * ```
  22582. * @augments PassNode
  22583. */
  22584. class ToonOutlinePassNode extends PassNode {
  22585. static get type() {
  22586. return 'ToonOutlinePassNode';
  22587. }
  22588. /**
  22589. * Constructs a new outline pass node.
  22590. *
  22591. * @param {Scene} scene - A reference to the scene.
  22592. * @param {Camera} camera - A reference to the camera.
  22593. * @param {Node} colorNode - Defines the outline's color.
  22594. * @param {Node} thicknessNode - Defines the outline's thickness.
  22595. * @param {Node} alphaNode - Defines the outline's alpha.
  22596. */
  22597. constructor( scene, camera, colorNode, thicknessNode, alphaNode ) {
  22598. super( PassNode.COLOR, scene, camera );
  22599. /**
  22600. * Defines the outline's color.
  22601. *
  22602. * @type {Node}
  22603. */
  22604. this.colorNode = colorNode;
  22605. /**
  22606. * Defines the outline's thickness.
  22607. *
  22608. * @type {Node}
  22609. */
  22610. this.thicknessNode = thicknessNode;
  22611. /**
  22612. * Defines the outline's alpha.
  22613. *
  22614. * @type {Node}
  22615. */
  22616. this.alphaNode = alphaNode;
  22617. /**
  22618. * An internal material cache.
  22619. *
  22620. * @private
  22621. * @type {WeakMap<Material, NodeMaterial>}
  22622. */
  22623. this._materialCache = new WeakMap();
  22624. }
  22625. updateBefore( frame ) {
  22626. const { renderer } = frame;
  22627. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  22628. renderer.setRenderObjectFunction( ( object, scene, camera, geometry, material, group, lightsNode, clippingContext ) => {
  22629. // only render outline for supported materials
  22630. if ( material.isMeshToonMaterial || material.isMeshToonNodeMaterial ) {
  22631. if ( material.wireframe === false ) {
  22632. const outlineMaterial = this._getOutlineMaterial( material );
  22633. renderer.renderObject( object, scene, camera, geometry, outlineMaterial, group, lightsNode, clippingContext );
  22634. }
  22635. }
  22636. // default
  22637. renderer.renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext );
  22638. } );
  22639. super.updateBefore( frame );
  22640. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  22641. }
  22642. /**
  22643. * Creates the material used for outline rendering.
  22644. *
  22645. * @private
  22646. * @return {NodeMaterial} The outline material.
  22647. */
  22648. _createMaterial() {
  22649. const material = new NodeMaterial();
  22650. material.isMeshToonOutlineMaterial = true;
  22651. material.name = 'Toon_Outline';
  22652. material.side = BackSide;
  22653. // vertex node
  22654. const outlineNormal = normalLocal.negate();
  22655. const mvp = cameraProjectionMatrix.mul( modelViewMatrix );
  22656. const ratio = float( 1.0 ); // TODO: support outline thickness ratio for each vertex
  22657. const pos = mvp.mul( vec4( positionLocal, 1.0 ) );
  22658. const pos2 = mvp.mul( vec4( positionLocal.add( outlineNormal ), 1.0 ) );
  22659. const norm = normalize( pos.sub( pos2 ) ); // NOTE: subtract pos2 from pos because BackSide objectNormal is negative
  22660. material.vertexNode = pos.add( norm.mul( this.thicknessNode ).mul( pos.w ).mul( ratio ) );
  22661. // color node
  22662. material.colorNode = vec4( this.colorNode, this.alphaNode );
  22663. return material;
  22664. }
  22665. /**
  22666. * For the given toon material, this method returns a corresponding
  22667. * outline material.
  22668. *
  22669. * @private
  22670. * @param {(MeshToonMaterial|MeshToonNodeMaterial)} originalMaterial - The toon material.
  22671. * @return {NodeMaterial} The outline material.
  22672. */
  22673. _getOutlineMaterial( originalMaterial ) {
  22674. let outlineMaterial = this._materialCache.get( originalMaterial );
  22675. if ( outlineMaterial === undefined ) {
  22676. outlineMaterial = this._createMaterial();
  22677. this._materialCache.set( originalMaterial, outlineMaterial );
  22678. }
  22679. return outlineMaterial;
  22680. }
  22681. }
  22682. /**
  22683. * TSL function for creating a toon outline pass node.
  22684. *
  22685. * @function
  22686. * @param {Scene} scene - A reference to the scene.
  22687. * @param {Camera} camera - A reference to the camera.
  22688. * @param {Color} color - Defines the outline's color.
  22689. * @param {Number} [thickness=0.003] - Defines the outline's thickness.
  22690. * @param {Number} [alpha=1] - Defines the outline's alpha.
  22691. * @returns {ToonOutlinePassNode}
  22692. */
  22693. 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 ) ) );
  22694. /** @module ToneMappingFunctions **/
  22695. /**
  22696. * Linear tone mapping, exposure only.
  22697. *
  22698. * @method
  22699. * @param {Node<vec3>} color - The color that should be tone mapped.
  22700. * @param {Node<float>} exposure - The exposure.
  22701. * @return {Node<vec3>} The tone mapped color.
  22702. */
  22703. const linearToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  22704. return color.mul( exposure ).clamp();
  22705. } ).setLayout( {
  22706. name: 'linearToneMapping',
  22707. type: 'vec3',
  22708. inputs: [
  22709. { name: 'color', type: 'vec3' },
  22710. { name: 'exposure', type: 'float' }
  22711. ]
  22712. } );
  22713. /**
  22714. * Reinhard tone mapping.
  22715. *
  22716. * Reference: {@link https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf}
  22717. *
  22718. * @method
  22719. * @param {Node<vec3>} color - The color that should be tone mapped.
  22720. * @param {Node<float>} exposure - The exposure.
  22721. * @return {Node<vec3>} The tone mapped color.
  22722. */
  22723. const reinhardToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  22724. color = color.mul( exposure );
  22725. return color.div( color.add( 1.0 ) ).clamp();
  22726. } ).setLayout( {
  22727. name: 'reinhardToneMapping',
  22728. type: 'vec3',
  22729. inputs: [
  22730. { name: 'color', type: 'vec3' },
  22731. { name: 'exposure', type: 'float' }
  22732. ]
  22733. } );
  22734. /**
  22735. * Cineon tone mapping.
  22736. *
  22737. * Reference: {@link http://filmicworlds.com/blog/filmic-tonemapping-operators/}
  22738. *
  22739. * @method
  22740. * @param {Node<vec3>} color - The color that should be tone mapped.
  22741. * @param {Node<float>} exposure - The exposure.
  22742. * @return {Node<vec3>} The tone mapped color.
  22743. */
  22744. const cineonToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  22745. // filmic operator by Jim Hejl and Richard Burgess-Dawson
  22746. color = color.mul( exposure );
  22747. color = color.sub( 0.004 ).max( 0.0 );
  22748. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  22749. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  22750. return a.div( b ).pow( 2.2 );
  22751. } ).setLayout( {
  22752. name: 'cineonToneMapping',
  22753. type: 'vec3',
  22754. inputs: [
  22755. { name: 'color', type: 'vec3' },
  22756. { name: 'exposure', type: 'float' }
  22757. ]
  22758. } );
  22759. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  22760. const RRTAndODTFit = /*@__PURE__*/ Fn( ( [ color ] ) => {
  22761. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  22762. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  22763. return a.div( b );
  22764. } );
  22765. /**
  22766. * ACESFilmic tone mapping.
  22767. *
  22768. * Reference: {@link https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs}
  22769. *
  22770. * @method
  22771. * @param {Node<vec3>} color - The color that should be tone mapped.
  22772. * @param {Node<float>} exposure - The exposure.
  22773. * @return {Node<vec3>} The tone mapped color.
  22774. */
  22775. const acesFilmicToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  22776. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  22777. const ACESInputMat = mat3(
  22778. 0.59719, 0.35458, 0.04823,
  22779. 0.07600, 0.90834, 0.01566,
  22780. 0.02840, 0.13383, 0.83777
  22781. );
  22782. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  22783. const ACESOutputMat = mat3(
  22784. 1.60475, -0.53108, -0.07367,
  22785. -0.10208, 1.10813, -605e-5,
  22786. -327e-5, -0.07276, 1.07602
  22787. );
  22788. color = color.mul( exposure ).div( 0.6 );
  22789. color = ACESInputMat.mul( color );
  22790. // Apply RRT and ODT
  22791. color = RRTAndODTFit( color );
  22792. color = ACESOutputMat.mul( color );
  22793. // Clamp to [0, 1]
  22794. return color.clamp();
  22795. } ).setLayout( {
  22796. name: 'acesFilmicToneMapping',
  22797. type: 'vec3',
  22798. inputs: [
  22799. { name: 'color', type: 'vec3' },
  22800. { name: 'exposure', type: 'float' }
  22801. ]
  22802. } );
  22803. 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 ) );
  22804. 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 ) );
  22805. const agxDefaultContrastApprox = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  22806. const x = vec3( x_immutable ).toVar();
  22807. const x2 = vec3( x.mul( x ) ).toVar();
  22808. const x4 = vec3( x2.mul( x2 ) ).toVar();
  22809. 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 ) ) ) );
  22810. } );
  22811. /**
  22812. * AgX tone mapping.
  22813. *
  22814. * @method
  22815. * @param {Node<vec3>} color - The color that should be tone mapped.
  22816. * @param {Node<float>} exposure - The exposure.
  22817. * @return {Node<vec3>} The tone mapped color.
  22818. */
  22819. const agxToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  22820. const colortone = vec3( color ).toVar();
  22821. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  22822. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, -0.1413297634984383, -0.14132976349843826 ), vec3( -0.11060664309660323, 1.157823702216272, -0.11060664309660294 ), vec3( -0.016493938717834573, -0.016493938717834257, 1.2519364065950405 ) );
  22823. const AgxMinEv = float( -12.47393 );
  22824. const AgxMaxEv = float( 4.026069 );
  22825. colortone.mulAssign( exposure );
  22826. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  22827. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  22828. colortone.assign( max$1( colortone, 1e-10 ) );
  22829. colortone.assign( log2( colortone ) );
  22830. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  22831. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  22832. colortone.assign( agxDefaultContrastApprox( colortone ) );
  22833. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  22834. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  22835. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  22836. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  22837. return colortone;
  22838. } ).setLayout( {
  22839. name: 'agxToneMapping',
  22840. type: 'vec3',
  22841. inputs: [
  22842. { name: 'color', type: 'vec3' },
  22843. { name: 'exposure', type: 'float' }
  22844. ]
  22845. } );
  22846. /**
  22847. * Neutral tone mapping.
  22848. *
  22849. * Reference: {@link https://modelviewer.dev/examples/tone-mapping}
  22850. *
  22851. * @method
  22852. * @param {Node<vec3>} color - The color that should be tone mapped.
  22853. * @param {Node<float>} exposure - The exposure.
  22854. * @return {Node<vec3>} The tone mapped color.
  22855. */
  22856. const neutralToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  22857. const StartCompression = float( 0.8 - 0.04 );
  22858. const Desaturation = float( 0.15 );
  22859. color = color.mul( exposure );
  22860. const x = min$1( color.r, min$1( color.g, color.b ) );
  22861. const offset = select( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  22862. color.subAssign( offset );
  22863. const peak = max$1( color.r, max$1( color.g, color.b ) );
  22864. If( peak.lessThan( StartCompression ), () => {
  22865. return color;
  22866. } );
  22867. const d = sub( 1, StartCompression );
  22868. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  22869. color.mulAssign( newPeak.div( peak ) );
  22870. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  22871. return mix( color, vec3( newPeak ), g );
  22872. } ).setLayout( {
  22873. name: 'neutralToneMapping',
  22874. type: 'vec3',
  22875. inputs: [
  22876. { name: 'color', type: 'vec3' },
  22877. { name: 'exposure', type: 'float' }
  22878. ]
  22879. } );
  22880. /** @module CodeNode **/
  22881. /**
  22882. * This class represents native code sections. It is the base
  22883. * class for modules like {@link FunctionNode} which allows to implement
  22884. * functions with native shader languages.
  22885. *
  22886. * @augments Node
  22887. */
  22888. class CodeNode extends Node {
  22889. static get type() {
  22890. return 'CodeNode';
  22891. }
  22892. /**
  22893. * Constructs a new code node.
  22894. *
  22895. * @param {String} [code=''] - The native code.
  22896. * @param {Array<Node>} [includes=[]] - An array of includes.
  22897. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  22898. */
  22899. constructor( code = '', includes = [], language = '' ) {
  22900. super( 'code' );
  22901. /**
  22902. * This flag can be used for type testing.
  22903. *
  22904. * @type {Boolean}
  22905. * @readonly
  22906. * @default true
  22907. */
  22908. this.isCodeNode = true;
  22909. /**
  22910. * The native code.
  22911. *
  22912. * @type {String}
  22913. * @default ''
  22914. */
  22915. this.code = code;
  22916. /**
  22917. * An array of includes
  22918. *
  22919. * @type {Array<Node>}
  22920. * @default []
  22921. */
  22922. this.includes = includes;
  22923. /**
  22924. * The used language.
  22925. *
  22926. * @type {('js'|'wgsl'|'glsl')}
  22927. * @default ''
  22928. */
  22929. this.language = language;
  22930. }
  22931. /**
  22932. * The method is overwritten so it always returns `true`.
  22933. *
  22934. * @return {Boolean} Whether this node is global or not.
  22935. */
  22936. isGlobal() {
  22937. return true;
  22938. }
  22939. /**
  22940. * Sets the includes of this code node.
  22941. *
  22942. * @param {Array<Node>} includes - The includes to set.
  22943. * @return {CodeNode} A reference to this node.
  22944. */
  22945. setIncludes( includes ) {
  22946. this.includes = includes;
  22947. return this;
  22948. }
  22949. /**
  22950. * Returns the includes of this code node.
  22951. *
  22952. * @param {NodeBuilder} builder - The current node builder.
  22953. * @return {Array<Node>} The includes.
  22954. */
  22955. getIncludes( /*builder*/ ) {
  22956. return this.includes;
  22957. }
  22958. generate( builder ) {
  22959. const includes = this.getIncludes( builder );
  22960. for ( const include of includes ) {
  22961. include.build( builder );
  22962. }
  22963. const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) );
  22964. nodeCode.code = this.code;
  22965. return nodeCode.code;
  22966. }
  22967. serialize( data ) {
  22968. super.serialize( data );
  22969. data.code = this.code;
  22970. data.language = this.language;
  22971. }
  22972. deserialize( data ) {
  22973. super.deserialize( data );
  22974. this.code = data.code;
  22975. this.language = data.language;
  22976. }
  22977. }
  22978. /**
  22979. * TSL function for creating a code node.
  22980. *
  22981. * @function
  22982. * @param {String} [code=''] - The native code.
  22983. * @param {Array<Node>} [includes=[]] - An array of includes.
  22984. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  22985. * @returns {CodeNode}
  22986. */
  22987. const code = /*@__PURE__*/ nodeProxy( CodeNode );
  22988. /**
  22989. * TSL function for creating a JS code node.
  22990. *
  22991. * @function
  22992. * @param {String} src - The native code.
  22993. * @param {Array<Node>} includes - An array of includes.
  22994. * @returns {CodeNode}
  22995. */
  22996. const js = ( src, includes ) => code( src, includes, 'js' );
  22997. /**
  22998. * TSL function for creating a WGSL code node.
  22999. *
  23000. * @function
  23001. * @param {String} src - The native code.
  23002. * @param {Array<Node>} includes - An array of includes.
  23003. * @returns {CodeNode}
  23004. */
  23005. const wgsl = ( src, includes ) => code( src, includes, 'wgsl' );
  23006. /**
  23007. * TSL function for creating a GLSL code node.
  23008. *
  23009. * @function
  23010. * @param {String} src - The native code.
  23011. * @param {Array<Node>} includes - An array of includes.
  23012. * @returns {CodeNode}
  23013. */
  23014. const glsl = ( src, includes ) => code( src, includes, 'glsl' );
  23015. /**
  23016. * This class represents a native shader function. It can be used to implement
  23017. * certain aspects of a node material with native shader code. There are two predefined
  23018. * TSL functions for easier usage.
  23019. *
  23020. * - `wgslFn`: Creates a WGSL function node.
  23021. * - `glslFn`: Creates a GLSL function node.
  23022. *
  23023. * A basic example with one include looks like so:
  23024. *
  23025. * ```js
  23026. * const desaturateWGSLFn = wgslFn( `
  23027. * fn desaturate( color:vec3<f32> ) -> vec3<f32> {
  23028. * let lum = vec3<f32>( 0.299, 0.587, 0.114 );
  23029. * return vec3<f32>( dot( lum, color ) );
  23030. * }`
  23031. *);
  23032. * const someWGSLFn = wgslFn( `
  23033. * fn someFn( color:vec3<f32> ) -> vec3<f32> {
  23034. * return desaturate( color );
  23035. * }
  23036. * `, [ desaturateWGSLFn ] );
  23037. * material.colorNode = someWGSLFn( { color: texture( map ) } );
  23038. *```
  23039. * @augments CodeNode
  23040. */
  23041. class FunctionNode extends CodeNode {
  23042. static get type() {
  23043. return 'FunctionNode';
  23044. }
  23045. /**
  23046. * Constructs a new function node.
  23047. *
  23048. * @param {String} [code=''] - The native code.
  23049. * @param {Array<Node>} [includes=[]] - An array of includes.
  23050. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  23051. */
  23052. constructor( code = '', includes = [], language = '' ) {
  23053. super( code, includes, language );
  23054. }
  23055. getNodeType( builder ) {
  23056. return this.getNodeFunction( builder ).type;
  23057. }
  23058. /**
  23059. * Returns the inputs of this function node.
  23060. *
  23061. * @param {NodeBuilder} builder - The current node builder.
  23062. * @return {Array<NodeFunctionInput>} The inputs.
  23063. */
  23064. getInputs( builder ) {
  23065. return this.getNodeFunction( builder ).inputs;
  23066. }
  23067. /**
  23068. * Returns the node function for this function node.
  23069. *
  23070. * @param {NodeBuilder} builder - The current node builder.
  23071. * @return {NodeFunction} The node function.
  23072. */
  23073. getNodeFunction( builder ) {
  23074. const nodeData = builder.getDataFromNode( this );
  23075. let nodeFunction = nodeData.nodeFunction;
  23076. if ( nodeFunction === undefined ) {
  23077. nodeFunction = builder.parser.parseFunction( this.code );
  23078. nodeData.nodeFunction = nodeFunction;
  23079. }
  23080. return nodeFunction;
  23081. }
  23082. generate( builder, output ) {
  23083. super.generate( builder );
  23084. const nodeFunction = this.getNodeFunction( builder );
  23085. const name = nodeFunction.name;
  23086. const type = nodeFunction.type;
  23087. const nodeCode = builder.getCodeFromNode( this, type );
  23088. if ( name !== '' ) {
  23089. // use a custom property name
  23090. nodeCode.name = name;
  23091. }
  23092. const propertyName = builder.getPropertyName( nodeCode );
  23093. const code = this.getNodeFunction( builder ).getCode( propertyName );
  23094. nodeCode.code = code + '\n';
  23095. if ( output === 'property' ) {
  23096. return propertyName;
  23097. } else {
  23098. return builder.format( `${ propertyName }()`, type, output );
  23099. }
  23100. }
  23101. }
  23102. const nativeFn = ( code, includes = [], language = '' ) => {
  23103. for ( let i = 0; i < includes.length; i ++ ) {
  23104. const include = includes[ i ];
  23105. // TSL Function: glslFn, wgslFn
  23106. if ( typeof include === 'function' ) {
  23107. includes[ i ] = include.functionNode;
  23108. }
  23109. }
  23110. const functionNode = nodeObject( new FunctionNode( code, includes, language ) );
  23111. const fn = ( ...params ) => functionNode.call( ...params );
  23112. fn.functionNode = functionNode;
  23113. return fn;
  23114. };
  23115. const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' );
  23116. const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' );
  23117. /** @module ScriptableValueNode **/
  23118. /**
  23119. * `ScriptableNode` uses this class to manage script inputs and outputs.
  23120. *
  23121. * @augments Node
  23122. */
  23123. class ScriptableValueNode extends Node {
  23124. static get type() {
  23125. return 'ScriptableValueNode';
  23126. }
  23127. /**
  23128. * Constructs a new scriptable node.
  23129. *
  23130. * @param {Any} [value=null] - The value.
  23131. */
  23132. constructor( value = null ) {
  23133. super();
  23134. /**
  23135. * A reference to the value.
  23136. *
  23137. * @private
  23138. * @default null
  23139. */
  23140. this._value = value;
  23141. /**
  23142. * Depending on the type of `_value`, this property might cache parsed data.
  23143. *
  23144. * @private
  23145. * @default null
  23146. */
  23147. this._cache = null;
  23148. /**
  23149. * If this node represents an input, this property represents the input type.
  23150. *
  23151. * @type {String?}
  23152. * @default null
  23153. */
  23154. this.inputType = null;
  23155. /**
  23156. * If this node represents an output, this property represents the output type.
  23157. *
  23158. * @type {String?}
  23159. * @default null
  23160. */
  23161. this.outputType = null;
  23162. /**
  23163. * An event dispatcher for managing events.
  23164. *
  23165. * @type {EventDispatcher}
  23166. */
  23167. this.events = new EventDispatcher();
  23168. /**
  23169. * This flag can be used for type testing.
  23170. *
  23171. * @type {Boolean}
  23172. * @readonly
  23173. * @default true
  23174. */
  23175. this.isScriptableValueNode = true;
  23176. }
  23177. /**
  23178. * Whether this node represents an output or not.
  23179. *
  23180. * @type {Boolean}
  23181. * @readonly
  23182. * @default true
  23183. */
  23184. get isScriptableOutputNode() {
  23185. return this.outputType !== null;
  23186. }
  23187. set value( val ) {
  23188. if ( this._value === val ) return;
  23189. if ( this._cache && this.inputType === 'URL' && this.value.value instanceof ArrayBuffer ) {
  23190. URL.revokeObjectURL( this._cache );
  23191. this._cache = null;
  23192. }
  23193. this._value = val;
  23194. this.events.dispatchEvent( { type: 'change' } );
  23195. this.refresh();
  23196. }
  23197. /**
  23198. * The node's value.
  23199. *
  23200. * @type {Any}
  23201. */
  23202. get value() {
  23203. return this._value;
  23204. }
  23205. /**
  23206. * Dispatches the `refresh` event.
  23207. */
  23208. refresh() {
  23209. this.events.dispatchEvent( { type: 'refresh' } );
  23210. }
  23211. /**
  23212. * The `value` property usually represents a node or even binary data in form of array buffers.
  23213. * In this case, this method tries to return the actual value behind the complex type.
  23214. *
  23215. * @return {Any} The value.
  23216. */
  23217. getValue() {
  23218. const value = this.value;
  23219. if ( value && this._cache === null && this.inputType === 'URL' && value.value instanceof ArrayBuffer ) {
  23220. this._cache = URL.createObjectURL( new Blob( [ value.value ] ) );
  23221. } else if ( value && value.value !== null && value.value !== undefined && (
  23222. ( ( this.inputType === 'URL' || this.inputType === 'String' ) && typeof value.value === 'string' ) ||
  23223. ( this.inputType === 'Number' && typeof value.value === 'number' ) ||
  23224. ( this.inputType === 'Vector2' && value.value.isVector2 ) ||
  23225. ( this.inputType === 'Vector3' && value.value.isVector3 ) ||
  23226. ( this.inputType === 'Vector4' && value.value.isVector4 ) ||
  23227. ( this.inputType === 'Color' && value.value.isColor ) ||
  23228. ( this.inputType === 'Matrix3' && value.value.isMatrix3 ) ||
  23229. ( this.inputType === 'Matrix4' && value.value.isMatrix4 )
  23230. ) ) {
  23231. return value.value;
  23232. }
  23233. return this._cache || value;
  23234. }
  23235. /**
  23236. * Overwritten since the node type is inferred from the value.
  23237. *
  23238. * @param {NodeBuilder} builder - The current node builder.
  23239. * @return {String} The node type.
  23240. */
  23241. getNodeType( builder ) {
  23242. return this.value && this.value.isNode ? this.value.getNodeType( builder ) : 'float';
  23243. }
  23244. setup() {
  23245. return this.value && this.value.isNode ? this.value : float();
  23246. }
  23247. serialize( data ) {
  23248. super.serialize( data );
  23249. if ( this.value !== null ) {
  23250. if ( this.inputType === 'ArrayBuffer' ) {
  23251. data.value = arrayBufferToBase64( this.value );
  23252. } else {
  23253. data.value = this.value ? this.value.toJSON( data.meta ).uuid : null;
  23254. }
  23255. } else {
  23256. data.value = null;
  23257. }
  23258. data.inputType = this.inputType;
  23259. data.outputType = this.outputType;
  23260. }
  23261. deserialize( data ) {
  23262. super.deserialize( data );
  23263. let value = null;
  23264. if ( data.value !== null ) {
  23265. if ( data.inputType === 'ArrayBuffer' ) {
  23266. value = base64ToArrayBuffer( data.value );
  23267. } else if ( data.inputType === 'Texture' ) {
  23268. value = data.meta.textures[ data.value ];
  23269. } else {
  23270. value = data.meta.nodes[ data.value ] || null;
  23271. }
  23272. }
  23273. this.value = value;
  23274. this.inputType = data.inputType;
  23275. this.outputType = data.outputType;
  23276. }
  23277. }
  23278. /**
  23279. * TSL function for creating a scriptable value node.
  23280. *
  23281. * @function
  23282. * @param {Any} [value=null] - The value.
  23283. * @returns {ScriptableValueNode}
  23284. */
  23285. const scriptableValue = /*@__PURE__*/ nodeProxy( ScriptableValueNode );
  23286. /** @module ScriptableNode **/
  23287. /**
  23288. * A Map-like data structure for managing resources of scriptable nodes.
  23289. *
  23290. * @augments Map
  23291. */
  23292. class Resources extends Map {
  23293. get( key, callback = null, ...params ) {
  23294. if ( this.has( key ) ) return super.get( key );
  23295. if ( callback !== null ) {
  23296. const value = callback( ...params );
  23297. this.set( key, value );
  23298. return value;
  23299. }
  23300. }
  23301. }
  23302. class Parameters {
  23303. constructor( scriptableNode ) {
  23304. this.scriptableNode = scriptableNode;
  23305. }
  23306. get parameters() {
  23307. return this.scriptableNode.parameters;
  23308. }
  23309. get layout() {
  23310. return this.scriptableNode.getLayout();
  23311. }
  23312. getInputLayout( id ) {
  23313. return this.scriptableNode.getInputLayout( id );
  23314. }
  23315. get( name ) {
  23316. const param = this.parameters[ name ];
  23317. const value = param ? param.getValue() : null;
  23318. return value;
  23319. }
  23320. }
  23321. /**
  23322. * Defines the resources (e.g. namespaces) of scriptable nodes.
  23323. *
  23324. * @type {Resources}
  23325. */
  23326. const ScriptableNodeResources = new Resources();
  23327. /**
  23328. * This type of node allows to implement nodes with custom scripts. The script
  23329. * section is represented as an instance of `CodeNode` written with JavaScript.
  23330. * The script itself must adhere to a specific structure.
  23331. *
  23332. * - main(): Executed once by default and every time `node.needsUpdate` is set.
  23333. * - layout: The layout object defines the script's interface (inputs and outputs).
  23334. *
  23335. * ```js
  23336. * ScriptableNodeResources.set( 'TSL', TSL );
  23337. *
  23338. * const scriptableNode = scriptable( js( `
  23339. * layout = {
  23340. * outputType: 'node',
  23341. * elements: [
  23342. * { name: 'source', inputType: 'node' },
  23343. * ]
  23344. * };
  23345. *
  23346. * const { mul, oscSine } = TSL;
  23347. *
  23348. * function main() {
  23349. * const source = parameters.get( 'source' ) || float();
  23350. * return mul( source, oscSine() ) );
  23351. * }
  23352. *
  23353. * ` ) );
  23354. *
  23355. * scriptableNode.setParameter( 'source', color( 1, 0, 0 ) );
  23356. *
  23357. * const material = new THREE.MeshBasicNodeMaterial();
  23358. * material.colorNode = scriptableNode;
  23359. * ```
  23360. *
  23361. * @augments Node
  23362. */
  23363. class ScriptableNode extends Node {
  23364. static get type() {
  23365. return 'ScriptableNode';
  23366. }
  23367. /**
  23368. * Constructs a new scriptable node.
  23369. *
  23370. * @param {CodeNode?} [codeNode=null] - The code node.
  23371. * @param {Object} [parameters={}] - The parameters definition.
  23372. */
  23373. constructor( codeNode = null, parameters = {} ) {
  23374. super();
  23375. /**
  23376. * The code node.
  23377. *
  23378. * @type {CodeNode?}
  23379. * @default null
  23380. */
  23381. this.codeNode = codeNode;
  23382. /**
  23383. * The parameters definition.
  23384. *
  23385. * @type {Object}
  23386. * @default {}
  23387. */
  23388. this.parameters = parameters;
  23389. this._local = new Resources();
  23390. this._output = scriptableValue();
  23391. this._outputs = {};
  23392. this._source = this.source;
  23393. this._method = null;
  23394. this._object = null;
  23395. this._value = null;
  23396. this._needsOutputUpdate = true;
  23397. this.onRefresh = this.onRefresh.bind( this );
  23398. /**
  23399. * This flag can be used for type testing.
  23400. *
  23401. * @type {Boolean}
  23402. * @readonly
  23403. * @default true
  23404. */
  23405. this.isScriptableNode = true;
  23406. }
  23407. /**
  23408. * The source code of the scriptable node.
  23409. *
  23410. * @type {String}
  23411. */
  23412. get source() {
  23413. return this.codeNode ? this.codeNode.code : '';
  23414. }
  23415. /**
  23416. * Sets the reference of a local script variable.
  23417. *
  23418. * @param {String} name - The variable name.
  23419. * @param {Object} value - The reference to set.
  23420. * @return {Resources} The resource map
  23421. */
  23422. setLocal( name, value ) {
  23423. return this._local.set( name, value );
  23424. }
  23425. /**
  23426. * Gets the value of a local script variable.
  23427. *
  23428. * @param {String} name - The variable name.
  23429. * @return {Object} The value.
  23430. */
  23431. getLocal( name ) {
  23432. return this._local.get( name );
  23433. }
  23434. /**
  23435. * Event listener for the `refresh` event.
  23436. */
  23437. onRefresh() {
  23438. this._refresh();
  23439. }
  23440. /**
  23441. * Returns an input from the layout with the given id/name.
  23442. *
  23443. * @param {String} id - The id/name of the input.
  23444. * @return {Object} The element entry.
  23445. */
  23446. getInputLayout( id ) {
  23447. for ( const element of this.getLayout() ) {
  23448. if ( element.inputType && ( element.id === id || element.name === id ) ) {
  23449. return element;
  23450. }
  23451. }
  23452. }
  23453. /**
  23454. * Returns an output from the layout with the given id/name.
  23455. *
  23456. * @param {String} id - The id/name of the output.
  23457. * @return {Object} The element entry.
  23458. */
  23459. getOutputLayout( id ) {
  23460. for ( const element of this.getLayout() ) {
  23461. if ( element.outputType && ( element.id === id || element.name === id ) ) {
  23462. return element;
  23463. }
  23464. }
  23465. }
  23466. /**
  23467. * Defines a script output for the given name and value.
  23468. *
  23469. * @param {String} name - The name of the output.
  23470. * @param {Node} value - The node value.
  23471. * @return {ScriptableNode} A reference to this node.
  23472. */
  23473. setOutput( name, value ) {
  23474. const outputs = this._outputs;
  23475. if ( outputs[ name ] === undefined ) {
  23476. outputs[ name ] = scriptableValue( value );
  23477. } else {
  23478. outputs[ name ].value = value;
  23479. }
  23480. return this;
  23481. }
  23482. /**
  23483. * Returns a script output for the given name.
  23484. *
  23485. * @param {String} name - The name of the output.
  23486. * @return {ScriptableValueNode} The node value.
  23487. */
  23488. getOutput( name ) {
  23489. return this._outputs[ name ];
  23490. }
  23491. /**
  23492. * Returns a parameter for the given name
  23493. *
  23494. * @param {String} name - The name of the parameter.
  23495. * @return {ScriptableValueNode} The node value.
  23496. */
  23497. getParameter( name ) {
  23498. return this.parameters[ name ];
  23499. }
  23500. /**
  23501. * Sets a value for the given parameter name.
  23502. *
  23503. * @param {String} name - The parameter name.
  23504. * @param {Any} value - The parameter value.
  23505. * @return {ScriptableNode} A reference to this node.
  23506. */
  23507. setParameter( name, value ) {
  23508. const parameters = this.parameters;
  23509. if ( value && value.isScriptableNode ) {
  23510. this.deleteParameter( name );
  23511. parameters[ name ] = value;
  23512. parameters[ name ].getDefaultOutput().events.addEventListener( 'refresh', this.onRefresh );
  23513. } else if ( value && value.isScriptableValueNode ) {
  23514. this.deleteParameter( name );
  23515. parameters[ name ] = value;
  23516. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  23517. } else if ( parameters[ name ] === undefined ) {
  23518. parameters[ name ] = scriptableValue( value );
  23519. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  23520. } else {
  23521. parameters[ name ].value = value;
  23522. }
  23523. return this;
  23524. }
  23525. /**
  23526. * Returns the value of this node which is the value of
  23527. * the default output.
  23528. *
  23529. * @return {Node} The value.
  23530. */
  23531. getValue() {
  23532. return this.getDefaultOutput().getValue();
  23533. }
  23534. /**
  23535. * Deletes a parameter from the script.
  23536. *
  23537. * @param {String} name - The parameter to remove.
  23538. * @return {ScriptableNode} A reference to this node.
  23539. */
  23540. deleteParameter( name ) {
  23541. let valueNode = this.parameters[ name ];
  23542. if ( valueNode ) {
  23543. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  23544. valueNode.events.removeEventListener( 'refresh', this.onRefresh );
  23545. }
  23546. return this;
  23547. }
  23548. /**
  23549. * Deletes all parameters from the script.
  23550. *
  23551. * @return {ScriptableNode} A reference to this node.
  23552. */
  23553. clearParameters() {
  23554. for ( const name of Object.keys( this.parameters ) ) {
  23555. this.deleteParameter( name );
  23556. }
  23557. this.needsUpdate = true;
  23558. return this;
  23559. }
  23560. /**
  23561. * Calls a function from the script.
  23562. *
  23563. * @param {String} name - The function name.
  23564. * @param {...Any} params - A list of parameters.
  23565. * @return {Any} The result of the function call.
  23566. */
  23567. call( name, ...params ) {
  23568. const object = this.getObject();
  23569. const method = object[ name ];
  23570. if ( typeof method === 'function' ) {
  23571. return method( ...params );
  23572. }
  23573. }
  23574. /**
  23575. * Asynchronously calls a function from the script.
  23576. *
  23577. * @param {String} name - The function name.
  23578. * @param {...Any} params - A list of parameters.
  23579. * @return {Promise<Any>} The result of the function call.
  23580. */
  23581. async callAsync( name, ...params ) {
  23582. const object = this.getObject();
  23583. const method = object[ name ];
  23584. if ( typeof method === 'function' ) {
  23585. return method.constructor.name === 'AsyncFunction' ? await method( ...params ) : method( ...params );
  23586. }
  23587. }
  23588. /**
  23589. * Overwritten since the node types is inferred from the script's output.
  23590. *
  23591. * @param {NodeBuilder} builder - The current node builder
  23592. * @return {String} The node type.
  23593. */
  23594. getNodeType( builder ) {
  23595. return this.getDefaultOutputNode().getNodeType( builder );
  23596. }
  23597. /**
  23598. * Refreshes the script node.
  23599. *
  23600. * @param {String?} [output=null] - An optional output.
  23601. */
  23602. refresh( output = null ) {
  23603. if ( output !== null ) {
  23604. this.getOutput( output ).refresh();
  23605. } else {
  23606. this._refresh();
  23607. }
  23608. }
  23609. /**
  23610. * Returns an object representation of the script.
  23611. *
  23612. * @return {Object} The result object.
  23613. */
  23614. getObject() {
  23615. if ( this.needsUpdate ) this.dispose();
  23616. if ( this._object !== null ) return this._object;
  23617. //
  23618. const refresh = () => this.refresh();
  23619. const setOutput = ( id, value ) => this.setOutput( id, value );
  23620. const parameters = new Parameters( this );
  23621. const THREE = ScriptableNodeResources.get( 'THREE' );
  23622. const TSL = ScriptableNodeResources.get( 'TSL' );
  23623. const method = this.getMethod();
  23624. const params = [ parameters, this._local, ScriptableNodeResources, refresh, setOutput, THREE, TSL ];
  23625. this._object = method( ...params );
  23626. const layout = this._object.layout;
  23627. if ( layout ) {
  23628. if ( layout.cache === false ) {
  23629. this._local.clear();
  23630. }
  23631. // default output
  23632. this._output.outputType = layout.outputType || null;
  23633. if ( Array.isArray( layout.elements ) ) {
  23634. for ( const element of layout.elements ) {
  23635. const id = element.id || element.name;
  23636. if ( element.inputType ) {
  23637. if ( this.getParameter( id ) === undefined ) this.setParameter( id, null );
  23638. this.getParameter( id ).inputType = element.inputType;
  23639. }
  23640. if ( element.outputType ) {
  23641. if ( this.getOutput( id ) === undefined ) this.setOutput( id, null );
  23642. this.getOutput( id ).outputType = element.outputType;
  23643. }
  23644. }
  23645. }
  23646. }
  23647. return this._object;
  23648. }
  23649. deserialize( data ) {
  23650. super.deserialize( data );
  23651. for ( const name in this.parameters ) {
  23652. let valueNode = this.parameters[ name ];
  23653. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  23654. valueNode.events.addEventListener( 'refresh', this.onRefresh );
  23655. }
  23656. }
  23657. /**
  23658. * Returns the layout of the script.
  23659. *
  23660. * @return {Object} The script's layout.
  23661. */
  23662. getLayout() {
  23663. return this.getObject().layout;
  23664. }
  23665. /**
  23666. * Returns default node output of the script.
  23667. *
  23668. * @return {Node} The default node output.
  23669. */
  23670. getDefaultOutputNode() {
  23671. const output = this.getDefaultOutput().value;
  23672. if ( output && output.isNode ) {
  23673. return output;
  23674. }
  23675. return float();
  23676. }
  23677. /**
  23678. * Returns default output of the script.
  23679. *
  23680. * @return {ScriptableValueNode} The default output.
  23681. */
  23682. getDefaultOutput() {
  23683. return this._exec()._output;
  23684. }
  23685. /**
  23686. * Returns a function created from the node's script.
  23687. *
  23688. * @return {Function} The function representing the node's code.
  23689. */
  23690. getMethod() {
  23691. if ( this.needsUpdate ) this.dispose();
  23692. if ( this._method !== null ) return this._method;
  23693. //
  23694. const parametersProps = [ 'parameters', 'local', 'global', 'refresh', 'setOutput', 'THREE', 'TSL' ];
  23695. const interfaceProps = [ 'layout', 'init', 'main', 'dispose' ];
  23696. const properties = interfaceProps.join( ', ' );
  23697. const declarations = 'var ' + properties + '; var output = {};\n';
  23698. const returns = '\nreturn { ...output, ' + properties + ' };';
  23699. const code = declarations + this.codeNode.code + returns;
  23700. //
  23701. this._method = new Function( ...parametersProps, code );
  23702. return this._method;
  23703. }
  23704. /**
  23705. * Frees all internal resources.
  23706. */
  23707. dispose() {
  23708. if ( this._method === null ) return;
  23709. if ( this._object && typeof this._object.dispose === 'function' ) {
  23710. this._object.dispose();
  23711. }
  23712. this._method = null;
  23713. this._object = null;
  23714. this._source = null;
  23715. this._value = null;
  23716. this._needsOutputUpdate = true;
  23717. this._output.value = null;
  23718. this._outputs = {};
  23719. }
  23720. setup() {
  23721. return this.getDefaultOutputNode();
  23722. }
  23723. getCacheKey( force ) {
  23724. const values = [ hashString( this.source ), this.getDefaultOutputNode().getCacheKey( force ) ];
  23725. for ( const param in this.parameters ) {
  23726. values.push( this.parameters[ param ].getCacheKey( force ) );
  23727. }
  23728. return hashArray( values );
  23729. }
  23730. set needsUpdate( value ) {
  23731. if ( value === true ) this.dispose();
  23732. }
  23733. get needsUpdate() {
  23734. return this.source !== this._source;
  23735. }
  23736. /**
  23737. * Executes the `main` function of the script.
  23738. *
  23739. * @private
  23740. * @return {ScriptableNode} A reference to this node.
  23741. */
  23742. _exec() {
  23743. if ( this.codeNode === null ) return this;
  23744. if ( this._needsOutputUpdate === true ) {
  23745. this._value = this.call( 'main' );
  23746. this._needsOutputUpdate = false;
  23747. }
  23748. this._output.value = this._value;
  23749. return this;
  23750. }
  23751. /**
  23752. * Executes the refresh.
  23753. *
  23754. * @private
  23755. */
  23756. _refresh() {
  23757. this.needsUpdate = true;
  23758. this._exec();
  23759. this._output.refresh();
  23760. }
  23761. }
  23762. /**
  23763. * TSL function for creating a scriptable node.
  23764. *
  23765. * @function
  23766. * @param {CodeNode?} [codeNode=null] - The code node.
  23767. * @param {Object} [parameters={}] - The parameters definition.
  23768. * @returns {ScriptableNode}
  23769. */
  23770. const scriptable = /*@__PURE__*/ nodeProxy( ScriptableNode );
  23771. /** @module Fog **/
  23772. /**
  23773. * Returns a node that represents the `z` coordinate in view space
  23774. * for the current fragment. It's a different representation of the
  23775. * default depth value.
  23776. *
  23777. * This value can be part of a computation that defines how the fog
  23778. * density increases when moving away from the camera.
  23779. *
  23780. * @param {NodeBuilder} builder - The current node builder.
  23781. * @return {Node} The viewZ node.
  23782. */
  23783. function getViewZNode( builder ) {
  23784. let viewZ;
  23785. const getViewZ = builder.context.getViewZ;
  23786. if ( getViewZ !== undefined ) {
  23787. viewZ = getViewZ( this );
  23788. }
  23789. return ( viewZ || positionView.z ).negate();
  23790. }
  23791. /**
  23792. * Constructs a new range factor node.
  23793. *
  23794. * @function
  23795. * @param {Node} near - Defines the near value.
  23796. * @param {Node} far - Defines the far value.
  23797. */
  23798. const rangeFogFactor = Fn( ( [ near, far ], builder ) => {
  23799. const viewZ = getViewZNode( builder );
  23800. return smoothstep( near, far, viewZ );
  23801. } );
  23802. /**
  23803. * Represents an exponential squared fog. This type of fog gives
  23804. * a clear view near the camera and a faster than exponentially
  23805. * densening fog farther from the camera.
  23806. *
  23807. * @function
  23808. * @param {Node} density - Defines the fog density.
  23809. */
  23810. const densityFogFactor = Fn( ( [ density ], builder ) => {
  23811. const viewZ = getViewZNode( builder );
  23812. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  23813. } );
  23814. /**
  23815. * This class can be used to configure a fog for the scene.
  23816. * Nodes of this type are assigned to `Scene.fogNode`.
  23817. *
  23818. * @function
  23819. * @param {Node} color - Defines the color of the fog.
  23820. * @param {Node} factor - Defines how the fog is factored in the scene.
  23821. */
  23822. const fog = Fn( ( [ color, factor ] ) => {
  23823. return vec4( factor.toFloat().mix( output.rgb, color.toVec3() ), output.a );
  23824. } );
  23825. // Deprecated
  23826. /**
  23827. * @function
  23828. * @deprecated since r171. Use `fog( color, rangeFogFactor( near, far ) )` instead.
  23829. *
  23830. * @param {Node} color
  23831. * @param {Node} near
  23832. * @param {Node} far
  23833. * @returns {Function}
  23834. */
  23835. function rangeFog( color, near, far ) { // @deprecated, r171
  23836. console.warn( 'THREE.TSL: "rangeFog( color, near, far )" is deprecated. Use "fog( color, rangeFogFactor( near, far ) )" instead.' );
  23837. return fog( color, rangeFogFactor( near, far ) );
  23838. }
  23839. /**
  23840. * @function
  23841. * @deprecated since r171. Use `fog( color, densityFogFactor( density ) )` instead.
  23842. *
  23843. * @param {Node} color
  23844. * @param {Node} density
  23845. * @returns {Function}
  23846. */
  23847. function densityFog( color, density ) { // @deprecated, r171
  23848. console.warn( 'THREE.TSL: "densityFog( color, density )" is deprecated. Use "fog( color, densityFogFactor( density ) )" instead.' );
  23849. return fog( color, densityFogFactor( density ) );
  23850. }
  23851. /** @module RangeNode **/
  23852. let min = null;
  23853. let max = null;
  23854. /**
  23855. * `RangeNode` generates random instanced attribute data in a defined range.
  23856. * An exemplary use case for this utility node is to generate random per-instance
  23857. * colors:
  23858. * ```js
  23859. * const material = new MeshBasicNodeMaterial();
  23860. * material.colorNode = range( new Color( 0x000000 ), new Color( 0xFFFFFF ) );
  23861. * const mesh = new InstancedMesh( geometry, material, count );
  23862. * ```
  23863. * @augments Node
  23864. */
  23865. class RangeNode extends Node {
  23866. static get type() {
  23867. return 'RangeNode';
  23868. }
  23869. /**
  23870. * Constructs a new range node.
  23871. *
  23872. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  23873. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  23874. */
  23875. constructor( minNode = float(), maxNode = float() ) {
  23876. super();
  23877. /**
  23878. * A node defining the lower bound of the range.
  23879. *
  23880. * @type {Node<any>}
  23881. * @default float()
  23882. */
  23883. this.minNode = minNode;
  23884. /**
  23885. * A node defining the upper bound of the range.
  23886. *
  23887. * @type {Node<any>}
  23888. * @default float()
  23889. */
  23890. this.maxNode = maxNode;
  23891. }
  23892. /**
  23893. * Returns the vector length which is computed based on the range definition.
  23894. *
  23895. * @param {NodeBuilder} builder - The current node builder.
  23896. * @return {Number} The vector length.
  23897. */
  23898. getVectorLength( builder ) {
  23899. const minLength = builder.getTypeLength( getValueType( this.minNode.value ) );
  23900. const maxLength = builder.getTypeLength( getValueType( this.maxNode.value ) );
  23901. return minLength > maxLength ? minLength : maxLength;
  23902. }
  23903. /**
  23904. * This method is overwritten since the node type is inferred from range definition.
  23905. *
  23906. * @param {NodeBuilder} builder - The current node builder.
  23907. * @return {String} The node type.
  23908. */
  23909. getNodeType( builder ) {
  23910. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  23911. }
  23912. setup( builder ) {
  23913. const object = builder.object;
  23914. let output = null;
  23915. if ( object.count > 1 ) {
  23916. const minValue = this.minNode.value;
  23917. const maxValue = this.maxNode.value;
  23918. const minLength = builder.getTypeLength( getValueType( minValue ) );
  23919. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  23920. min = min || new Vector4();
  23921. max = max || new Vector4();
  23922. min.setScalar( 0 );
  23923. max.setScalar( 0 );
  23924. if ( minLength === 1 ) min.setScalar( minValue );
  23925. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b, 1 );
  23926. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  23927. if ( maxLength === 1 ) max.setScalar( maxValue );
  23928. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b, 1 );
  23929. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  23930. const stride = 4;
  23931. const length = stride * object.count;
  23932. const array = new Float32Array( length );
  23933. for ( let i = 0; i < length; i ++ ) {
  23934. const index = i % stride;
  23935. const minElementValue = min.getComponent( index );
  23936. const maxElementValue = max.getComponent( index );
  23937. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  23938. }
  23939. const nodeType = this.getNodeType( builder );
  23940. if ( object.count <= 4096 ) {
  23941. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  23942. } else {
  23943. // TODO: Improve anonymous buffer attribute creation removing this part
  23944. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  23945. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  23946. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  23947. }
  23948. } else {
  23949. output = float( 0 );
  23950. }
  23951. return output;
  23952. }
  23953. }
  23954. /**
  23955. * TSL function for creating a range node.
  23956. *
  23957. * @function
  23958. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  23959. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  23960. * @returns {RangeNode}
  23961. */
  23962. const range = /*@__PURE__*/ nodeProxy( RangeNode );
  23963. /** @module ComputeBuiltinNode **/
  23964. /**
  23965. * `ComputeBuiltinNode` represents a compute-scope builtin value that expose information
  23966. * about the currently running dispatch and/or the device it is running on.
  23967. *
  23968. * This node can only be used with a WebGPU backend.
  23969. *
  23970. * @augments Node
  23971. */
  23972. class ComputeBuiltinNode extends Node {
  23973. static get type() {
  23974. return 'ComputeBuiltinNode';
  23975. }
  23976. /**
  23977. * Constructs a new compute builtin node.
  23978. *
  23979. * @param {String} builtinName - The built-in name.
  23980. * @param {String} nodeType - The node type.
  23981. */
  23982. constructor( builtinName, nodeType ) {
  23983. super( nodeType );
  23984. /**
  23985. * The built-in name.
  23986. *
  23987. * @private
  23988. * @type {String}
  23989. */
  23990. this._builtinName = builtinName;
  23991. }
  23992. /**
  23993. * This method is overwritten since hash is derived from the built-in name.
  23994. *
  23995. * @param {NodeBuilder} builder - The current node builder.
  23996. * @return {String} The hash.
  23997. */
  23998. getHash( builder ) {
  23999. return this.getBuiltinName( builder );
  24000. }
  24001. /**
  24002. * This method is overwritten since the node type is simply derived from `nodeType`..
  24003. *
  24004. * @param {NodeBuilder} builder - The current node builder.
  24005. * @return {String} The node type.
  24006. */
  24007. getNodeType( /*builder*/ ) {
  24008. return this.nodeType;
  24009. }
  24010. /**
  24011. * Sets the builtin name.
  24012. *
  24013. * @param {String} builtinName - The built-in name.
  24014. * @return {ComputeBuiltinNode} A reference to this node.
  24015. */
  24016. setBuiltinName( builtinName ) {
  24017. this._builtinName = builtinName;
  24018. return this;
  24019. }
  24020. /**
  24021. * Returns the builtin name.
  24022. *
  24023. * @param {NodeBuilder} builder - The current node builder.
  24024. * @return {String} The builtin name.
  24025. */
  24026. getBuiltinName( /*builder*/ ) {
  24027. return this._builtinName;
  24028. }
  24029. /**
  24030. * Whether the current node builder has the builtin or not.
  24031. *
  24032. * @param {NodeBuilder} builder - The current node builder.
  24033. */
  24034. hasBuiltin( builder ) {
  24035. builder.hasBuiltin( this._builtinName );
  24036. }
  24037. generate( builder, output ) {
  24038. const builtinName = this.getBuiltinName( builder );
  24039. const nodeType = this.getNodeType( builder );
  24040. if ( builder.shaderStage === 'compute' ) {
  24041. return builder.format( builtinName, nodeType, output );
  24042. } else {
  24043. console.warn( `ComputeBuiltinNode: Compute built-in value ${builtinName} can not be accessed in the ${builder.shaderStage} stage` );
  24044. return builder.generateConst( nodeType );
  24045. }
  24046. }
  24047. serialize( data ) {
  24048. super.serialize( data );
  24049. data.global = this.global;
  24050. data._builtinName = this._builtinName;
  24051. }
  24052. deserialize( data ) {
  24053. super.deserialize( data );
  24054. this.global = data.global;
  24055. this._builtinName = data._builtinName;
  24056. }
  24057. }
  24058. /**
  24059. * TSL function for creating a compute builtin node.
  24060. *
  24061. * @function
  24062. * @param {String} name - The built-in name.
  24063. * @param {String} nodeType - The node type.
  24064. * @returns {ComputeBuiltinNode}
  24065. */
  24066. const computeBuiltin = ( name, nodeType ) => nodeObject( new ComputeBuiltinNode( name, nodeType ) );
  24067. /**
  24068. * TSL function for creating a `numWorkgroups` builtin node.
  24069. * Represents the number of workgroups dispatched by the compute shader.
  24070. * ```js
  24071. * // Run 512 invocations/threads with a workgroup size of 128.
  24072. * const computeFn = Fn(() => {
  24073. *
  24074. * // numWorkgroups.x = 4
  24075. * storageBuffer.element(0).assign(numWorkgroups.x)
  24076. *
  24077. * })().compute(512, [128]);
  24078. *
  24079. * // Run 512 invocations/threads with the default workgroup size of 64.
  24080. * const computeFn = Fn(() => {
  24081. *
  24082. * // numWorkgroups.x = 8
  24083. * storageBuffer.element(0).assign(numWorkgroups.x)
  24084. *
  24085. * })().compute(512);
  24086. * ```
  24087. *
  24088. * @function
  24089. * @returns {ComputeBuiltinNode<uvec3>}
  24090. */
  24091. const numWorkgroups = /*@__PURE__*/ computeBuiltin( 'numWorkgroups', 'uvec3' );
  24092. /**
  24093. * TSL function for creating a `workgroupId` builtin node.
  24094. * Represents the 3-dimensional index of the workgroup the current compute invocation belongs to.
  24095. * ```js
  24096. * // Execute 12 compute threads with a workgroup size of 3.
  24097. * const computeFn = Fn( () => {
  24098. *
  24099. * If( workgroupId.x.modInt( 2 ).equal( 0 ), () => {
  24100. *
  24101. * storageBuffer.element( instanceIndex ).assign( instanceIndex );
  24102. *
  24103. * } ).Else( () => {
  24104. *
  24105. * storageBuffer.element( instanceIndex ).assign( 0 );
  24106. *
  24107. * } );
  24108. *
  24109. * } )().compute( 12, [ 3 ] );
  24110. *
  24111. * // workgroupId.x = [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3];
  24112. * // Buffer Output = [0, 1, 2, 0, 0, 0, 6, 7, 8, 0, 0, 0];
  24113. * ```
  24114. *
  24115. * @function
  24116. * @returns {ComputeBuiltinNode<uvec3>}
  24117. */
  24118. const workgroupId = /*@__PURE__*/ computeBuiltin( 'workgroupId', 'uvec3' );
  24119. /**
  24120. * TSL function for creating a `globalId` builtin node. A non-linearized 3-dimensional
  24121. * representation of the current invocation's position within a 3D global grid.
  24122. *
  24123. * @function
  24124. * @returns {ComputeBuiltinNode<uvec3>}
  24125. */
  24126. const globalId = /*@__PURE__*/ computeBuiltin( 'globalId', 'uvec3' );
  24127. /**
  24128. * TSL function for creating a `localId` builtin node. A non-linearized 3-dimensional
  24129. * representation of the current invocation's position within a 3D workgroup grid.
  24130. *
  24131. * @function
  24132. * @returns {ComputeBuiltinNode<uvec3>}
  24133. */
  24134. const localId = /*@__PURE__*/ computeBuiltin( 'localId', 'uvec3' );
  24135. /**
  24136. * TSL function for creating a `subgroupSize` builtin node. A device dependent variable
  24137. * that exposes the size of the current invocation's subgroup.
  24138. *
  24139. * @function
  24140. * @returns {ComputeBuiltinNode<uint>}
  24141. */
  24142. const subgroupSize = /*@__PURE__*/ computeBuiltin( 'subgroupSize', 'uint' );
  24143. /** @module BarrierNode **/
  24144. /**
  24145. * Represents a GPU control barrier that synchronizes compute operations within a given scope.
  24146. *
  24147. * This node can only be used with a WebGPU backend.
  24148. *
  24149. * @augments Node
  24150. */
  24151. class BarrierNode extends Node {
  24152. /**
  24153. * Constructs a new barrier node.
  24154. *
  24155. * @param {String} scope - The scope defines the behavior of the node.
  24156. */
  24157. constructor( scope ) {
  24158. super();
  24159. this.scope = scope;
  24160. }
  24161. generate( builder ) {
  24162. const { scope } = this;
  24163. const { renderer } = builder;
  24164. if ( renderer.backend.isWebGLBackend === true ) {
  24165. builder.addFlowCode( `\t// ${scope}Barrier \n` );
  24166. } else {
  24167. builder.addLineFlowCode( `${scope}Barrier()`, this );
  24168. }
  24169. }
  24170. }
  24171. /**
  24172. * TSL function for creating a barrier node.
  24173. *
  24174. * @function
  24175. * @param {String} scope - The scope defines the behavior of the node..
  24176. * @returns {BarrierNode}
  24177. */
  24178. const barrier = nodeProxy( BarrierNode );
  24179. /**
  24180. * TSL function for creating a workgroup barrier. All compute shader
  24181. * invocations must wait for each invocation within a workgroup to
  24182. * complete before the barrier can be surpassed.
  24183. *
  24184. * @function
  24185. * @returns {BarrierNode}
  24186. */
  24187. const workgroupBarrier = () => barrier( 'workgroup' ).append();
  24188. /**
  24189. * TSL function for creating a storage barrier. All invocations must
  24190. * wait for each access to variables within the 'storage' address space
  24191. * to complete before the barrier can be passed.
  24192. *
  24193. * @function
  24194. * @returns {BarrierNode}
  24195. */
  24196. const storageBarrier = () => barrier( 'storage' ).append();
  24197. /**
  24198. * TSL function for creating a texture barrier. All invocations must
  24199. * wait for each access to variables within the 'texture' address space
  24200. * to complete before the barrier can be passed.
  24201. *
  24202. * @function
  24203. * @returns {BarrierNode}
  24204. */
  24205. const textureBarrier = () => barrier( 'texture' ).append();
  24206. /** @module WorkgroupInfoNode **/
  24207. /**
  24208. * Represents an element of a 'workgroup' scoped buffer.
  24209. *
  24210. * @augments ArrayElementNode
  24211. */
  24212. class WorkgroupInfoElementNode extends ArrayElementNode {
  24213. /**
  24214. * Constructs a new workgroup info element node.
  24215. *
  24216. * @param {Node} workgroupInfoNode - The workgroup info node.
  24217. * @param {Node} indexNode - The index node that defines the element access.
  24218. */
  24219. constructor( workgroupInfoNode, indexNode ) {
  24220. super( workgroupInfoNode, indexNode );
  24221. /**
  24222. * This flag can be used for type testing.
  24223. *
  24224. * @type {Boolean}
  24225. * @readonly
  24226. * @default true
  24227. */
  24228. this.isWorkgroupInfoElementNode = true;
  24229. }
  24230. generate( builder, output ) {
  24231. let snippet;
  24232. const isAssignContext = builder.context.assign;
  24233. snippet = super.generate( builder );
  24234. if ( isAssignContext !== true ) {
  24235. const type = this.getNodeType( builder );
  24236. snippet = builder.format( snippet, type, output );
  24237. }
  24238. // TODO: Possibly activate clip distance index on index access rather than from clipping context
  24239. return snippet;
  24240. }
  24241. }
  24242. /**
  24243. * A node allowing the user to create a 'workgroup' scoped buffer within the
  24244. * context of a compute shader. Typically, workgroup scoped buffers are
  24245. * created to hold data that is transferred from a global storage scope into
  24246. * a local workgroup scope. For invocations within a workgroup, data
  24247. * access speeds on 'workgroup' scoped buffers can be significantly faster
  24248. * than similar access operations on globally accessible storage buffers.
  24249. *
  24250. * This node can only be used with a WebGPU backend.
  24251. *
  24252. * @augments Node
  24253. */
  24254. class WorkgroupInfoNode extends Node {
  24255. /**
  24256. * Constructs a new buffer scoped to type scope.
  24257. *
  24258. * @param {String} scope - TODO.
  24259. * @param {String} bufferType - The data type of a 'workgroup' scoped buffer element.
  24260. * @param {Number} [bufferCount=0] - The number of elements in the buffer.
  24261. */
  24262. constructor( scope, bufferType, bufferCount = 0 ) {
  24263. super( bufferType );
  24264. /**
  24265. * The buffer type.
  24266. *
  24267. * @type {String}
  24268. */
  24269. this.bufferType = bufferType;
  24270. /**
  24271. * The buffer count.
  24272. *
  24273. * @type {Number}
  24274. * @default 0
  24275. */
  24276. this.bufferCount = bufferCount;
  24277. /**
  24278. * This flag can be used for type testing.
  24279. *
  24280. * @type {Boolean}
  24281. * @readonly
  24282. * @default true
  24283. */
  24284. this.isWorkgroupInfoNode = true;
  24285. /**
  24286. * The data type of the array buffer.
  24287. *
  24288. * @type {String}
  24289. */
  24290. this.elementType = bufferType;
  24291. /**
  24292. * TODO.
  24293. *
  24294. * @type {String}
  24295. */
  24296. this.scope = scope;
  24297. }
  24298. /**
  24299. * Sets the name/label of this node.
  24300. *
  24301. * @param {String} name - The name to set.
  24302. * @return {WorkgroupInfoNode} A reference to this node.
  24303. */
  24304. label( name ) {
  24305. this.name = name;
  24306. return this;
  24307. }
  24308. /**
  24309. * Sets the scope of this node.
  24310. *
  24311. * @param {String} scope - The scope to set.
  24312. * @return {WorkgroupInfoNode} A reference to this node.
  24313. */
  24314. setScope( scope ) {
  24315. this.scope = scope;
  24316. return this;
  24317. }
  24318. /**
  24319. * The data type of the array buffer.
  24320. *
  24321. * @return {String} The element type.
  24322. */
  24323. getElementType() {
  24324. return this.elementType;
  24325. }
  24326. /**
  24327. * Overwrites the default implementation since the input type
  24328. * is inferred from the scope.
  24329. *
  24330. * @param {NodeBuilder} builder - The current node builder.
  24331. * @return {String} The input type.
  24332. */
  24333. getInputType( /*builder*/ ) {
  24334. return `${this.scope}Array`;
  24335. }
  24336. /**
  24337. * This method can be used to access elements via an index node.
  24338. *
  24339. * @param {IndexNode} indexNode - indexNode.
  24340. * @return {WorkgroupInfoElementNode} A reference to an element.
  24341. */
  24342. element( indexNode ) {
  24343. return nodeObject( new WorkgroupInfoElementNode( this, indexNode ) );
  24344. }
  24345. generate( builder ) {
  24346. return builder.getScopedArray( this.name || `${this.scope}Array_${this.id}`, this.scope.toLowerCase(), this.bufferType, this.bufferCount );
  24347. }
  24348. }
  24349. /**
  24350. * TSL function for creating a workgroup info node.
  24351. * Creates a new 'workgroup' scoped array buffer.
  24352. *
  24353. * @function
  24354. * @param {String} type - The data type of a 'workgroup' scoped buffer element.
  24355. * @param {Number} [count=0] - The number of elements in the buffer.
  24356. * @returns {WorkgroupInfoNode}
  24357. */
  24358. const workgroupArray = ( type, count ) => nodeObject( new WorkgroupInfoNode( 'Workgroup', type, count ) );
  24359. /** @module AtomicFunctionNode **/
  24360. /**
  24361. * `AtomicFunctionNode` represents any function that can operate on atomic variable types
  24362. * within a shader. In an atomic function, any modification to an atomic variable will
  24363. * occur as an indivisible step with a defined order relative to other modifications.
  24364. * Accordingly, even if multiple atomic functions are modifying an atomic variable at once
  24365. * atomic operations will not interfere with each other.
  24366. *
  24367. * This node can only be used with a WebGPU backend.
  24368. *
  24369. * @augments TempNode
  24370. */
  24371. class AtomicFunctionNode extends TempNode {
  24372. static get type() {
  24373. return 'AtomicFunctionNode';
  24374. }
  24375. /**
  24376. * Constructs a new atomic function node.
  24377. *
  24378. * @param {String} method - The signature of the atomic function to construct.
  24379. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24380. * @param {Node} valueNode - The value that mutates the atomic variable.
  24381. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24382. */
  24383. constructor( method, pointerNode, valueNode, storeNode = null ) {
  24384. super( 'uint' );
  24385. /**
  24386. * The signature of the atomic function to construct.
  24387. *
  24388. * @type {String}
  24389. */
  24390. this.method = method;
  24391. /**
  24392. * An atomic variable or element of an atomic buffer.
  24393. *
  24394. * @type {Node}
  24395. */
  24396. this.pointerNode = pointerNode;
  24397. /**
  24398. * A value that modifies the atomic variable.
  24399. *
  24400. * @type {Node}
  24401. */
  24402. this.valueNode = valueNode;
  24403. /**
  24404. * A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24405. *
  24406. * @type {Node?}
  24407. * @default null
  24408. */
  24409. this.storeNode = storeNode;
  24410. }
  24411. /**
  24412. * Overwrites the default implementation to return the type of
  24413. * the pointer node.
  24414. *
  24415. * @param {NodeBuilder} builder - The current node builder.
  24416. * @return {String} The input type.
  24417. */
  24418. getInputType( builder ) {
  24419. return this.pointerNode.getNodeType( builder );
  24420. }
  24421. /**
  24422. * Overwritten since the node type is inferred from the input type.
  24423. *
  24424. * @param {NodeBuilder} builder - The current node builder.
  24425. * @return {String} The node type.
  24426. */
  24427. getNodeType( builder ) {
  24428. return this.getInputType( builder );
  24429. }
  24430. generate( builder ) {
  24431. const method = this.method;
  24432. const type = this.getNodeType( builder );
  24433. const inputType = this.getInputType( builder );
  24434. const a = this.pointerNode;
  24435. const b = this.valueNode;
  24436. const params = [];
  24437. params.push( `&${ a.build( builder, inputType ) }` );
  24438. if ( b !== null ) {
  24439. params.push( b.build( builder, inputType ) );
  24440. }
  24441. const methodSnippet = `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`;
  24442. if ( this.storeNode !== null ) {
  24443. const varSnippet = this.storeNode.build( builder, inputType );
  24444. builder.addLineFlowCode( `${varSnippet} = ${methodSnippet}`, this );
  24445. } else {
  24446. builder.addLineFlowCode( methodSnippet, this );
  24447. }
  24448. }
  24449. }
  24450. AtomicFunctionNode.ATOMIC_LOAD = 'atomicLoad';
  24451. AtomicFunctionNode.ATOMIC_STORE = 'atomicStore';
  24452. AtomicFunctionNode.ATOMIC_ADD = 'atomicAdd';
  24453. AtomicFunctionNode.ATOMIC_SUB = 'atomicSub';
  24454. AtomicFunctionNode.ATOMIC_MAX = 'atomicMax';
  24455. AtomicFunctionNode.ATOMIC_MIN = 'atomicMin';
  24456. AtomicFunctionNode.ATOMIC_AND = 'atomicAnd';
  24457. AtomicFunctionNode.ATOMIC_OR = 'atomicOr';
  24458. AtomicFunctionNode.ATOMIC_XOR = 'atomicXor';
  24459. /**
  24460. * TSL function for creating an atomic function node.
  24461. *
  24462. * @function
  24463. * @param {String} method - The signature of the atomic function to construct.
  24464. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24465. * @param {Node} valueNode - The value that mutates the atomic variable.
  24466. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24467. * @returns {AtomicFunctionNode}
  24468. */
  24469. const atomicNode = nodeProxy( AtomicFunctionNode );
  24470. /**
  24471. * TSL function for appending an atomic function call into the programmatic flow of a compute shader.
  24472. *
  24473. * @function
  24474. * @param {String} method - The signature of the atomic function to construct.
  24475. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24476. * @param {Node} valueNode - The value that mutates the atomic variable.
  24477. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24478. * @returns {AtomicFunctionNode}
  24479. */
  24480. const atomicFunc = ( method, pointerNode, valueNode, storeNode = null ) => {
  24481. const node = atomicNode( method, pointerNode, valueNode, storeNode );
  24482. node.append();
  24483. return node;
  24484. };
  24485. /**
  24486. * Loads the value stored in the atomic variable.
  24487. *
  24488. * @function
  24489. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24490. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24491. * @returns {AtomicFunctionNode}
  24492. */
  24493. const atomicLoad = ( pointerNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_LOAD, pointerNode, null, storeNode );
  24494. /**
  24495. * Stores a value in the atomic variable.
  24496. *
  24497. * @function
  24498. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24499. * @param {Node} valueNode - The value that mutates the atomic variable.
  24500. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24501. * @returns {AtomicFunctionNode}
  24502. */
  24503. const atomicStore = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_STORE, pointerNode, valueNode, storeNode );
  24504. /**
  24505. * Increments the value stored in the atomic variable.
  24506. *
  24507. * @function
  24508. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24509. * @param {Node} valueNode - The value that mutates the atomic variable.
  24510. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24511. * @returns {AtomicFunctionNode}
  24512. */
  24513. const atomicAdd = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_ADD, pointerNode, valueNode, storeNode );
  24514. /**
  24515. * Decrements the value stored in the atomic variable.
  24516. *
  24517. * @function
  24518. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24519. * @param {Node} valueNode - The value that mutates the atomic variable.
  24520. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24521. * @returns {AtomicFunctionNode}
  24522. */
  24523. const atomicSub = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_SUB, pointerNode, valueNode, storeNode );
  24524. /**
  24525. * Stores in an atomic variable the maximum between its current value and a parameter.
  24526. *
  24527. * @function
  24528. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24529. * @param {Node} valueNode - The value that mutates the atomic variable.
  24530. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24531. * @returns {AtomicFunctionNode}
  24532. */
  24533. const atomicMax = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_MAX, pointerNode, valueNode, storeNode );
  24534. /**
  24535. * Stores in an atomic variable the minimum between its current value and a parameter.
  24536. *
  24537. * @function
  24538. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24539. * @param {Node} valueNode - The value that mutates the atomic variable.
  24540. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24541. * @returns {AtomicFunctionNode}
  24542. */
  24543. const atomicMin = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_MIN, pointerNode, valueNode, storeNode );
  24544. /**
  24545. * Stores in an atomic variable the bitwise AND of its value with a parameter.
  24546. *
  24547. * @function
  24548. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24549. * @param {Node} valueNode - The value that mutates the atomic variable.
  24550. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24551. * @returns {AtomicFunctionNode}
  24552. */
  24553. const atomicAnd = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_AND, pointerNode, valueNode, storeNode );
  24554. /**
  24555. * Stores in an atomic variable the bitwise OR of its value with a parameter.
  24556. *
  24557. * @function
  24558. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24559. * @param {Node} valueNode - The value that mutates the atomic variable.
  24560. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24561. * @returns {AtomicFunctionNode}
  24562. */
  24563. const atomicOr = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_OR, pointerNode, valueNode, storeNode );
  24564. /**
  24565. * Stores in an atomic variable the bitwise XOR of its value with a parameter.
  24566. *
  24567. * @function
  24568. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24569. * @param {Node} valueNode - The value that mutates the atomic variable.
  24570. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24571. * @returns {AtomicFunctionNode}
  24572. */
  24573. const atomicXor = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_XOR, pointerNode, valueNode, storeNode );
  24574. /** @module Lights **/
  24575. let uniformsLib;
  24576. function getLightData( light ) {
  24577. uniformsLib = uniformsLib || new WeakMap();
  24578. let uniforms = uniformsLib.get( light );
  24579. if ( uniforms === undefined ) uniformsLib.set( light, uniforms = {} );
  24580. return uniforms;
  24581. }
  24582. /**
  24583. * TSL function for getting a shadow matrix uniform node for the given light.
  24584. *
  24585. * @function
  24586. * @param {Light} light -The light source.
  24587. * @returns {UniformNode<mat4>} The shadow matrix uniform node.
  24588. */
  24589. function lightShadowMatrix( light ) {
  24590. const data = getLightData( light );
  24591. return data.shadowMatrix || ( data.shadowMatrix = uniform( 'mat4' ).setGroup( renderGroup ).onRenderUpdate( () => {
  24592. if ( light.castShadow !== true ) {
  24593. light.shadow.updateMatrices( light );
  24594. }
  24595. return light.shadow.matrix;
  24596. } ) );
  24597. }
  24598. /**
  24599. * TSL function for getting projected uv coordinates for the given light.
  24600. * Relevant when using maps with spot lights.
  24601. *
  24602. * @function
  24603. * @param {Light} light -The light source.
  24604. * @returns {Node<vec3>} The projected uvs.
  24605. */
  24606. function lightProjectionUV( light ) {
  24607. const data = getLightData( light );
  24608. if ( data.projectionUV === undefined ) {
  24609. const spotLightCoord = lightShadowMatrix( light ).mul( positionWorld );
  24610. data.projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  24611. }
  24612. return data.projectionUV;
  24613. }
  24614. /**
  24615. * TSL function for getting the position in world space for the given light.
  24616. *
  24617. * @function
  24618. * @param {Light} light -The light source.
  24619. * @returns {UniformNode<vec3>} The light's position in world space.
  24620. */
  24621. function lightPosition( light ) {
  24622. const data = getLightData( light );
  24623. return data.position || ( data.position = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.matrixWorld ) ) );
  24624. }
  24625. /**
  24626. * TSL function for getting the light target position in world space for the given light.
  24627. *
  24628. * @function
  24629. * @param {Light} light -The light source.
  24630. * @returns {UniformNode<vec3>} The light target position in world space.
  24631. */
  24632. function lightTargetPosition( light ) {
  24633. const data = getLightData( light );
  24634. return data.targetPosition || ( data.targetPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.target.matrixWorld ) ) );
  24635. }
  24636. /**
  24637. * TSL function for getting the position in view space for the given light.
  24638. *
  24639. * @function
  24640. * @param {Light} light -The light source.
  24641. * @returns {UniformNode<vec3>} The light's position in view space.
  24642. */
  24643. function lightViewPosition( light ) {
  24644. const data = getLightData( light );
  24645. return data.viewPosition || ( data.viewPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => {
  24646. self.value = self.value || new Vector3();
  24647. self.value.setFromMatrixPosition( light.matrixWorld );
  24648. self.value.applyMatrix4( camera.matrixWorldInverse );
  24649. } ) );
  24650. }
  24651. /**
  24652. * TSL function for getting the light target direction for the given light.
  24653. *
  24654. * @function
  24655. * @param {Light} light -The light source.
  24656. * @returns {Node<vec3>} The light's target direction.
  24657. */
  24658. const lightTargetDirection = ( light ) => cameraViewMatrix.transformDirection( lightPosition( light ).sub( lightTargetPosition( light ) ) );
  24659. /** @module LightsNode **/
  24660. const sortLights = ( lights ) => {
  24661. return lights.sort( ( a, b ) => a.id - b.id );
  24662. };
  24663. const getLightNodeById = ( id, lightNodes ) => {
  24664. for ( const lightNode of lightNodes ) {
  24665. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  24666. return lightNode;
  24667. }
  24668. }
  24669. return null;
  24670. };
  24671. const _lightsNodeRef = /*@__PURE__*/ new WeakMap();
  24672. /**
  24673. * This node represents the scene's lighting and manages the lighting model's life cycle
  24674. * for the current build 3D object. It is responsible for computing the total outgoing
  24675. * light in a given lighting context.
  24676. *
  24677. * @augments Node
  24678. */
  24679. class LightsNode extends Node {
  24680. static get type() {
  24681. return 'LightsNode';
  24682. }
  24683. /**
  24684. * Constructs a new lights node.
  24685. */
  24686. constructor() {
  24687. super( 'vec3' );
  24688. /**
  24689. * A node representing the total diffuse light.
  24690. *
  24691. * @type {Node<vec3>}
  24692. */
  24693. this.totalDiffuseNode = vec3().toVar( 'totalDiffuse' );
  24694. /**
  24695. * A node representing the total specular light.
  24696. *
  24697. * @type {Node<vec3>}
  24698. */
  24699. this.totalSpecularNode = vec3().toVar( 'totalSpecular' );
  24700. /**
  24701. * A node representing the outgoing light.
  24702. *
  24703. * @type {Node<vec3>}
  24704. */
  24705. this.outgoingLightNode = vec3().toVar( 'outgoingLight' );
  24706. /**
  24707. * An array representing the lights in the scene.
  24708. *
  24709. * @private
  24710. * @type {Array<Light>}
  24711. */
  24712. this._lights = [];
  24713. /**
  24714. * For each light in the scene, this node will create a
  24715. * corresponding light node.
  24716. *
  24717. * @private
  24718. * @type {Array<LightingNode>?}
  24719. * @default null
  24720. */
  24721. this._lightNodes = null;
  24722. /**
  24723. * A hash for identifying the current light nodes setup.
  24724. *
  24725. * @private
  24726. * @type {String?}
  24727. * @default null
  24728. */
  24729. this._lightNodesHash = null;
  24730. /**
  24731. * `LightsNode` sets this property to `true` by default.
  24732. *
  24733. * @type {Boolean}
  24734. * @default true
  24735. */
  24736. this.global = true;
  24737. }
  24738. /**
  24739. * Overwrites the default {@link Node#customCacheKey} implementation by including the
  24740. * light IDs into the cache key.
  24741. *
  24742. * @return {Number} The custom cache key.
  24743. */
  24744. customCacheKey() {
  24745. const lightIDs = [];
  24746. const lights = this._lights;
  24747. for ( let i = 0; i < lights.length; i ++ ) {
  24748. lightIDs.push( lights[ i ].id );
  24749. }
  24750. return hashArray( lightIDs );
  24751. }
  24752. /**
  24753. * Computes a hash value for identifying the current light nodes setup.
  24754. *
  24755. * @param {NodeBuilder} builder - A reference to the current node builder.
  24756. * @return {String} The computed hash.
  24757. */
  24758. getHash( builder ) {
  24759. if ( this._lightNodesHash === null ) {
  24760. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  24761. const hash = [];
  24762. for ( const lightNode of this._lightNodes ) {
  24763. hash.push( lightNode.getSelf().getHash() );
  24764. }
  24765. this._lightNodesHash = 'lights-' + hash.join( ',' );
  24766. }
  24767. return this._lightNodesHash;
  24768. }
  24769. analyze( builder ) {
  24770. const properties = builder.getDataFromNode( this );
  24771. for ( const node of properties.nodes ) {
  24772. node.build( builder );
  24773. }
  24774. }
  24775. /**
  24776. * Creates lighting nodes for each scene light. This makes it possible to further
  24777. * process lights in the node system.
  24778. *
  24779. * @param {NodeBuilder} builder - A reference to the current node builder.
  24780. */
  24781. setupLightsNode( builder ) {
  24782. const lightNodes = [];
  24783. const previousLightNodes = this._lightNodes;
  24784. const lights = sortLights( this._lights );
  24785. const nodeLibrary = builder.renderer.library;
  24786. for ( const light of lights ) {
  24787. if ( light.isNode ) {
  24788. lightNodes.push( nodeObject( light ) );
  24789. } else {
  24790. let lightNode = null;
  24791. if ( previousLightNodes !== null ) {
  24792. lightNode = getLightNodeById( light.id, previousLightNodes ); // reuse existing light node
  24793. }
  24794. if ( lightNode === null ) {
  24795. // find the corresponding node type for a given light
  24796. const lightNodeClass = nodeLibrary.getLightNodeClass( light.constructor );
  24797. if ( lightNodeClass === null ) {
  24798. console.warn( `LightsNode.setupNodeLights: Light node not found for ${ light.constructor.name }` );
  24799. continue;
  24800. }
  24801. let lightNode = null;
  24802. if ( ! _lightsNodeRef.has( light ) ) {
  24803. lightNode = nodeObject( new lightNodeClass( light ) );
  24804. _lightsNodeRef.set( light, lightNode );
  24805. } else {
  24806. lightNode = _lightsNodeRef.get( light );
  24807. }
  24808. lightNodes.push( lightNode );
  24809. }
  24810. }
  24811. }
  24812. this._lightNodes = lightNodes;
  24813. }
  24814. /**
  24815. * Setups the internal lights by building all respective
  24816. * light nodes.
  24817. *
  24818. * @param {NodeBuilder} builder - A reference to the current node builder.
  24819. * @param {Array<LightingNode>} lightNodes - An array of lighting nodes.
  24820. */
  24821. setupLights( builder, lightNodes ) {
  24822. for ( const lightNode of lightNodes ) {
  24823. lightNode.build( builder );
  24824. }
  24825. }
  24826. /**
  24827. * The implementation makes sure that for each light in the scene
  24828. * there is a corresponding light node. By building the light nodes
  24829. * and evaluating the lighting model the outgoing light is computed.
  24830. *
  24831. * @param {NodeBuilder} builder - A reference to the current node builder.
  24832. * @return {Node<vec3>} A node representing the outgoing light.
  24833. */
  24834. setup( builder ) {
  24835. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  24836. const context = builder.context;
  24837. const lightingModel = context.lightingModel;
  24838. let outgoingLightNode = this.outgoingLightNode;
  24839. if ( lightingModel ) {
  24840. const { _lightNodes, totalDiffuseNode, totalSpecularNode } = this;
  24841. context.outgoingLight = outgoingLightNode;
  24842. const stack = builder.addStack();
  24843. //
  24844. const properties = builder.getDataFromNode( this );
  24845. properties.nodes = stack.nodes;
  24846. //
  24847. lightingModel.start( context, stack, builder );
  24848. // lights
  24849. this.setupLights( builder, _lightNodes );
  24850. //
  24851. lightingModel.indirect( context, stack, builder );
  24852. //
  24853. const { backdrop, backdropAlpha } = context;
  24854. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  24855. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  24856. if ( backdrop !== null ) {
  24857. if ( backdropAlpha !== null ) {
  24858. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  24859. } else {
  24860. totalDiffuse = vec3( backdrop );
  24861. }
  24862. context.material.transparent = true;
  24863. }
  24864. totalDiffuseNode.assign( totalDiffuse );
  24865. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  24866. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  24867. //
  24868. lightingModel.finish( context, stack, builder );
  24869. //
  24870. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  24871. }
  24872. return outgoingLightNode;
  24873. }
  24874. /**
  24875. * Configures this node with an array of lights.
  24876. *
  24877. * @param {Array<Light>} lights - An array of lights.
  24878. * @return {LightsNode} A reference to this node.
  24879. */
  24880. setLights( lights ) {
  24881. this._lights = lights;
  24882. this._lightNodes = null;
  24883. this._lightNodesHash = null;
  24884. return this;
  24885. }
  24886. /**
  24887. * Returns an array of the scene's lights.
  24888. *
  24889. * @return {Array<Light>} The scene's lights.
  24890. */
  24891. getLights() {
  24892. return this._lights;
  24893. }
  24894. /**
  24895. * Whether the scene has lights or not.
  24896. *
  24897. * @type {Boolean}
  24898. */
  24899. get hasLights() {
  24900. return this._lights.length > 0;
  24901. }
  24902. }
  24903. /**
  24904. * TSL function for creating an instance of `LightsNode` and configuring
  24905. * it with the given array of lights.
  24906. *
  24907. * @function
  24908. * @param {Array<Light>} lights - An array of lights.
  24909. * @return {LightsNode} The created lights node.
  24910. */
  24911. const lights = ( lights = [] ) => nodeObject( new LightsNode() ).setLights( lights );
  24912. /** @module ShadowBaseNode **/
  24913. /**
  24914. * Base class for all shadow nodes.
  24915. *
  24916. * Shadow nodes encapsulate shadow related logic and are always coupled to lighting nodes.
  24917. * Lighting nodes might share the same shadow node type or use specific ones depending on
  24918. * their requirements.
  24919. *
  24920. * @augments Node
  24921. */
  24922. class ShadowBaseNode extends Node {
  24923. static get type() {
  24924. return 'ShadowBaseNode';
  24925. }
  24926. /**
  24927. * Constructs a new shadow base node.
  24928. *
  24929. * @param {Light} light - The shadow casting light.
  24930. */
  24931. constructor( light ) {
  24932. super();
  24933. /**
  24934. * The shadow casting light.
  24935. *
  24936. * @type {Light}
  24937. */
  24938. this.light = light;
  24939. /**
  24940. * Overwritten since shadows are updated by default per render.
  24941. *
  24942. * @type {String}
  24943. * @default 'render'
  24944. */
  24945. this.updateBeforeType = NodeUpdateType.RENDER;
  24946. /**
  24947. * This flag can be used for type testing.
  24948. *
  24949. * @type {Boolean}
  24950. * @readonly
  24951. * @default true
  24952. */
  24953. this.isShadowBaseNode = true;
  24954. }
  24955. /**
  24956. * Setups the shadow position node which is by default the predefined TSL node object `shadowPositionWorld`.
  24957. *
  24958. * @param {(NodeBuilder|{Material})} object - A configuration object that must at least hold a material reference.
  24959. */
  24960. setupShadowPosition( { material } ) {
  24961. // Use assign inside an Fn()
  24962. shadowPositionWorld.assign( material.shadowPositionNode || positionWorld );
  24963. }
  24964. /**
  24965. * Can be called when the shadow isn't required anymore. That can happen when
  24966. * a lighting node stops casting shadows by setting {@link Object3D#castShadow}
  24967. * to `false`.
  24968. */
  24969. dispose() {
  24970. this.updateBeforeType = NodeUpdateType.NONE;
  24971. }
  24972. }
  24973. /**
  24974. * TSL object that represents the vertex position in world space during the shadow pass.
  24975. *
  24976. * @type {Node<vec3>}
  24977. */
  24978. const shadowPositionWorld = /*@__PURE__*/ vec3().toVar( 'shadowPositionWorld' );
  24979. /** @module RendererUtils **/
  24980. /**
  24981. * Saves the state of the given renderer and stores it into the given state object.
  24982. *
  24983. * If not state object is provided, the function creates one.
  24984. *
  24985. * @function
  24986. * @param {Renderer} renderer - The renderer.
  24987. * @param {Object} [state={}] - The state.
  24988. * @return {Object} The state.
  24989. */
  24990. function saveRendererState( renderer, state = {} ) {
  24991. state.toneMapping = renderer.toneMapping;
  24992. state.toneMappingExposure = renderer.toneMappingExposure;
  24993. state.outputColorSpace = renderer.outputColorSpace;
  24994. state.renderTarget = renderer.getRenderTarget();
  24995. state.activeCubeFace = renderer.getActiveCubeFace();
  24996. state.activeMipmapLevel = renderer.getActiveMipmapLevel();
  24997. state.renderObjectFunction = renderer.getRenderObjectFunction();
  24998. state.pixelRatio = renderer.getPixelRatio();
  24999. state.mrt = renderer.getMRT();
  25000. state.clearColor = renderer.getClearColor( state.clearColor || new Color() );
  25001. state.clearAlpha = renderer.getClearAlpha();
  25002. state.autoClear = renderer.autoClear;
  25003. state.scissorTest = renderer.getScissorTest();
  25004. return state;
  25005. }
  25006. /**
  25007. * Saves the state of the given renderer and stores it into the given state object.
  25008. * Besides, the function also resets the state of the renderer to its default values.
  25009. *
  25010. * If not state object is provided, the function creates one.
  25011. *
  25012. * @function
  25013. * @param {Renderer} renderer - The renderer.
  25014. * @param {Object} [state={}] - The state.
  25015. * @return {Object} The state.
  25016. */
  25017. function resetRendererState( renderer, state ) {
  25018. state = saveRendererState( renderer, state );
  25019. renderer.setMRT( null );
  25020. renderer.setRenderObjectFunction( null );
  25021. renderer.setClearColor( 0x000000, 1 );
  25022. renderer.autoClear = true;
  25023. return state;
  25024. }
  25025. /**
  25026. * Restores the state of the given renderer from the given state object.
  25027. *
  25028. * @function
  25029. * @param {Renderer} renderer - The renderer.
  25030. * @param {Object} state - The state to restore.
  25031. */
  25032. function restoreRendererState( renderer, state ) {
  25033. renderer.toneMapping = state.toneMapping;
  25034. renderer.toneMappingExposure = state.toneMappingExposure;
  25035. renderer.outputColorSpace = state.outputColorSpace;
  25036. renderer.setRenderTarget( state.renderTarget, state.activeCubeFace, state.activeMipmapLevel );
  25037. renderer.setRenderObjectFunction( state.renderObjectFunction );
  25038. renderer.setPixelRatio( state.pixelRatio );
  25039. renderer.setMRT( state.mrt );
  25040. renderer.setClearColor( state.clearColor, state.clearAlpha );
  25041. renderer.autoClear = state.autoClear;
  25042. renderer.setScissorTest( state.scissorTest );
  25043. }
  25044. /**
  25045. * Saves the state of the given scene and stores it into the given state object.
  25046. *
  25047. * If not state object is provided, the function creates one.
  25048. *
  25049. * @function
  25050. * @param {Scene} scene - The scene.
  25051. * @param {Object} [state={}] - The state.
  25052. * @return {Object} The state.
  25053. */
  25054. function saveSceneState( scene, state = {} ) {
  25055. state.background = scene.background;
  25056. state.backgroundNode = scene.backgroundNode;
  25057. state.overrideMaterial = scene.overrideMaterial;
  25058. return state;
  25059. }
  25060. /**
  25061. * Saves the state of the given scene and stores it into the given state object.
  25062. * Besides, the function also resets the state of the scene to its default values.
  25063. *
  25064. * If not state object is provided, the function creates one.
  25065. *
  25066. * @function
  25067. * @param {Scene} scene - The scene.
  25068. * @param {Object} [state={}] - The state.
  25069. * @return {Object} The state.
  25070. */
  25071. function resetSceneState( scene, state ) {
  25072. state = saveSceneState( scene, state );
  25073. scene.background = null;
  25074. scene.backgroundNode = null;
  25075. scene.overrideMaterial = null;
  25076. return state;
  25077. }
  25078. /**
  25079. * Restores the state of the given scene from the given state object.
  25080. *
  25081. * @function
  25082. * @param {Scene} scene - The scene.
  25083. * @param {Object} state - The state to restore.
  25084. */
  25085. function restoreSceneState( scene, state ) {
  25086. scene.background = state.background;
  25087. scene.backgroundNode = state.backgroundNode;
  25088. scene.overrideMaterial = state.overrideMaterial;
  25089. }
  25090. /**
  25091. * Saves the state of the given renderer and scene and stores it into the given state object.
  25092. *
  25093. * If not state object is provided, the function creates one.
  25094. *
  25095. * @function
  25096. * @param {Renderer} renderer - The renderer.
  25097. * @param {Scene} scene - The scene.
  25098. * @param {Object} [state={}] - The state.
  25099. * @return {Object} The state.
  25100. */
  25101. function saveRendererAndSceneState( renderer, scene, state = {} ) {
  25102. state = saveRendererState( renderer, state );
  25103. state = saveSceneState( scene, state );
  25104. return state;
  25105. }
  25106. /**
  25107. * Saves the state of the given renderer and scene and stores it into the given state object.
  25108. * Besides, the function also resets the state of the renderer and scene to its default values.
  25109. *
  25110. * If not state object is provided, the function creates one.
  25111. *
  25112. * @function
  25113. * @param {Renderer} renderer - The renderer.
  25114. * @param {Scene} scene - The scene.
  25115. * @param {Object} [state={}] - The state.
  25116. * @return {Object} The state.
  25117. */
  25118. function resetRendererAndSceneState( renderer, scene, state ) {
  25119. state = resetRendererState( renderer, state );
  25120. state = resetSceneState( scene, state );
  25121. return state;
  25122. }
  25123. /**
  25124. * Restores the state of the given renderer and scene from the given state object.
  25125. *
  25126. * @function
  25127. * @param {Renderer} renderer - The renderer.
  25128. * @param {Scene} scene - The scene.
  25129. * @param {Object} state - The state to restore.
  25130. */
  25131. function restoreRendererAndSceneState( renderer, scene, state ) {
  25132. restoreRendererState( renderer, state );
  25133. restoreSceneState( scene, state );
  25134. }
  25135. var RendererUtils = /*#__PURE__*/Object.freeze({
  25136. __proto__: null,
  25137. resetRendererAndSceneState: resetRendererAndSceneState,
  25138. resetRendererState: resetRendererState,
  25139. resetSceneState: resetSceneState,
  25140. restoreRendererAndSceneState: restoreRendererAndSceneState,
  25141. restoreRendererState: restoreRendererState,
  25142. restoreSceneState: restoreSceneState,
  25143. saveRendererAndSceneState: saveRendererAndSceneState,
  25144. saveRendererState: saveRendererState,
  25145. saveSceneState: saveSceneState
  25146. });
  25147. /** @module ShadowNode **/
  25148. const shadowMaterialLib = /*@__PURE__*/ new WeakMap();
  25149. const linearDistance = /*@__PURE__*/ Fn( ( [ position, cameraNear, cameraFar ] ) => {
  25150. let dist = positionWorld.sub( position ).length();
  25151. dist = dist.sub( cameraNear ).div( cameraFar.sub( cameraNear ) );
  25152. dist = dist.saturate(); // clamp to [ 0, 1 ]
  25153. return dist;
  25154. } );
  25155. const linearShadowDistance = ( light ) => {
  25156. const camera = light.shadow.camera;
  25157. const nearDistance = reference( 'near', 'float', camera ).setGroup( renderGroup );
  25158. const farDistance = reference( 'far', 'float', camera ).setGroup( renderGroup );
  25159. const referencePosition = objectPosition( light );
  25160. return linearDistance( referencePosition, nearDistance, farDistance );
  25161. };
  25162. const getShadowMaterial = ( light ) => {
  25163. let material = shadowMaterialLib.get( light );
  25164. if ( material === undefined ) {
  25165. const depthNode = light.isPointLight ? linearShadowDistance( light ) : null;
  25166. material = new NodeMaterial();
  25167. material.colorNode = vec4( 0, 0, 0, 1 );
  25168. material.depthNode = depthNode;
  25169. material.isShadowPassMaterial = true; // Use to avoid other overrideMaterial override material.colorNode unintentionally when using material.shadowNode
  25170. material.name = 'ShadowMaterial';
  25171. material.fog = false;
  25172. shadowMaterialLib.set( light, material );
  25173. }
  25174. return material;
  25175. };
  25176. /**
  25177. * A shadow filtering function performing basic filtering. This is in fact an unfiltered version of the shadow map
  25178. * with a binary `[0,1]` result.
  25179. *
  25180. * @method
  25181. * @param {Object} inputs - The input parameter object.
  25182. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  25183. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  25184. * @return {Node<float>} The filtering result.
  25185. */
  25186. const BasicShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord } ) => {
  25187. return texture( depthTexture, shadowCoord.xy ).compare( shadowCoord.z );
  25188. } );
  25189. /**
  25190. * A shadow filtering function performing PCF filtering.
  25191. *
  25192. * @method
  25193. * @param {Object} inputs - The input parameter object.
  25194. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  25195. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  25196. * @param {LightShadow} inputs.shadow - The light shadow.
  25197. * @return {Node<float>} The filtering result.
  25198. */
  25199. const PCFShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow } ) => {
  25200. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  25201. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  25202. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  25203. const texelSize = vec2( 1 ).div( mapSize );
  25204. const dx0 = texelSize.x.negate().mul( radius );
  25205. const dy0 = texelSize.y.negate().mul( radius );
  25206. const dx1 = texelSize.x.mul( radius );
  25207. const dy1 = texelSize.y.mul( radius );
  25208. const dx2 = dx0.div( 2 );
  25209. const dy2 = dy0.div( 2 );
  25210. const dx3 = dx1.div( 2 );
  25211. const dy3 = dy1.div( 2 );
  25212. return add(
  25213. depthCompare( shadowCoord.xy.add( vec2( dx0, dy0 ) ), shadowCoord.z ),
  25214. depthCompare( shadowCoord.xy.add( vec2( 0, dy0 ) ), shadowCoord.z ),
  25215. depthCompare( shadowCoord.xy.add( vec2( dx1, dy0 ) ), shadowCoord.z ),
  25216. depthCompare( shadowCoord.xy.add( vec2( dx2, dy2 ) ), shadowCoord.z ),
  25217. depthCompare( shadowCoord.xy.add( vec2( 0, dy2 ) ), shadowCoord.z ),
  25218. depthCompare( shadowCoord.xy.add( vec2( dx3, dy2 ) ), shadowCoord.z ),
  25219. depthCompare( shadowCoord.xy.add( vec2( dx0, 0 ) ), shadowCoord.z ),
  25220. depthCompare( shadowCoord.xy.add( vec2( dx2, 0 ) ), shadowCoord.z ),
  25221. depthCompare( shadowCoord.xy, shadowCoord.z ),
  25222. depthCompare( shadowCoord.xy.add( vec2( dx3, 0 ) ), shadowCoord.z ),
  25223. depthCompare( shadowCoord.xy.add( vec2( dx1, 0 ) ), shadowCoord.z ),
  25224. depthCompare( shadowCoord.xy.add( vec2( dx2, dy3 ) ), shadowCoord.z ),
  25225. depthCompare( shadowCoord.xy.add( vec2( 0, dy3 ) ), shadowCoord.z ),
  25226. depthCompare( shadowCoord.xy.add( vec2( dx3, dy3 ) ), shadowCoord.z ),
  25227. depthCompare( shadowCoord.xy.add( vec2( dx0, dy1 ) ), shadowCoord.z ),
  25228. depthCompare( shadowCoord.xy.add( vec2( 0, dy1 ) ), shadowCoord.z ),
  25229. depthCompare( shadowCoord.xy.add( vec2( dx1, dy1 ) ), shadowCoord.z )
  25230. ).mul( 1 / 17 );
  25231. } );
  25232. /**
  25233. * A shadow filtering function performing PCF soft filtering.
  25234. *
  25235. * @method
  25236. * @param {Object} inputs - The input parameter object.
  25237. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  25238. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  25239. * @param {LightShadow} inputs.shadow - The light shadow.
  25240. * @return {Node<float>} The filtering result.
  25241. */
  25242. const PCFSoftShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow } ) => {
  25243. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  25244. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  25245. const texelSize = vec2( 1 ).div( mapSize );
  25246. const dx = texelSize.x;
  25247. const dy = texelSize.y;
  25248. const uv = shadowCoord.xy;
  25249. const f = fract( uv.mul( mapSize ).add( 0.5 ) );
  25250. uv.subAssign( f.mul( texelSize ) );
  25251. return add(
  25252. depthCompare( uv, shadowCoord.z ),
  25253. depthCompare( uv.add( vec2( dx, 0 ) ), shadowCoord.z ),
  25254. depthCompare( uv.add( vec2( 0, dy ) ), shadowCoord.z ),
  25255. depthCompare( uv.add( texelSize ), shadowCoord.z ),
  25256. mix(
  25257. depthCompare( uv.add( vec2( dx.negate(), 0 ) ), shadowCoord.z ),
  25258. depthCompare( uv.add( vec2( dx.mul( 2 ), 0 ) ), shadowCoord.z ),
  25259. f.x
  25260. ),
  25261. mix(
  25262. depthCompare( uv.add( vec2( dx.negate(), dy ) ), shadowCoord.z ),
  25263. depthCompare( uv.add( vec2( dx.mul( 2 ), dy ) ), shadowCoord.z ),
  25264. f.x
  25265. ),
  25266. mix(
  25267. depthCompare( uv.add( vec2( 0, dy.negate() ) ), shadowCoord.z ),
  25268. depthCompare( uv.add( vec2( 0, dy.mul( 2 ) ) ), shadowCoord.z ),
  25269. f.y
  25270. ),
  25271. mix(
  25272. depthCompare( uv.add( vec2( dx, dy.negate() ) ), shadowCoord.z ),
  25273. depthCompare( uv.add( vec2( dx, dy.mul( 2 ) ) ), shadowCoord.z ),
  25274. f.y
  25275. ),
  25276. mix(
  25277. mix(
  25278. depthCompare( uv.add( vec2( dx.negate(), dy.negate() ) ), shadowCoord.z ),
  25279. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.negate() ) ), shadowCoord.z ),
  25280. f.x
  25281. ),
  25282. mix(
  25283. depthCompare( uv.add( vec2( dx.negate(), dy.mul( 2 ) ) ), shadowCoord.z ),
  25284. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.mul( 2 ) ) ), shadowCoord.z ),
  25285. f.x
  25286. ),
  25287. f.y
  25288. )
  25289. ).mul( 1 / 9 );
  25290. } );
  25291. /**
  25292. * A shadow filtering function performing VSM filtering.
  25293. *
  25294. * @method
  25295. * @param {Object} inputs - The input parameter object.
  25296. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  25297. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  25298. * @return {Node<float>} The filtering result.
  25299. */
  25300. const VSMShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord } ) => {
  25301. const occlusion = float( 1 ).toVar();
  25302. const distribution = texture( depthTexture ).sample( shadowCoord.xy ).rg;
  25303. const hardShadow = step( shadowCoord.z, distribution.x );
  25304. If( hardShadow.notEqual( float( 1.0 ) ), () => {
  25305. const distance = shadowCoord.z.sub( distribution.x );
  25306. const variance = max$1( 0, distribution.y.mul( distribution.y ) );
  25307. let softnessProbability = variance.div( variance.add( distance.mul( distance ) ) ); // Chebeyshevs inequality
  25308. softnessProbability = clamp( sub( softnessProbability, 0.3 ).div( 0.95 - 0.3 ) );
  25309. occlusion.assign( clamp( max$1( hardShadow, softnessProbability ) ) );
  25310. } );
  25311. return occlusion;
  25312. } );
  25313. /**
  25314. * Represents the shader code for the first VSM render pass.
  25315. *
  25316. * @method
  25317. * @param {Object} inputs - The input parameter object.
  25318. * @param {Node<float>} inputs.samples - The number of samples
  25319. * @param {Node<float>} inputs.radius - The radius.
  25320. * @param {Node<float>} inputs.size - The size.
  25321. * @param {TextureNode} inputs.shadowPass - A reference to the render target's depth data.
  25322. * @return {Node<vec2>} The VSM output.
  25323. */
  25324. const VSMPassVertical = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass } ) => {
  25325. const mean = float( 0 ).toVar();
  25326. const squaredMean = float( 0 ).toVar();
  25327. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  25328. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( -1 ) );
  25329. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  25330. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  25331. const depth = shadowPass.sample( add( screenCoordinate.xy, vec2( 0, uvOffset ).mul( radius ) ).div( size ) ).x;
  25332. mean.addAssign( depth );
  25333. squaredMean.addAssign( depth.mul( depth ) );
  25334. } );
  25335. mean.divAssign( samples );
  25336. squaredMean.divAssign( samples );
  25337. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  25338. return vec2( mean, std_dev );
  25339. } );
  25340. /**
  25341. * Represents the shader code for the second VSM render pass.
  25342. *
  25343. * @method
  25344. * @param {Object} inputs - The input parameter object.
  25345. * @param {Node<float>} inputs.samples - The number of samples
  25346. * @param {Node<float>} inputs.radius - The radius.
  25347. * @param {Node<float>} inputs.size - The size.
  25348. * @param {TextureNode} inputs.shadowPass - The result of the first VSM render pass.
  25349. * @return {Node<vec2>} The VSM output.
  25350. */
  25351. const VSMPassHorizontal = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass } ) => {
  25352. const mean = float( 0 ).toVar();
  25353. const squaredMean = float( 0 ).toVar();
  25354. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  25355. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( -1 ) );
  25356. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  25357. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  25358. const distribution = shadowPass.sample( add( screenCoordinate.xy, vec2( uvOffset, 0 ).mul( radius ) ).div( size ) );
  25359. mean.addAssign( distribution.x );
  25360. squaredMean.addAssign( add( distribution.y.mul( distribution.y ), distribution.x.mul( distribution.x ) ) );
  25361. } );
  25362. mean.divAssign( samples );
  25363. squaredMean.divAssign( samples );
  25364. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  25365. return vec2( mean, std_dev );
  25366. } );
  25367. const _shadowFilterLib = [ BasicShadowFilter, PCFShadowFilter, PCFSoftShadowFilter, VSMShadowFilter ];
  25368. //
  25369. let _rendererState;
  25370. const _quadMesh = /*@__PURE__*/ new QuadMesh();
  25371. /**
  25372. * Represents the default shadow implementation for lighting nodes.
  25373. *
  25374. * @augments module:ShadowBaseNode~ShadowBaseNode
  25375. */
  25376. class ShadowNode extends ShadowBaseNode {
  25377. static get type() {
  25378. return 'ShadowNode';
  25379. }
  25380. /**
  25381. * Constructs a new shadow node.
  25382. *
  25383. * @param {Light} light - The shadow casting light.
  25384. * @param {LightShadow?} [shadow=null] - An optional light shadow.
  25385. */
  25386. constructor( light, shadow = null ) {
  25387. super( light );
  25388. /**
  25389. * The light shadow which defines the properties light's
  25390. * shadow.
  25391. *
  25392. * @type {LightShadow?}
  25393. * @default null
  25394. */
  25395. this.shadow = shadow || light.shadow;
  25396. /**
  25397. * A reference to the shadow map which is a render target.
  25398. *
  25399. * @type {RenderTarget?}
  25400. * @default null
  25401. */
  25402. this.shadowMap = null;
  25403. /**
  25404. * Only relevant for VSM shadows. Render target for the
  25405. * first VSM render pass.
  25406. *
  25407. * @type {RenderTarget?}
  25408. * @default null
  25409. */
  25410. this.vsmShadowMapVertical = null;
  25411. /**
  25412. * Only relevant for VSM shadows. Render target for the
  25413. * second VSM render pass.
  25414. *
  25415. * @type {RenderTarget?}
  25416. * @default null
  25417. */
  25418. this.vsmShadowMapHorizontal = null;
  25419. /**
  25420. * Only relevant for VSM shadows. Node material which
  25421. * is used to render the first VSM pass.
  25422. *
  25423. * @type {NodeMaterial?}
  25424. * @default null
  25425. */
  25426. this.vsmMaterialVertical = null;
  25427. /**
  25428. * Only relevant for VSM shadows. Node material which
  25429. * is used to render the second VSM pass.
  25430. *
  25431. * @type {NodeMaterial?}
  25432. * @default null
  25433. */
  25434. this.vsmMaterialHorizontal = null;
  25435. /**
  25436. * A reference to the output node which defines the
  25437. * final result of this shadow node.
  25438. *
  25439. * @type {Node?}
  25440. * @private
  25441. * @default null
  25442. */
  25443. this._node = null;
  25444. /**
  25445. * This flag can be used for type testing.
  25446. *
  25447. * @type {Boolean}
  25448. * @readonly
  25449. * @default true
  25450. */
  25451. this.isShadowNode = true;
  25452. }
  25453. /**
  25454. * Setups the shadow filtering.
  25455. *
  25456. * @param {NodeBuilder} builder - A reference to the current node builder.
  25457. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  25458. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  25459. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  25460. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  25461. * @param {LightShadow} inputs.shadow - The light shadow.
  25462. * @return {Node<float>} The result node of the shadow filtering.
  25463. */
  25464. setupShadowFilter( builder, { filterFn, depthTexture, shadowCoord, shadow } ) {
  25465. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  25466. .and( shadowCoord.x.lessThanEqual( 1 ) )
  25467. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  25468. .and( shadowCoord.y.lessThanEqual( 1 ) )
  25469. .and( shadowCoord.z.lessThanEqual( 1 ) );
  25470. const shadowNode = filterFn( { depthTexture, shadowCoord, shadow } );
  25471. return frustumTest.select( shadowNode, float( 1 ) );
  25472. }
  25473. /**
  25474. * Setups the shadow coordinates.
  25475. *
  25476. * @param {NodeBuilder} builder - A reference to the current node builder.
  25477. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  25478. * @return {Node<vec3>} The shadow coordinates.
  25479. */
  25480. setupShadowCoord( builder, shadowPosition ) {
  25481. const { shadow } = this;
  25482. const { renderer } = builder;
  25483. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  25484. let shadowCoord = shadowPosition;
  25485. let coordZ;
  25486. if ( shadow.camera.isOrthographicCamera || renderer.logarithmicDepthBuffer !== true ) {
  25487. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  25488. coordZ = shadowCoord.z;
  25489. if ( renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  25490. coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Conversion [ 0, 1 ] to [ - 1, 1 ]
  25491. }
  25492. } else {
  25493. const w = shadowCoord.w;
  25494. shadowCoord = shadowCoord.xy.div( w ); // <-- Only divide X/Y coords since we don't need Z
  25495. // The normally available "cameraNear" and "cameraFar" nodes cannot be used here because they do not get
  25496. // updated to use the shadow camera. So, we have to declare our own "local" ones here.
  25497. // TODO: How do we get the cameraNear/cameraFar nodes to use the shadow camera so we don't have to declare local ones here?
  25498. const cameraNearLocal = reference( 'near', 'float', shadow.camera ).setGroup( renderGroup );
  25499. const cameraFarLocal = reference( 'far', 'float', shadow.camera ).setGroup( renderGroup );
  25500. coordZ = viewZToLogarithmicDepth( w.negate(), cameraNearLocal, cameraFarLocal );
  25501. }
  25502. shadowCoord = vec3(
  25503. shadowCoord.x,
  25504. shadowCoord.y.oneMinus(), // follow webgpu standards
  25505. coordZ.add( bias )
  25506. );
  25507. return shadowCoord;
  25508. }
  25509. /**
  25510. * Returns the shadow filtering function for the given shadow type.
  25511. *
  25512. * @param {Number} type - The shadow type.
  25513. * @return {Function} The filtering function.
  25514. */
  25515. getShadowFilterFn( type ) {
  25516. return _shadowFilterLib[ type ];
  25517. }
  25518. /**
  25519. * Setups the shadow output node.
  25520. *
  25521. * @param {NodeBuilder} builder - A reference to the current node builder.
  25522. * @return {Node<vec3>} The shadow output node.
  25523. */
  25524. setupShadow( builder ) {
  25525. const { renderer } = builder;
  25526. const { light, shadow } = this;
  25527. const shadowMapType = renderer.shadowMap.type;
  25528. const depthTexture = new DepthTexture( shadow.mapSize.width, shadow.mapSize.height );
  25529. depthTexture.compareFunction = LessCompare;
  25530. const shadowMap = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  25531. shadowMap.depthTexture = depthTexture;
  25532. shadow.camera.updateProjectionMatrix();
  25533. // VSM
  25534. if ( shadowMapType === VSMShadowMap ) {
  25535. depthTexture.compareFunction = null; // VSM does not use textureSampleCompare()/texture2DCompare()
  25536. this.vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } );
  25537. this.vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } );
  25538. const shadowPassVertical = texture( depthTexture );
  25539. const shadowPassHorizontal = texture( this.vsmShadowMapVertical.texture );
  25540. const samples = reference( 'blurSamples', 'float', shadow ).setGroup( renderGroup );
  25541. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  25542. const size = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  25543. let material = this.vsmMaterialVertical || ( this.vsmMaterialVertical = new NodeMaterial() );
  25544. material.fragmentNode = VSMPassVertical( { samples, radius, size, shadowPass: shadowPassVertical } ).context( builder.getSharedContext() );
  25545. material.name = 'VSMVertical';
  25546. material = this.vsmMaterialHorizontal || ( this.vsmMaterialHorizontal = new NodeMaterial() );
  25547. material.fragmentNode = VSMPassHorizontal( { samples, radius, size, shadowPass: shadowPassHorizontal } ).context( builder.getSharedContext() );
  25548. material.name = 'VSMHorizontal';
  25549. }
  25550. //
  25551. const shadowIntensity = reference( 'intensity', 'float', shadow ).setGroup( renderGroup );
  25552. const normalBias = reference( 'normalBias', 'float', shadow ).setGroup( renderGroup );
  25553. const shadowPosition = lightShadowMatrix( light ).mul( shadowPositionWorld.add( transformedNormalWorld.mul( normalBias ) ) );
  25554. const shadowCoord = this.setupShadowCoord( builder, shadowPosition );
  25555. //
  25556. const filterFn = shadow.filterNode || this.getShadowFilterFn( renderer.shadowMap.type ) || null;
  25557. if ( filterFn === null ) {
  25558. throw new Error( 'THREE.WebGPURenderer: Shadow map type not supported yet.' );
  25559. }
  25560. const shadowDepthTexture = ( shadowMapType === VSMShadowMap ) ? this.vsmShadowMapHorizontal.texture : depthTexture;
  25561. const shadowNode = this.setupShadowFilter( builder, { filterFn, shadowTexture: shadowMap.texture, depthTexture: shadowDepthTexture, shadowCoord, shadow } );
  25562. const shadowColor = texture( shadowMap.texture, shadowCoord );
  25563. const shadowOutput = mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) ).toVar();
  25564. this.shadowMap = shadowMap;
  25565. this.shadow.map = shadowMap;
  25566. return shadowOutput;
  25567. }
  25568. /**
  25569. * The implementation performs the setup of the output node. An output is only
  25570. * produces if shadow mapping is globally enabled in the renderer.
  25571. *
  25572. * @param {NodeBuilder} builder - A reference to the current node builder.
  25573. * @return {ShaderCallNodeInternal} The output node.
  25574. */
  25575. setup( builder ) {
  25576. if ( builder.renderer.shadowMap.enabled === false ) return;
  25577. return Fn( () => {
  25578. let node = this._node;
  25579. this.setupShadowPosition( builder );
  25580. if ( node === null ) {
  25581. this._node = node = this.setupShadow( builder );
  25582. }
  25583. if ( builder.material.shadowNode ) { // @deprecated, r171
  25584. console.warn( 'THREE.NodeMaterial: ".shadowNode" is deprecated. Use ".castShadowNode" instead.' );
  25585. }
  25586. if ( builder.material.receivedShadowNode ) {
  25587. node = builder.material.receivedShadowNode( node );
  25588. }
  25589. return node;
  25590. } )();
  25591. }
  25592. /**
  25593. * Renders the shadow. The logic of this function could be included
  25594. * into {@link ShadowNode#updateShadow} however more specialized shadow
  25595. * nodes might require a custom shadow map rendering. By having a
  25596. * dedicated method, it's easier to overwrite the default behavior.
  25597. *
  25598. * @param {NodeFrame} frame - A reference to the current node frame.
  25599. */
  25600. renderShadow( frame ) {
  25601. const { shadow, shadowMap, light } = this;
  25602. const { renderer, scene } = frame;
  25603. shadow.updateMatrices( light );
  25604. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.height );
  25605. renderer.render( scene, shadow.camera );
  25606. }
  25607. /**
  25608. * Updates the shadow.
  25609. *
  25610. * @param {NodeFrame} frame - A reference to the current node frame.
  25611. */
  25612. updateShadow( frame ) {
  25613. const { shadowMap, light, shadow } = this;
  25614. const { renderer, scene, camera } = frame;
  25615. const shadowType = renderer.shadowMap.type;
  25616. const depthVersion = shadowMap.depthTexture.version;
  25617. this._depthVersionCached = depthVersion;
  25618. shadow.camera.layers.mask = camera.layers.mask;
  25619. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  25620. const currentMRT = renderer.getMRT();
  25621. const useVelocity = currentMRT ? currentMRT.has( 'velocity' ) : false;
  25622. _rendererState = resetRendererAndSceneState( renderer, scene, _rendererState );
  25623. scene.overrideMaterial = getShadowMaterial( light );
  25624. renderer.setRenderObjectFunction( ( object, scene, _camera, geometry, material, group, ...params ) => {
  25625. if ( object.castShadow === true || ( object.receiveShadow && shadowType === VSMShadowMap ) ) {
  25626. if ( useVelocity ) {
  25627. getDataFromObject( object ).useVelocity = true;
  25628. }
  25629. object.onBeforeShadow( renderer, object, camera, shadow.camera, geometry, scene.overrideMaterial, group );
  25630. renderer.renderObject( object, scene, _camera, geometry, material, group, ...params );
  25631. object.onAfterShadow( renderer, object, camera, shadow.camera, geometry, scene.overrideMaterial, group );
  25632. }
  25633. } );
  25634. renderer.setRenderTarget( shadowMap );
  25635. this.renderShadow( frame );
  25636. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  25637. // vsm blur pass
  25638. if ( light.isPointLight !== true && shadowType === VSMShadowMap ) {
  25639. this.vsmPass( renderer );
  25640. }
  25641. restoreRendererAndSceneState( renderer, scene, _rendererState );
  25642. }
  25643. /**
  25644. * For VSM additional render passes are required.
  25645. *
  25646. * @param {Renderer} renderer - A reference to the current renderer.
  25647. */
  25648. vsmPass( renderer ) {
  25649. const { shadow } = this;
  25650. this.vsmShadowMapVertical.setSize( shadow.mapSize.width, shadow.mapSize.height );
  25651. this.vsmShadowMapHorizontal.setSize( shadow.mapSize.width, shadow.mapSize.height );
  25652. renderer.setRenderTarget( this.vsmShadowMapVertical );
  25653. _quadMesh.material = this.vsmMaterialVertical;
  25654. _quadMesh.render( renderer );
  25655. renderer.setRenderTarget( this.vsmShadowMapHorizontal );
  25656. _quadMesh.material = this.vsmMaterialHorizontal;
  25657. _quadMesh.render( renderer );
  25658. }
  25659. /**
  25660. * Frees the internal resources of this shadow node.
  25661. */
  25662. dispose() {
  25663. this.shadowMap.dispose();
  25664. this.shadowMap = null;
  25665. if ( this.vsmShadowMapVertical !== null ) {
  25666. this.vsmShadowMapVertical.dispose();
  25667. this.vsmShadowMapVertical = null;
  25668. this.vsmMaterialVertical.dispose();
  25669. this.vsmMaterialVertical = null;
  25670. }
  25671. if ( this.vsmShadowMapHorizontal !== null ) {
  25672. this.vsmShadowMapHorizontal.dispose();
  25673. this.vsmShadowMapHorizontal = null;
  25674. this.vsmMaterialHorizontal.dispose();
  25675. this.vsmMaterialHorizontal = null;
  25676. }
  25677. super.dispose();
  25678. }
  25679. /**
  25680. * The implementation performs the update of the shadow map if necessary.
  25681. *
  25682. * @param {NodeFrame} frame - A reference to the current node frame.
  25683. */
  25684. updateBefore( frame ) {
  25685. const { shadow } = this;
  25686. const needsUpdate = shadow.needsUpdate || shadow.autoUpdate;
  25687. if ( needsUpdate ) {
  25688. this.updateShadow( frame );
  25689. if ( this.shadowMap.depthTexture.version === this._depthVersionCached ) {
  25690. shadow.needsUpdate = false;
  25691. }
  25692. }
  25693. }
  25694. }
  25695. /**
  25696. * TSL function for creating an instance of `ShadowNode`.
  25697. *
  25698. * @function
  25699. * @param {Light} light - The shadow casting light.
  25700. * @param {LightShadow} shadow - The light shadow.
  25701. * @return {ShadowNode} The created shadow node.
  25702. */
  25703. const shadow = ( light, shadow ) => nodeObject( new ShadowNode( light, shadow ) );
  25704. /**
  25705. * Base class for analytic light nodes.
  25706. *
  25707. * @augments LightingNode
  25708. */
  25709. class AnalyticLightNode extends LightingNode {
  25710. static get type() {
  25711. return 'AnalyticLightNode';
  25712. }
  25713. /**
  25714. * Constructs a new analytic light node.
  25715. *
  25716. * @param {Light?} [light=null] - The light source.
  25717. */
  25718. constructor( light = null ) {
  25719. super();
  25720. /**
  25721. * The light source.
  25722. *
  25723. * @type {Light?}
  25724. * @default null
  25725. */
  25726. this.light = light;
  25727. /**
  25728. * The light's color value.
  25729. *
  25730. * @type {Color}
  25731. */
  25732. this.color = new Color();
  25733. /**
  25734. * The light's color node. Points to `colorNode` of the light source, if set. Otherwise
  25735. * it creates a uniform node based on {@link AnalyticLightNode#color}.
  25736. *
  25737. * @type {Node}
  25738. */
  25739. this.colorNode = ( light && light.colorNode ) || uniform( this.color ).setGroup( renderGroup );
  25740. /**
  25741. * This property is used to retain a reference to the original value of {@link AnalyticLightNode#colorNode}.
  25742. * The final color node is represented by a different node when using shadows.
  25743. *
  25744. * @type {Node?}
  25745. * @default null
  25746. */
  25747. this.baseColorNode = null;
  25748. /**
  25749. * Represents the light's shadow.
  25750. *
  25751. * @type {ShadowNode?}
  25752. * @default null
  25753. */
  25754. this.shadowNode = null;
  25755. /**
  25756. * Represents the light's shadow color.
  25757. *
  25758. * @type {Node?}
  25759. * @default null
  25760. */
  25761. this.shadowColorNode = null;
  25762. /**
  25763. * This flag can be used for type testing.
  25764. *
  25765. * @type {Boolean}
  25766. * @readonly
  25767. * @default true
  25768. */
  25769. this.isAnalyticLightNode = true;
  25770. /**
  25771. * Overwritten since analytic light nodes are updated
  25772. * once per frame.
  25773. *
  25774. * @type {String}
  25775. * @default 'frame'
  25776. */
  25777. this.updateType = NodeUpdateType.FRAME;
  25778. }
  25779. /**
  25780. * Overwrites the default {@link Node#customCacheKey} implementation by including the
  25781. * `light.id` and `light.castShadow` into the cache key.
  25782. *
  25783. * @return {Number} The custom cache key.
  25784. */
  25785. customCacheKey() {
  25786. return hash$1( this.light.id, this.light.castShadow ? 1 : 0 );
  25787. }
  25788. getHash() {
  25789. return this.light.uuid;
  25790. }
  25791. /**
  25792. * Setups the shadow node for this light. The method exists so concrete light classes
  25793. * can setup different types of shadow nodes.
  25794. *
  25795. * @return {ShadowNode} The created shadow node.
  25796. */
  25797. setupShadowNode() {
  25798. return shadow( this.light );
  25799. }
  25800. /**
  25801. * Setups the shadow for this light. This method is only executed if the light
  25802. * cast shadows and the current build object receives shadows. It incorporates
  25803. * shadows into the lighting computation.
  25804. *
  25805. * @param {NodeBuilder} builder - The current node builder.
  25806. */
  25807. setupShadow( builder ) {
  25808. const { renderer } = builder;
  25809. if ( renderer.shadowMap.enabled === false ) return;
  25810. let shadowColorNode = this.shadowColorNode;
  25811. if ( shadowColorNode === null ) {
  25812. const customShadowNode = this.light.shadow.shadowNode;
  25813. let shadowNode;
  25814. if ( customShadowNode !== undefined ) {
  25815. shadowNode = nodeObject( customShadowNode );
  25816. } else {
  25817. shadowNode = this.setupShadowNode( builder );
  25818. }
  25819. this.shadowNode = shadowNode;
  25820. this.shadowColorNode = shadowColorNode = this.colorNode.mul( shadowNode );
  25821. this.baseColorNode = this.colorNode;
  25822. }
  25823. //
  25824. this.colorNode = shadowColorNode;
  25825. }
  25826. /**
  25827. * Unlike most other nodes, lighting nodes do not return a output node in {@link Node#setup}.
  25828. * The main purpose of lighting nodes is to configure the current {@link LightingModel} and/or
  25829. * invocate the respective interface methods.
  25830. *
  25831. * @param {NodeBuilder} builder - The current node builder.
  25832. */
  25833. setup( builder ) {
  25834. this.colorNode = this.baseColorNode || this.colorNode;
  25835. if ( this.light.castShadow ) {
  25836. if ( builder.object.receiveShadow ) {
  25837. this.setupShadow( builder );
  25838. }
  25839. } else if ( this.shadowNode !== null ) {
  25840. this.shadowNode.dispose();
  25841. this.shadowNode = null;
  25842. this.shadowColorNode = null;
  25843. }
  25844. }
  25845. /**
  25846. * The update method is used to update light uniforms per frame.
  25847. * Potentially overwritten in concrete light nodes to update light
  25848. * specific uniforms.
  25849. *
  25850. * @param {NodeFrame} frame - A reference to the current node frame.
  25851. */
  25852. update( /*frame*/ ) {
  25853. const { light } = this;
  25854. this.color.copy( light.color ).multiplyScalar( light.intensity );
  25855. }
  25856. }
  25857. /** @module LightUtils **/
  25858. /**
  25859. * Represents a `discard` shader operation in TSL.
  25860. *
  25861. * @method
  25862. * @param {Object} inputs - The input parameter object.
  25863. * @param {Node<float>} inputs.lightDistance - The distance of the light's position to the current fragment position.
  25864. * @param {Node<float>} inputs.cutoffDistance - The light's cutoff distance.
  25865. * @param {Node<float>} inputs.decayExponent - The light's decay exponent.
  25866. * @return {Node<float>} The distance falloff.
  25867. */
  25868. const getDistanceAttenuation = /*@__PURE__*/ Fn( ( inputs ) => {
  25869. const { lightDistance, cutoffDistance, decayExponent } = inputs;
  25870. // based upon Frostbite 3 Moving to Physically-based Rendering
  25871. // page 32, equation 26: E[window1]
  25872. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  25873. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  25874. return cutoffDistance.greaterThan( 0 ).select(
  25875. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  25876. distanceFalloff
  25877. );
  25878. } ); // validated
  25879. /** @module PointShadowNode **/
  25880. const _clearColor$2 = /*@__PURE__*/ new Color();
  25881. // cubeToUV() maps a 3D direction vector suitable for cube texture mapping to a 2D
  25882. // vector suitable for 2D texture mapping. This code uses the following layout for the
  25883. // 2D texture:
  25884. //
  25885. // xzXZ
  25886. // y Y
  25887. //
  25888. // Y - Positive y direction
  25889. // y - Negative y direction
  25890. // X - Positive x direction
  25891. // x - Negative x direction
  25892. // Z - Positive z direction
  25893. // z - Negative z direction
  25894. //
  25895. // Source and test bed:
  25896. // https://gist.github.com/tschw/da10c43c467ce8afd0c4
  25897. const cubeToUV = /*@__PURE__*/ Fn( ( [ pos, texelSizeY ] ) => {
  25898. const v = pos.toVar();
  25899. // Number of texels to avoid at the edge of each square
  25900. const absV = abs( v );
  25901. // Intersect unit cube
  25902. const scaleToCube = div( 1.0, max$1( absV.x, max$1( absV.y, absV.z ) ) );
  25903. absV.mulAssign( scaleToCube );
  25904. // Apply scale to avoid seams
  25905. // two texels less per square (one texel will do for NEAREST)
  25906. v.mulAssign( scaleToCube.mul( texelSizeY.mul( 2 ).oneMinus() ) );
  25907. // Unwrap
  25908. // space: -1 ... 1 range for each square
  25909. //
  25910. // #X## dim := ( 4 , 2 )
  25911. // # # center := ( 1 , 1 )
  25912. const planar = vec2( v.xy ).toVar();
  25913. const almostATexel = texelSizeY.mul( 1.5 );
  25914. const almostOne = almostATexel.oneMinus();
  25915. If( absV.z.greaterThanEqual( almostOne ), () => {
  25916. If( v.z.greaterThan( 0.0 ), () => {
  25917. planar.x.assign( sub( 4.0, v.x ) );
  25918. } );
  25919. } ).ElseIf( absV.x.greaterThanEqual( almostOne ), () => {
  25920. const signX = sign( v.x );
  25921. planar.x.assign( v.z.mul( signX ).add( signX.mul( 2.0 ) ) );
  25922. } ).ElseIf( absV.y.greaterThanEqual( almostOne ), () => {
  25923. const signY = sign( v.y );
  25924. planar.x.assign( v.x.add( signY.mul( 2.0 ) ).add( 2.0 ) );
  25925. planar.y.assign( v.z.mul( signY ).sub( 2.0 ) );
  25926. } );
  25927. // Transform to UV space
  25928. // scale := 0.5 / dim
  25929. // translate := ( center + 0.5 ) / dim
  25930. return vec2( 0.125, 0.25 ).mul( planar ).add( vec2( 0.375, 0.75 ) ).flipY();
  25931. } ).setLayout( {
  25932. name: 'cubeToUV',
  25933. type: 'vec2',
  25934. inputs: [
  25935. { name: 'pos', type: 'vec3' },
  25936. { name: 'texelSizeY', type: 'float' }
  25937. ]
  25938. } );
  25939. const BasicPointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize } ) => {
  25940. return texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp );
  25941. } );
  25942. const PointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize, shadow } ) => {
  25943. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  25944. const offset = vec2( -1, 1.0 ).mul( radius ).mul( texelSize.y );
  25945. return texture( depthTexture, cubeToUV( bd3D.add( offset.xyy ), texelSize.y ) ).compare( dp )
  25946. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyy ), texelSize.y ) ).compare( dp ) )
  25947. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xyx ), texelSize.y ) ).compare( dp ) )
  25948. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyx ), texelSize.y ) ).compare( dp ) )
  25949. .add( texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp ) )
  25950. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxy ), texelSize.y ) ).compare( dp ) )
  25951. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxy ), texelSize.y ) ).compare( dp ) )
  25952. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxx ), texelSize.y ) ).compare( dp ) )
  25953. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxx ), texelSize.y ) ).compare( dp ) )
  25954. .mul( 1.0 / 9.0 );
  25955. } );
  25956. const pointShadowFilter = /*@__PURE__*/ Fn( ( { filterFn, depthTexture, shadowCoord, shadow } ) => {
  25957. // for point lights, the uniform @vShadowCoord is re-purposed to hold
  25958. // the vector from the light to the world-space position of the fragment.
  25959. const lightToPosition = shadowCoord.xyz.toVar();
  25960. const lightToPositionLength = lightToPosition.length();
  25961. const cameraNearLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.near );
  25962. const cameraFarLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.far );
  25963. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  25964. const mapSize = uniform( shadow.mapSize ).setGroup( renderGroup );
  25965. const result = float( 1.0 ).toVar();
  25966. If( lightToPositionLength.sub( cameraFarLocal ).lessThanEqual( 0.0 ).and( lightToPositionLength.sub( cameraNearLocal ).greaterThanEqual( 0.0 ) ), () => {
  25967. // dp = normalized distance from light to fragment position
  25968. const dp = lightToPositionLength.sub( cameraNearLocal ).div( cameraFarLocal.sub( cameraNearLocal ) ).toVar(); // need to clamp?
  25969. dp.addAssign( bias );
  25970. // bd3D = base direction 3D
  25971. const bd3D = lightToPosition.normalize();
  25972. const texelSize = vec2( 1.0 ).div( mapSize.mul( vec2( 4.0, 2.0 ) ) );
  25973. // percentage-closer filtering
  25974. result.assign( filterFn( { depthTexture, bd3D, dp, texelSize, shadow } ) );
  25975. } );
  25976. return result;
  25977. } );
  25978. const _viewport = /*@__PURE__*/ new Vector4();
  25979. const _viewportSize = /*@__PURE__*/ new Vector2();
  25980. const _shadowMapSize = /*@__PURE__*/ new Vector2();
  25981. /**
  25982. * Represents the shadow implementation for point light nodes.
  25983. *
  25984. * @augments module:ShadowNode~ShadowNode
  25985. */
  25986. class PointShadowNode extends ShadowNode {
  25987. static get type() {
  25988. return 'PointShadowNode';
  25989. }
  25990. /**
  25991. * Constructs a new point shadow node.
  25992. *
  25993. * @param {PointLight} light - The shadow casting point light.
  25994. * @param {PointLightShadow?} [shadow=null] - An optional point light shadow.
  25995. */
  25996. constructor( light, shadow = null ) {
  25997. super( light, shadow );
  25998. }
  25999. /**
  26000. * Overwrites the default implementation to return point light shadow specific
  26001. * filtering functions.
  26002. *
  26003. * @param {Number} type - The shadow type.
  26004. * @return {Function} The filtering function.
  26005. */
  26006. getShadowFilterFn( type ) {
  26007. return type === BasicShadowMap ? BasicPointShadowFilter : PointShadowFilter;
  26008. }
  26009. /**
  26010. * Overwrites the default implementation so the unaltered shadow position is used.
  26011. *
  26012. * @param {NodeBuilder} builder - A reference to the current node builder.
  26013. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  26014. * @return {Node<vec3>} The shadow coordinates.
  26015. */
  26016. setupShadowCoord( builder, shadowPosition ) {
  26017. return shadowPosition;
  26018. }
  26019. /**
  26020. * Overwrites the default implementation to only use point light specific
  26021. * shadow filter functions.
  26022. *
  26023. * @param {NodeBuilder} builder - A reference to the current node builder.
  26024. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  26025. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  26026. * @param {Texture} inputs.shadowTexture - A reference to the shadow map's texture.
  26027. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  26028. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  26029. * @param {LightShadow} inputs.shadow - The light shadow.
  26030. * @return {Node<float>} The result node of the shadow filtering.
  26031. */
  26032. setupShadowFilter( builder, { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } ) {
  26033. return pointShadowFilter( { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } );
  26034. }
  26035. /**
  26036. * Overwrites the default implementation with point light specific
  26037. * rendering code.
  26038. *
  26039. * @param {NodeFrame} frame - A reference to the current node frame.
  26040. */
  26041. renderShadow( frame ) {
  26042. const { shadow, shadowMap, light } = this;
  26043. const { renderer, scene } = frame;
  26044. const shadowFrameExtents = shadow.getFrameExtents();
  26045. _shadowMapSize.copy( shadow.mapSize );
  26046. _shadowMapSize.multiply( shadowFrameExtents );
  26047. shadowMap.setSize( _shadowMapSize.width, _shadowMapSize.height );
  26048. _viewportSize.copy( shadow.mapSize );
  26049. //
  26050. const previousAutoClear = renderer.autoClear;
  26051. const previousClearColor = renderer.getClearColor( _clearColor$2 );
  26052. const previousClearAlpha = renderer.getClearAlpha();
  26053. renderer.autoClear = false;
  26054. renderer.setClearColor( shadow.clearColor, shadow.clearAlpha );
  26055. renderer.clear();
  26056. const viewportCount = shadow.getViewportCount();
  26057. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  26058. const viewport = shadow.getViewport( vp );
  26059. const x = _viewportSize.x * viewport.x;
  26060. const y = _shadowMapSize.y - _viewportSize.y - ( _viewportSize.y * viewport.y );
  26061. _viewport.set(
  26062. x,
  26063. y,
  26064. _viewportSize.x * viewport.z,
  26065. _viewportSize.y * viewport.w
  26066. );
  26067. shadowMap.viewport.copy( _viewport );
  26068. shadow.updateMatrices( light, vp );
  26069. renderer.render( scene, shadow.camera );
  26070. }
  26071. //
  26072. renderer.autoClear = previousAutoClear;
  26073. renderer.setClearColor( previousClearColor, previousClearAlpha );
  26074. }
  26075. }
  26076. /**
  26077. * TSL function for creating an instance of `PointShadowNode`.
  26078. *
  26079. * @function
  26080. * @param {PointLight} light - The shadow casting point light.
  26081. * @param {PointLightShadow?} [shadow=null] - An optional point light shadow.
  26082. * @return {PointShadowNode} The created point shadow node.
  26083. */
  26084. const pointShadow = ( light, shadow ) => nodeObject( new PointShadowNode( light, shadow ) );
  26085. const directPointLight = Fn( ( { color, lightViewPosition, cutoffDistance, decayExponent }, builder ) => {
  26086. const lightingModel = builder.context.lightingModel;
  26087. const lVector = lightViewPosition.sub( positionView ); // @TODO: Add it into LightNode
  26088. const lightDirection = lVector.normalize();
  26089. const lightDistance = lVector.length();
  26090. const lightAttenuation = getDistanceAttenuation( {
  26091. lightDistance,
  26092. cutoffDistance,
  26093. decayExponent
  26094. } );
  26095. const lightColor = color.mul( lightAttenuation );
  26096. const reflectedLight = builder.context.reflectedLight;
  26097. lightingModel.direct( {
  26098. lightDirection,
  26099. lightColor,
  26100. reflectedLight
  26101. }, builder.stack, builder );
  26102. } );
  26103. /**
  26104. * Module for representing point lights as nodes.
  26105. *
  26106. * @augments AnalyticLightNode
  26107. */
  26108. class PointLightNode extends AnalyticLightNode {
  26109. static get type() {
  26110. return 'PointLightNode';
  26111. }
  26112. /**
  26113. * Constructs a new point light node.
  26114. *
  26115. * @param {PointLight?} [light=null] - The point light source.
  26116. */
  26117. constructor( light = null ) {
  26118. super( light );
  26119. /**
  26120. * Uniform node representing the cutoff distance.
  26121. *
  26122. * @type {UniformNode<float>}
  26123. */
  26124. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  26125. /**
  26126. * Uniform node representing the decay exponent.
  26127. *
  26128. * @type {UniformNode<float>}
  26129. */
  26130. this.decayExponentNode = uniform( 2 ).setGroup( renderGroup );
  26131. }
  26132. /**
  26133. * Overwritten to updated point light specific uniforms.
  26134. *
  26135. * @param {NodeFrame} frame - A reference to the current node frame.
  26136. */
  26137. update( frame ) {
  26138. const { light } = this;
  26139. super.update( frame );
  26140. this.cutoffDistanceNode.value = light.distance;
  26141. this.decayExponentNode.value = light.decay;
  26142. }
  26143. /**
  26144. * Overwritten to setup point light specific shadow.
  26145. *
  26146. * @return {PointShadowNode}
  26147. */
  26148. setupShadowNode() {
  26149. return pointShadow( this.light );
  26150. }
  26151. setup( builder ) {
  26152. super.setup( builder );
  26153. directPointLight( {
  26154. color: this.colorNode,
  26155. lightViewPosition: lightViewPosition( this.light ),
  26156. cutoffDistance: this.cutoffDistanceNode,
  26157. decayExponent: this.decayExponentNode
  26158. } ).append();
  26159. }
  26160. }
  26161. /** @module Procedural **/
  26162. /**
  26163. * Creates a 2x2 checkerboard pattern that can be used as procedural texture data.
  26164. *
  26165. * @method
  26166. * @param {Node<vec2>} coord - The uv coordinates.
  26167. * @return {Node<float>} The result data.
  26168. */
  26169. const checker = /*@__PURE__*/ Fn( ( [ coord = uv() ] ) => {
  26170. const uv = coord.mul( 2.0 );
  26171. const cx = uv.x.floor();
  26172. const cy = uv.y.floor();
  26173. const result = cx.add( cy ).mod( 2.0 );
  26174. return result.sign();
  26175. } );
  26176. /** @module Shapes **/
  26177. /**
  26178. * Generates a circle based on the uv coordinates.
  26179. *
  26180. * @method
  26181. * @param {Node<vec2>} coord - The uv to generate the circle.
  26182. * @return {Node<float>} The circle shape.
  26183. */
  26184. const shapeCircle = Fn( ( [ coord = uv() ], { renderer, material } ) => {
  26185. const alpha = float( 1 ).toVar();
  26186. const len2 = lengthSq( coord.mul( 2 ).sub( 1 ) );
  26187. if ( material.alphaToCoverage && renderer.samples > 1 ) {
  26188. const dlen = float( len2.fwidth() ).toVar();
  26189. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  26190. } else {
  26191. len2.greaterThan( 1.0 ).discard();
  26192. }
  26193. return alpha;
  26194. } );
  26195. // Three.js Transpiler
  26196. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  26197. const mx_select = /*@__PURE__*/ Fn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  26198. const f = float( f_immutable ).toVar();
  26199. const t = float( t_immutable ).toVar();
  26200. const b = bool( b_immutable ).toVar();
  26201. return select( b, t, f );
  26202. } ).setLayout( {
  26203. name: 'mx_select',
  26204. type: 'float',
  26205. inputs: [
  26206. { name: 'b', type: 'bool' },
  26207. { name: 't', type: 'float' },
  26208. { name: 'f', type: 'float' }
  26209. ]
  26210. } );
  26211. const mx_negate_if = /*@__PURE__*/ Fn( ( [ val_immutable, b_immutable ] ) => {
  26212. const b = bool( b_immutable ).toVar();
  26213. const val = float( val_immutable ).toVar();
  26214. return select( b, val.negate(), val );
  26215. } ).setLayout( {
  26216. name: 'mx_negate_if',
  26217. type: 'float',
  26218. inputs: [
  26219. { name: 'val', type: 'float' },
  26220. { name: 'b', type: 'bool' }
  26221. ]
  26222. } );
  26223. const mx_floor = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  26224. const x = float( x_immutable ).toVar();
  26225. return int( floor( x ) );
  26226. } ).setLayout( {
  26227. name: 'mx_floor',
  26228. type: 'int',
  26229. inputs: [
  26230. { name: 'x', type: 'float' }
  26231. ]
  26232. } );
  26233. const mx_floorfrac = /*@__PURE__*/ Fn( ( [ x_immutable, i ] ) => {
  26234. const x = float( x_immutable ).toVar();
  26235. i.assign( mx_floor( x ) );
  26236. return x.sub( float( i ) );
  26237. } );
  26238. const mx_bilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  26239. const t = float( t_immutable ).toVar();
  26240. const s = float( s_immutable ).toVar();
  26241. const v3 = float( v3_immutable ).toVar();
  26242. const v2 = float( v2_immutable ).toVar();
  26243. const v1 = float( v1_immutable ).toVar();
  26244. const v0 = float( v0_immutable ).toVar();
  26245. const s1 = float( sub( 1.0, s ) ).toVar();
  26246. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  26247. } ).setLayout( {
  26248. name: 'mx_bilerp_0',
  26249. type: 'float',
  26250. inputs: [
  26251. { name: 'v0', type: 'float' },
  26252. { name: 'v1', type: 'float' },
  26253. { name: 'v2', type: 'float' },
  26254. { name: 'v3', type: 'float' },
  26255. { name: 's', type: 'float' },
  26256. { name: 't', type: 'float' }
  26257. ]
  26258. } );
  26259. const mx_bilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  26260. const t = float( t_immutable ).toVar();
  26261. const s = float( s_immutable ).toVar();
  26262. const v3 = vec3( v3_immutable ).toVar();
  26263. const v2 = vec3( v2_immutable ).toVar();
  26264. const v1 = vec3( v1_immutable ).toVar();
  26265. const v0 = vec3( v0_immutable ).toVar();
  26266. const s1 = float( sub( 1.0, s ) ).toVar();
  26267. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  26268. } ).setLayout( {
  26269. name: 'mx_bilerp_1',
  26270. type: 'vec3',
  26271. inputs: [
  26272. { name: 'v0', type: 'vec3' },
  26273. { name: 'v1', type: 'vec3' },
  26274. { name: 'v2', type: 'vec3' },
  26275. { name: 'v3', type: 'vec3' },
  26276. { name: 's', type: 'float' },
  26277. { name: 't', type: 'float' }
  26278. ]
  26279. } );
  26280. const mx_bilerp = /*@__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  26281. 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 ] ) => {
  26282. const r = float( r_immutable ).toVar();
  26283. const t = float( t_immutable ).toVar();
  26284. const s = float( s_immutable ).toVar();
  26285. const v7 = float( v7_immutable ).toVar();
  26286. const v6 = float( v6_immutable ).toVar();
  26287. const v5 = float( v5_immutable ).toVar();
  26288. const v4 = float( v4_immutable ).toVar();
  26289. const v3 = float( v3_immutable ).toVar();
  26290. const v2 = float( v2_immutable ).toVar();
  26291. const v1 = float( v1_immutable ).toVar();
  26292. const v0 = float( v0_immutable ).toVar();
  26293. const s1 = float( sub( 1.0, s ) ).toVar();
  26294. const t1 = float( sub( 1.0, t ) ).toVar();
  26295. const r1 = float( sub( 1.0, r ) ).toVar();
  26296. 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 ) ) ) ) ) );
  26297. } ).setLayout( {
  26298. name: 'mx_trilerp_0',
  26299. type: 'float',
  26300. inputs: [
  26301. { name: 'v0', type: 'float' },
  26302. { name: 'v1', type: 'float' },
  26303. { name: 'v2', type: 'float' },
  26304. { name: 'v3', type: 'float' },
  26305. { name: 'v4', type: 'float' },
  26306. { name: 'v5', type: 'float' },
  26307. { name: 'v6', type: 'float' },
  26308. { name: 'v7', type: 'float' },
  26309. { name: 's', type: 'float' },
  26310. { name: 't', type: 'float' },
  26311. { name: 'r', type: 'float' }
  26312. ]
  26313. } );
  26314. 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 ] ) => {
  26315. const r = float( r_immutable ).toVar();
  26316. const t = float( t_immutable ).toVar();
  26317. const s = float( s_immutable ).toVar();
  26318. const v7 = vec3( v7_immutable ).toVar();
  26319. const v6 = vec3( v6_immutable ).toVar();
  26320. const v5 = vec3( v5_immutable ).toVar();
  26321. const v4 = vec3( v4_immutable ).toVar();
  26322. const v3 = vec3( v3_immutable ).toVar();
  26323. const v2 = vec3( v2_immutable ).toVar();
  26324. const v1 = vec3( v1_immutable ).toVar();
  26325. const v0 = vec3( v0_immutable ).toVar();
  26326. const s1 = float( sub( 1.0, s ) ).toVar();
  26327. const t1 = float( sub( 1.0, t ) ).toVar();
  26328. const r1 = float( sub( 1.0, r ) ).toVar();
  26329. 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 ) ) ) ) ) );
  26330. } ).setLayout( {
  26331. name: 'mx_trilerp_1',
  26332. type: 'vec3',
  26333. inputs: [
  26334. { name: 'v0', type: 'vec3' },
  26335. { name: 'v1', type: 'vec3' },
  26336. { name: 'v2', type: 'vec3' },
  26337. { name: 'v3', type: 'vec3' },
  26338. { name: 'v4', type: 'vec3' },
  26339. { name: 'v5', type: 'vec3' },
  26340. { name: 'v6', type: 'vec3' },
  26341. { name: 'v7', type: 'vec3' },
  26342. { name: 's', type: 'float' },
  26343. { name: 't', type: 'float' },
  26344. { name: 'r', type: 'float' }
  26345. ]
  26346. } );
  26347. const mx_trilerp = /*@__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  26348. const mx_gradient_float_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  26349. const y = float( y_immutable ).toVar();
  26350. const x = float( x_immutable ).toVar();
  26351. const hash = uint( hash_immutable ).toVar();
  26352. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  26353. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  26354. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  26355. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  26356. } ).setLayout( {
  26357. name: 'mx_gradient_float_0',
  26358. type: 'float',
  26359. inputs: [
  26360. { name: 'hash', type: 'uint' },
  26361. { name: 'x', type: 'float' },
  26362. { name: 'y', type: 'float' }
  26363. ]
  26364. } );
  26365. const mx_gradient_float_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  26366. const z = float( z_immutable ).toVar();
  26367. const y = float( y_immutable ).toVar();
  26368. const x = float( x_immutable ).toVar();
  26369. const hash = uint( hash_immutable ).toVar();
  26370. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  26371. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  26372. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  26373. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  26374. } ).setLayout( {
  26375. name: 'mx_gradient_float_1',
  26376. type: 'float',
  26377. inputs: [
  26378. { name: 'hash', type: 'uint' },
  26379. { name: 'x', type: 'float' },
  26380. { name: 'y', type: 'float' },
  26381. { name: 'z', type: 'float' }
  26382. ]
  26383. } );
  26384. const mx_gradient_float = /*@__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  26385. const mx_gradient_vec3_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  26386. const y = float( y_immutable ).toVar();
  26387. const x = float( x_immutable ).toVar();
  26388. const hash = uvec3( hash_immutable ).toVar();
  26389. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  26390. } ).setLayout( {
  26391. name: 'mx_gradient_vec3_0',
  26392. type: 'vec3',
  26393. inputs: [
  26394. { name: 'hash', type: 'uvec3' },
  26395. { name: 'x', type: 'float' },
  26396. { name: 'y', type: 'float' }
  26397. ]
  26398. } );
  26399. const mx_gradient_vec3_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  26400. const z = float( z_immutable ).toVar();
  26401. const y = float( y_immutable ).toVar();
  26402. const x = float( x_immutable ).toVar();
  26403. const hash = uvec3( hash_immutable ).toVar();
  26404. 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 ) );
  26405. } ).setLayout( {
  26406. name: 'mx_gradient_vec3_1',
  26407. type: 'vec3',
  26408. inputs: [
  26409. { name: 'hash', type: 'uvec3' },
  26410. { name: 'x', type: 'float' },
  26411. { name: 'y', type: 'float' },
  26412. { name: 'z', type: 'float' }
  26413. ]
  26414. } );
  26415. const mx_gradient_vec3 = /*@__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  26416. const mx_gradient_scale2d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  26417. const v = float( v_immutable ).toVar();
  26418. return mul( 0.6616, v );
  26419. } ).setLayout( {
  26420. name: 'mx_gradient_scale2d_0',
  26421. type: 'float',
  26422. inputs: [
  26423. { name: 'v', type: 'float' }
  26424. ]
  26425. } );
  26426. const mx_gradient_scale3d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  26427. const v = float( v_immutable ).toVar();
  26428. return mul( 0.9820, v );
  26429. } ).setLayout( {
  26430. name: 'mx_gradient_scale3d_0',
  26431. type: 'float',
  26432. inputs: [
  26433. { name: 'v', type: 'float' }
  26434. ]
  26435. } );
  26436. const mx_gradient_scale2d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  26437. const v = vec3( v_immutable ).toVar();
  26438. return mul( 0.6616, v );
  26439. } ).setLayout( {
  26440. name: 'mx_gradient_scale2d_1',
  26441. type: 'vec3',
  26442. inputs: [
  26443. { name: 'v', type: 'vec3' }
  26444. ]
  26445. } );
  26446. const mx_gradient_scale2d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  26447. const mx_gradient_scale3d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  26448. const v = vec3( v_immutable ).toVar();
  26449. return mul( 0.9820, v );
  26450. } ).setLayout( {
  26451. name: 'mx_gradient_scale3d_1',
  26452. type: 'vec3',
  26453. inputs: [
  26454. { name: 'v', type: 'vec3' }
  26455. ]
  26456. } );
  26457. const mx_gradient_scale3d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  26458. const mx_rotl32 = /*@__PURE__*/ Fn( ( [ x_immutable, k_immutable ] ) => {
  26459. const k = int( k_immutable ).toVar();
  26460. const x = uint( x_immutable ).toVar();
  26461. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  26462. } ).setLayout( {
  26463. name: 'mx_rotl32',
  26464. type: 'uint',
  26465. inputs: [
  26466. { name: 'x', type: 'uint' },
  26467. { name: 'k', type: 'int' }
  26468. ]
  26469. } );
  26470. const mx_bjmix = /*@__PURE__*/ Fn( ( [ a, b, c ] ) => {
  26471. a.subAssign( c );
  26472. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  26473. c.addAssign( b );
  26474. b.subAssign( a );
  26475. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  26476. a.addAssign( c );
  26477. c.subAssign( b );
  26478. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  26479. b.addAssign( a );
  26480. a.subAssign( c );
  26481. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  26482. c.addAssign( b );
  26483. b.subAssign( a );
  26484. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  26485. a.addAssign( c );
  26486. c.subAssign( b );
  26487. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  26488. b.addAssign( a );
  26489. } );
  26490. const mx_bjfinal = /*@__PURE__*/ Fn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  26491. const c = uint( c_immutable ).toVar();
  26492. const b = uint( b_immutable ).toVar();
  26493. const a = uint( a_immutable ).toVar();
  26494. c.bitXorAssign( b );
  26495. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  26496. a.bitXorAssign( c );
  26497. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  26498. b.bitXorAssign( a );
  26499. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  26500. c.bitXorAssign( b );
  26501. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  26502. a.bitXorAssign( c );
  26503. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  26504. b.bitXorAssign( a );
  26505. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  26506. c.bitXorAssign( b );
  26507. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  26508. return c;
  26509. } ).setLayout( {
  26510. name: 'mx_bjfinal',
  26511. type: 'uint',
  26512. inputs: [
  26513. { name: 'a', type: 'uint' },
  26514. { name: 'b', type: 'uint' },
  26515. { name: 'c', type: 'uint' }
  26516. ]
  26517. } );
  26518. const mx_bits_to_01 = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  26519. const bits = uint( bits_immutable ).toVar();
  26520. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  26521. } ).setLayout( {
  26522. name: 'mx_bits_to_01',
  26523. type: 'float',
  26524. inputs: [
  26525. { name: 'bits', type: 'uint' }
  26526. ]
  26527. } );
  26528. const mx_fade = /*@__PURE__*/ Fn( ( [ t_immutable ] ) => {
  26529. const t = float( t_immutable ).toVar();
  26530. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  26531. } ).setLayout( {
  26532. name: 'mx_fade',
  26533. type: 'float',
  26534. inputs: [
  26535. { name: 't', type: 'float' }
  26536. ]
  26537. } );
  26538. const mx_hash_int_0 = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  26539. const x = int( x_immutable ).toVar();
  26540. const len = uint( uint( 1 ) ).toVar();
  26541. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  26542. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  26543. } ).setLayout( {
  26544. name: 'mx_hash_int_0',
  26545. type: 'uint',
  26546. inputs: [
  26547. { name: 'x', type: 'int' }
  26548. ]
  26549. } );
  26550. const mx_hash_int_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  26551. const y = int( y_immutable ).toVar();
  26552. const x = int( x_immutable ).toVar();
  26553. const len = uint( uint( 2 ) ).toVar();
  26554. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  26555. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  26556. a.addAssign( uint( x ) );
  26557. b.addAssign( uint( y ) );
  26558. return mx_bjfinal( a, b, c );
  26559. } ).setLayout( {
  26560. name: 'mx_hash_int_1',
  26561. type: 'uint',
  26562. inputs: [
  26563. { name: 'x', type: 'int' },
  26564. { name: 'y', type: 'int' }
  26565. ]
  26566. } );
  26567. const mx_hash_int_2 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  26568. const z = int( z_immutable ).toVar();
  26569. const y = int( y_immutable ).toVar();
  26570. const x = int( x_immutable ).toVar();
  26571. const len = uint( uint( 3 ) ).toVar();
  26572. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  26573. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  26574. a.addAssign( uint( x ) );
  26575. b.addAssign( uint( y ) );
  26576. c.addAssign( uint( z ) );
  26577. return mx_bjfinal( a, b, c );
  26578. } ).setLayout( {
  26579. name: 'mx_hash_int_2',
  26580. type: 'uint',
  26581. inputs: [
  26582. { name: 'x', type: 'int' },
  26583. { name: 'y', type: 'int' },
  26584. { name: 'z', type: 'int' }
  26585. ]
  26586. } );
  26587. const mx_hash_int_3 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  26588. const xx = int( xx_immutable ).toVar();
  26589. const z = int( z_immutable ).toVar();
  26590. const y = int( y_immutable ).toVar();
  26591. const x = int( x_immutable ).toVar();
  26592. const len = uint( uint( 4 ) ).toVar();
  26593. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  26594. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  26595. a.addAssign( uint( x ) );
  26596. b.addAssign( uint( y ) );
  26597. c.addAssign( uint( z ) );
  26598. mx_bjmix( a, b, c );
  26599. a.addAssign( uint( xx ) );
  26600. return mx_bjfinal( a, b, c );
  26601. } ).setLayout( {
  26602. name: 'mx_hash_int_3',
  26603. type: 'uint',
  26604. inputs: [
  26605. { name: 'x', type: 'int' },
  26606. { name: 'y', type: 'int' },
  26607. { name: 'z', type: 'int' },
  26608. { name: 'xx', type: 'int' }
  26609. ]
  26610. } );
  26611. const mx_hash_int_4 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  26612. const yy = int( yy_immutable ).toVar();
  26613. const xx = int( xx_immutable ).toVar();
  26614. const z = int( z_immutable ).toVar();
  26615. const y = int( y_immutable ).toVar();
  26616. const x = int( x_immutable ).toVar();
  26617. const len = uint( uint( 5 ) ).toVar();
  26618. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  26619. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  26620. a.addAssign( uint( x ) );
  26621. b.addAssign( uint( y ) );
  26622. c.addAssign( uint( z ) );
  26623. mx_bjmix( a, b, c );
  26624. a.addAssign( uint( xx ) );
  26625. b.addAssign( uint( yy ) );
  26626. return mx_bjfinal( a, b, c );
  26627. } ).setLayout( {
  26628. name: 'mx_hash_int_4',
  26629. type: 'uint',
  26630. inputs: [
  26631. { name: 'x', type: 'int' },
  26632. { name: 'y', type: 'int' },
  26633. { name: 'z', type: 'int' },
  26634. { name: 'xx', type: 'int' },
  26635. { name: 'yy', type: 'int' }
  26636. ]
  26637. } );
  26638. 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 ] );
  26639. const mx_hash_vec3_0 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  26640. const y = int( y_immutable ).toVar();
  26641. const x = int( x_immutable ).toVar();
  26642. const h = uint( mx_hash_int( x, y ) ).toVar();
  26643. const result = uvec3().toVar();
  26644. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  26645. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  26646. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  26647. return result;
  26648. } ).setLayout( {
  26649. name: 'mx_hash_vec3_0',
  26650. type: 'uvec3',
  26651. inputs: [
  26652. { name: 'x', type: 'int' },
  26653. { name: 'y', type: 'int' }
  26654. ]
  26655. } );
  26656. const mx_hash_vec3_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  26657. const z = int( z_immutable ).toVar();
  26658. const y = int( y_immutable ).toVar();
  26659. const x = int( x_immutable ).toVar();
  26660. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  26661. const result = uvec3().toVar();
  26662. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  26663. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  26664. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  26665. return result;
  26666. } ).setLayout( {
  26667. name: 'mx_hash_vec3_1',
  26668. type: 'uvec3',
  26669. inputs: [
  26670. { name: 'x', type: 'int' },
  26671. { name: 'y', type: 'int' },
  26672. { name: 'z', type: 'int' }
  26673. ]
  26674. } );
  26675. const mx_hash_vec3 = /*@__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  26676. const mx_perlin_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26677. const p = vec2( p_immutable ).toVar();
  26678. const X = int().toVar(), Y = int().toVar();
  26679. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  26680. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  26681. const u = float( mx_fade( fx ) ).toVar();
  26682. const v = float( mx_fade( fy ) ).toVar();
  26683. 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();
  26684. return mx_gradient_scale2d( result );
  26685. } ).setLayout( {
  26686. name: 'mx_perlin_noise_float_0',
  26687. type: 'float',
  26688. inputs: [
  26689. { name: 'p', type: 'vec2' }
  26690. ]
  26691. } );
  26692. const mx_perlin_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26693. const p = vec3( p_immutable ).toVar();
  26694. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  26695. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  26696. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  26697. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  26698. const u = float( mx_fade( fx ) ).toVar();
  26699. const v = float( mx_fade( fy ) ).toVar();
  26700. const w = float( mx_fade( fz ) ).toVar();
  26701. 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();
  26702. return mx_gradient_scale3d( result );
  26703. } ).setLayout( {
  26704. name: 'mx_perlin_noise_float_1',
  26705. type: 'float',
  26706. inputs: [
  26707. { name: 'p', type: 'vec3' }
  26708. ]
  26709. } );
  26710. const mx_perlin_noise_float = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  26711. const mx_perlin_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26712. const p = vec2( p_immutable ).toVar();
  26713. const X = int().toVar(), Y = int().toVar();
  26714. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  26715. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  26716. const u = float( mx_fade( fx ) ).toVar();
  26717. const v = float( mx_fade( fy ) ).toVar();
  26718. 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();
  26719. return mx_gradient_scale2d( result );
  26720. } ).setLayout( {
  26721. name: 'mx_perlin_noise_vec3_0',
  26722. type: 'vec3',
  26723. inputs: [
  26724. { name: 'p', type: 'vec2' }
  26725. ]
  26726. } );
  26727. const mx_perlin_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26728. const p = vec3( p_immutable ).toVar();
  26729. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  26730. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  26731. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  26732. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  26733. const u = float( mx_fade( fx ) ).toVar();
  26734. const v = float( mx_fade( fy ) ).toVar();
  26735. const w = float( mx_fade( fz ) ).toVar();
  26736. 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();
  26737. return mx_gradient_scale3d( result );
  26738. } ).setLayout( {
  26739. name: 'mx_perlin_noise_vec3_1',
  26740. type: 'vec3',
  26741. inputs: [
  26742. { name: 'p', type: 'vec3' }
  26743. ]
  26744. } );
  26745. const mx_perlin_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  26746. const mx_cell_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26747. const p = float( p_immutable ).toVar();
  26748. const ix = int( mx_floor( p ) ).toVar();
  26749. return mx_bits_to_01( mx_hash_int( ix ) );
  26750. } ).setLayout( {
  26751. name: 'mx_cell_noise_float_0',
  26752. type: 'float',
  26753. inputs: [
  26754. { name: 'p', type: 'float' }
  26755. ]
  26756. } );
  26757. const mx_cell_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26758. const p = vec2( p_immutable ).toVar();
  26759. const ix = int( mx_floor( p.x ) ).toVar();
  26760. const iy = int( mx_floor( p.y ) ).toVar();
  26761. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  26762. } ).setLayout( {
  26763. name: 'mx_cell_noise_float_1',
  26764. type: 'float',
  26765. inputs: [
  26766. { name: 'p', type: 'vec2' }
  26767. ]
  26768. } );
  26769. const mx_cell_noise_float_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26770. const p = vec3( p_immutable ).toVar();
  26771. const ix = int( mx_floor( p.x ) ).toVar();
  26772. const iy = int( mx_floor( p.y ) ).toVar();
  26773. const iz = int( mx_floor( p.z ) ).toVar();
  26774. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  26775. } ).setLayout( {
  26776. name: 'mx_cell_noise_float_2',
  26777. type: 'float',
  26778. inputs: [
  26779. { name: 'p', type: 'vec3' }
  26780. ]
  26781. } );
  26782. const mx_cell_noise_float_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26783. const p = vec4( p_immutable ).toVar();
  26784. const ix = int( mx_floor( p.x ) ).toVar();
  26785. const iy = int( mx_floor( p.y ) ).toVar();
  26786. const iz = int( mx_floor( p.z ) ).toVar();
  26787. const iw = int( mx_floor( p.w ) ).toVar();
  26788. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  26789. } ).setLayout( {
  26790. name: 'mx_cell_noise_float_3',
  26791. type: 'float',
  26792. inputs: [
  26793. { name: 'p', type: 'vec4' }
  26794. ]
  26795. } );
  26796. 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 ] );
  26797. const mx_cell_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26798. const p = float( p_immutable ).toVar();
  26799. const ix = int( mx_floor( p ) ).toVar();
  26800. 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 ) ) ) );
  26801. } ).setLayout( {
  26802. name: 'mx_cell_noise_vec3_0',
  26803. type: 'vec3',
  26804. inputs: [
  26805. { name: 'p', type: 'float' }
  26806. ]
  26807. } );
  26808. const mx_cell_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26809. const p = vec2( p_immutable ).toVar();
  26810. const ix = int( mx_floor( p.x ) ).toVar();
  26811. const iy = int( mx_floor( p.y ) ).toVar();
  26812. 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 ) ) ) );
  26813. } ).setLayout( {
  26814. name: 'mx_cell_noise_vec3_1',
  26815. type: 'vec3',
  26816. inputs: [
  26817. { name: 'p', type: 'vec2' }
  26818. ]
  26819. } );
  26820. const mx_cell_noise_vec3_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26821. const p = vec3( p_immutable ).toVar();
  26822. const ix = int( mx_floor( p.x ) ).toVar();
  26823. const iy = int( mx_floor( p.y ) ).toVar();
  26824. const iz = int( mx_floor( p.z ) ).toVar();
  26825. 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 ) ) ) );
  26826. } ).setLayout( {
  26827. name: 'mx_cell_noise_vec3_2',
  26828. type: 'vec3',
  26829. inputs: [
  26830. { name: 'p', type: 'vec3' }
  26831. ]
  26832. } );
  26833. const mx_cell_noise_vec3_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26834. const p = vec4( p_immutable ).toVar();
  26835. const ix = int( mx_floor( p.x ) ).toVar();
  26836. const iy = int( mx_floor( p.y ) ).toVar();
  26837. const iz = int( mx_floor( p.z ) ).toVar();
  26838. const iw = int( mx_floor( p.w ) ).toVar();
  26839. 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 ) ) ) );
  26840. } ).setLayout( {
  26841. name: 'mx_cell_noise_vec3_3',
  26842. type: 'vec3',
  26843. inputs: [
  26844. { name: 'p', type: 'vec4' }
  26845. ]
  26846. } );
  26847. 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 ] );
  26848. const mx_fractal_noise_float$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  26849. const diminish = float( diminish_immutable ).toVar();
  26850. const lacunarity = float( lacunarity_immutable ).toVar();
  26851. const octaves = int( octaves_immutable ).toVar();
  26852. const p = vec3( p_immutable ).toVar();
  26853. const result = float( 0.0 ).toVar();
  26854. const amplitude = float( 1.0 ).toVar();
  26855. Loop( octaves, () => {
  26856. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  26857. amplitude.mulAssign( diminish );
  26858. p.mulAssign( lacunarity );
  26859. } );
  26860. return result;
  26861. } ).setLayout( {
  26862. name: 'mx_fractal_noise_float',
  26863. type: 'float',
  26864. inputs: [
  26865. { name: 'p', type: 'vec3' },
  26866. { name: 'octaves', type: 'int' },
  26867. { name: 'lacunarity', type: 'float' },
  26868. { name: 'diminish', type: 'float' }
  26869. ]
  26870. } );
  26871. const mx_fractal_noise_vec3$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  26872. const diminish = float( diminish_immutable ).toVar();
  26873. const lacunarity = float( lacunarity_immutable ).toVar();
  26874. const octaves = int( octaves_immutable ).toVar();
  26875. const p = vec3( p_immutable ).toVar();
  26876. const result = vec3( 0.0 ).toVar();
  26877. const amplitude = float( 1.0 ).toVar();
  26878. Loop( octaves, () => {
  26879. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  26880. amplitude.mulAssign( diminish );
  26881. p.mulAssign( lacunarity );
  26882. } );
  26883. return result;
  26884. } ).setLayout( {
  26885. name: 'mx_fractal_noise_vec3',
  26886. type: 'vec3',
  26887. inputs: [
  26888. { name: 'p', type: 'vec3' },
  26889. { name: 'octaves', type: 'int' },
  26890. { name: 'lacunarity', type: 'float' },
  26891. { name: 'diminish', type: 'float' }
  26892. ]
  26893. } );
  26894. const mx_fractal_noise_vec2$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  26895. const diminish = float( diminish_immutable ).toVar();
  26896. const lacunarity = float( lacunarity_immutable ).toVar();
  26897. const octaves = int( octaves_immutable ).toVar();
  26898. const p = vec3( p_immutable ).toVar();
  26899. 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 ) );
  26900. } ).setLayout( {
  26901. name: 'mx_fractal_noise_vec2',
  26902. type: 'vec2',
  26903. inputs: [
  26904. { name: 'p', type: 'vec3' },
  26905. { name: 'octaves', type: 'int' },
  26906. { name: 'lacunarity', type: 'float' },
  26907. { name: 'diminish', type: 'float' }
  26908. ]
  26909. } );
  26910. const mx_fractal_noise_vec4$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  26911. const diminish = float( diminish_immutable ).toVar();
  26912. const lacunarity = float( lacunarity_immutable ).toVar();
  26913. const octaves = int( octaves_immutable ).toVar();
  26914. const p = vec3( p_immutable ).toVar();
  26915. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  26916. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  26917. return vec4( c, f );
  26918. } ).setLayout( {
  26919. name: 'mx_fractal_noise_vec4',
  26920. type: 'vec4',
  26921. inputs: [
  26922. { name: 'p', type: 'vec3' },
  26923. { name: 'octaves', type: 'int' },
  26924. { name: 'lacunarity', type: 'float' },
  26925. { name: 'diminish', type: 'float' }
  26926. ]
  26927. } );
  26928. const mx_worley_distance_0 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  26929. const metric = int( metric_immutable ).toVar();
  26930. const jitter = float( jitter_immutable ).toVar();
  26931. const yoff = int( yoff_immutable ).toVar();
  26932. const xoff = int( xoff_immutable ).toVar();
  26933. const y = int( y_immutable ).toVar();
  26934. const x = int( x_immutable ).toVar();
  26935. const p = vec2( p_immutable ).toVar();
  26936. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  26937. const off = vec2( tmp.x, tmp.y ).toVar();
  26938. off.subAssign( 0.5 );
  26939. off.mulAssign( jitter );
  26940. off.addAssign( 0.5 );
  26941. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  26942. const diff = vec2( cellpos.sub( p ) ).toVar();
  26943. If( metric.equal( int( 2 ) ), () => {
  26944. return abs( diff.x ).add( abs( diff.y ) );
  26945. } );
  26946. If( metric.equal( int( 3 ) ), () => {
  26947. return max$1( abs( diff.x ), abs( diff.y ) );
  26948. } );
  26949. return dot( diff, diff );
  26950. } ).setLayout( {
  26951. name: 'mx_worley_distance_0',
  26952. type: 'float',
  26953. inputs: [
  26954. { name: 'p', type: 'vec2' },
  26955. { name: 'x', type: 'int' },
  26956. { name: 'y', type: 'int' },
  26957. { name: 'xoff', type: 'int' },
  26958. { name: 'yoff', type: 'int' },
  26959. { name: 'jitter', type: 'float' },
  26960. { name: 'metric', type: 'int' }
  26961. ]
  26962. } );
  26963. 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 ] ) => {
  26964. const metric = int( metric_immutable ).toVar();
  26965. const jitter = float( jitter_immutable ).toVar();
  26966. const zoff = int( zoff_immutable ).toVar();
  26967. const yoff = int( yoff_immutable ).toVar();
  26968. const xoff = int( xoff_immutable ).toVar();
  26969. const z = int( z_immutable ).toVar();
  26970. const y = int( y_immutable ).toVar();
  26971. const x = int( x_immutable ).toVar();
  26972. const p = vec3( p_immutable ).toVar();
  26973. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  26974. off.subAssign( 0.5 );
  26975. off.mulAssign( jitter );
  26976. off.addAssign( 0.5 );
  26977. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  26978. const diff = vec3( cellpos.sub( p ) ).toVar();
  26979. If( metric.equal( int( 2 ) ), () => {
  26980. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  26981. } );
  26982. If( metric.equal( int( 3 ) ), () => {
  26983. return max$1( max$1( abs( diff.x ), abs( diff.y ) ), abs( diff.z ) );
  26984. } );
  26985. return dot( diff, diff );
  26986. } ).setLayout( {
  26987. name: 'mx_worley_distance_1',
  26988. type: 'float',
  26989. inputs: [
  26990. { name: 'p', type: 'vec3' },
  26991. { name: 'x', type: 'int' },
  26992. { name: 'y', type: 'int' },
  26993. { name: 'z', type: 'int' },
  26994. { name: 'xoff', type: 'int' },
  26995. { name: 'yoff', type: 'int' },
  26996. { name: 'zoff', type: 'int' },
  26997. { name: 'jitter', type: 'float' },
  26998. { name: 'metric', type: 'int' }
  26999. ]
  27000. } );
  27001. const mx_worley_distance = /*@__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  27002. const mx_worley_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  27003. const metric = int( metric_immutable ).toVar();
  27004. const jitter = float( jitter_immutable ).toVar();
  27005. const p = vec2( p_immutable ).toVar();
  27006. const X = int().toVar(), Y = int().toVar();
  27007. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  27008. const sqdist = float( 1e6 ).toVar();
  27009. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  27010. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  27011. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  27012. sqdist.assign( min$1( sqdist, dist ) );
  27013. } );
  27014. } );
  27015. If( metric.equal( int( 0 ) ), () => {
  27016. sqdist.assign( sqrt( sqdist ) );
  27017. } );
  27018. return sqdist;
  27019. } ).setLayout( {
  27020. name: 'mx_worley_noise_float_0',
  27021. type: 'float',
  27022. inputs: [
  27023. { name: 'p', type: 'vec2' },
  27024. { name: 'jitter', type: 'float' },
  27025. { name: 'metric', type: 'int' }
  27026. ]
  27027. } );
  27028. const mx_worley_noise_vec2_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  27029. const metric = int( metric_immutable ).toVar();
  27030. const jitter = float( jitter_immutable ).toVar();
  27031. const p = vec2( p_immutable ).toVar();
  27032. const X = int().toVar(), Y = int().toVar();
  27033. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  27034. const sqdist = vec2( 1e6, 1e6 ).toVar();
  27035. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  27036. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  27037. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  27038. If( dist.lessThan( sqdist.x ), () => {
  27039. sqdist.y.assign( sqdist.x );
  27040. sqdist.x.assign( dist );
  27041. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  27042. sqdist.y.assign( dist );
  27043. } );
  27044. } );
  27045. } );
  27046. If( metric.equal( int( 0 ) ), () => {
  27047. sqdist.assign( sqrt( sqdist ) );
  27048. } );
  27049. return sqdist;
  27050. } ).setLayout( {
  27051. name: 'mx_worley_noise_vec2_0',
  27052. type: 'vec2',
  27053. inputs: [
  27054. { name: 'p', type: 'vec2' },
  27055. { name: 'jitter', type: 'float' },
  27056. { name: 'metric', type: 'int' }
  27057. ]
  27058. } );
  27059. const mx_worley_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  27060. const metric = int( metric_immutable ).toVar();
  27061. const jitter = float( jitter_immutable ).toVar();
  27062. const p = vec2( p_immutable ).toVar();
  27063. const X = int().toVar(), Y = int().toVar();
  27064. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  27065. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  27066. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  27067. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  27068. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  27069. If( dist.lessThan( sqdist.x ), () => {
  27070. sqdist.z.assign( sqdist.y );
  27071. sqdist.y.assign( sqdist.x );
  27072. sqdist.x.assign( dist );
  27073. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  27074. sqdist.z.assign( sqdist.y );
  27075. sqdist.y.assign( dist );
  27076. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  27077. sqdist.z.assign( dist );
  27078. } );
  27079. } );
  27080. } );
  27081. If( metric.equal( int( 0 ) ), () => {
  27082. sqdist.assign( sqrt( sqdist ) );
  27083. } );
  27084. return sqdist;
  27085. } ).setLayout( {
  27086. name: 'mx_worley_noise_vec3_0',
  27087. type: 'vec3',
  27088. inputs: [
  27089. { name: 'p', type: 'vec2' },
  27090. { name: 'jitter', type: 'float' },
  27091. { name: 'metric', type: 'int' }
  27092. ]
  27093. } );
  27094. const mx_worley_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  27095. const metric = int( metric_immutable ).toVar();
  27096. const jitter = float( jitter_immutable ).toVar();
  27097. const p = vec3( p_immutable ).toVar();
  27098. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  27099. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  27100. const sqdist = float( 1e6 ).toVar();
  27101. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  27102. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  27103. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  27104. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  27105. sqdist.assign( min$1( sqdist, dist ) );
  27106. } );
  27107. } );
  27108. } );
  27109. If( metric.equal( int( 0 ) ), () => {
  27110. sqdist.assign( sqrt( sqdist ) );
  27111. } );
  27112. return sqdist;
  27113. } ).setLayout( {
  27114. name: 'mx_worley_noise_float_1',
  27115. type: 'float',
  27116. inputs: [
  27117. { name: 'p', type: 'vec3' },
  27118. { name: 'jitter', type: 'float' },
  27119. { name: 'metric', type: 'int' }
  27120. ]
  27121. } );
  27122. const mx_worley_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  27123. const mx_worley_noise_vec2_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  27124. const metric = int( metric_immutable ).toVar();
  27125. const jitter = float( jitter_immutable ).toVar();
  27126. const p = vec3( p_immutable ).toVar();
  27127. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  27128. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  27129. const sqdist = vec2( 1e6, 1e6 ).toVar();
  27130. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  27131. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  27132. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  27133. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  27134. If( dist.lessThan( sqdist.x ), () => {
  27135. sqdist.y.assign( sqdist.x );
  27136. sqdist.x.assign( dist );
  27137. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  27138. sqdist.y.assign( dist );
  27139. } );
  27140. } );
  27141. } );
  27142. } );
  27143. If( metric.equal( int( 0 ) ), () => {
  27144. sqdist.assign( sqrt( sqdist ) );
  27145. } );
  27146. return sqdist;
  27147. } ).setLayout( {
  27148. name: 'mx_worley_noise_vec2_1',
  27149. type: 'vec2',
  27150. inputs: [
  27151. { name: 'p', type: 'vec3' },
  27152. { name: 'jitter', type: 'float' },
  27153. { name: 'metric', type: 'int' }
  27154. ]
  27155. } );
  27156. const mx_worley_noise_vec2$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  27157. const mx_worley_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  27158. const metric = int( metric_immutable ).toVar();
  27159. const jitter = float( jitter_immutable ).toVar();
  27160. const p = vec3( p_immutable ).toVar();
  27161. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  27162. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  27163. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  27164. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  27165. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  27166. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  27167. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  27168. If( dist.lessThan( sqdist.x ), () => {
  27169. sqdist.z.assign( sqdist.y );
  27170. sqdist.y.assign( sqdist.x );
  27171. sqdist.x.assign( dist );
  27172. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  27173. sqdist.z.assign( sqdist.y );
  27174. sqdist.y.assign( dist );
  27175. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  27176. sqdist.z.assign( dist );
  27177. } );
  27178. } );
  27179. } );
  27180. } );
  27181. If( metric.equal( int( 0 ) ), () => {
  27182. sqdist.assign( sqrt( sqdist ) );
  27183. } );
  27184. return sqdist;
  27185. } ).setLayout( {
  27186. name: 'mx_worley_noise_vec3_1',
  27187. type: 'vec3',
  27188. inputs: [
  27189. { name: 'p', type: 'vec3' },
  27190. { name: 'jitter', type: 'float' },
  27191. { name: 'metric', type: 'int' }
  27192. ]
  27193. } );
  27194. const mx_worley_noise_vec3$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  27195. // Three.js Transpiler
  27196. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  27197. const mx_hsvtorgb = /*@__PURE__*/ Fn( ( [ hsv ] ) => {
  27198. const s = hsv.y;
  27199. const v = hsv.z;
  27200. const result = vec3().toVar();
  27201. If( s.lessThan( 0.0001 ), () => {
  27202. result.assign( vec3( v, v, v ) );
  27203. } ).Else( () => {
  27204. let h = hsv.x;
  27205. h = h.sub( floor( h ) ).mul( 6.0 ).toVar(); // TODO: check what .toVar() is needed in node system cache
  27206. const hi = int( trunc( h ) );
  27207. const f = h.sub( float( hi ) );
  27208. const p = v.mul( s.oneMinus() );
  27209. const q = v.mul( s.mul( f ).oneMinus() );
  27210. const t = v.mul( s.mul( f.oneMinus() ).oneMinus() );
  27211. If( hi.equal( int( 0 ) ), () => {
  27212. result.assign( vec3( v, t, p ) );
  27213. } ).ElseIf( hi.equal( int( 1 ) ), () => {
  27214. result.assign( vec3( q, v, p ) );
  27215. } ).ElseIf( hi.equal( int( 2 ) ), () => {
  27216. result.assign( vec3( p, v, t ) );
  27217. } ).ElseIf( hi.equal( int( 3 ) ), () => {
  27218. result.assign( vec3( p, q, v ) );
  27219. } ).ElseIf( hi.equal( int( 4 ) ), () => {
  27220. result.assign( vec3( t, p, v ) );
  27221. } ).Else( () => {
  27222. result.assign( vec3( v, p, q ) );
  27223. } );
  27224. } );
  27225. return result;
  27226. } ).setLayout( {
  27227. name: 'mx_hsvtorgb',
  27228. type: 'vec3',
  27229. inputs: [
  27230. { name: 'hsv', type: 'vec3' }
  27231. ]
  27232. } );
  27233. const mx_rgbtohsv = /*@__PURE__*/ Fn( ( [ c_immutable ] ) => {
  27234. const c = vec3( c_immutable ).toVar();
  27235. const r = float( c.x ).toVar();
  27236. const g = float( c.y ).toVar();
  27237. const b = float( c.z ).toVar();
  27238. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  27239. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  27240. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  27241. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  27242. v.assign( maxcomp );
  27243. If( maxcomp.greaterThan( 0.0 ), () => {
  27244. s.assign( delta.div( maxcomp ) );
  27245. } ).Else( () => {
  27246. s.assign( 0.0 );
  27247. } );
  27248. If( s.lessThanEqual( 0.0 ), () => {
  27249. h.assign( 0.0 );
  27250. } ).Else( () => {
  27251. If( r.greaterThanEqual( maxcomp ), () => {
  27252. h.assign( g.sub( b ).div( delta ) );
  27253. } ).ElseIf( g.greaterThanEqual( maxcomp ), () => {
  27254. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  27255. } ).Else( () => {
  27256. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  27257. } );
  27258. h.mulAssign( 1.0 / 6.0 );
  27259. If( h.lessThan( 0.0 ), () => {
  27260. h.addAssign( 1.0 );
  27261. } );
  27262. } );
  27263. return vec3( h, s, v );
  27264. } ).setLayout( {
  27265. name: 'mx_rgbtohsv',
  27266. type: 'vec3',
  27267. inputs: [
  27268. { name: 'c', type: 'vec3' }
  27269. ]
  27270. } );
  27271. // Three.js Transpiler
  27272. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  27273. const mx_srgb_texture_to_lin_rec709 = /*@__PURE__*/ Fn( ( [ color_immutable ] ) => {
  27274. const color = vec3( color_immutable ).toVar();
  27275. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  27276. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  27277. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  27278. return mix( linSeg, powSeg, isAbove );
  27279. } ).setLayout( {
  27280. name: 'mx_srgb_texture_to_lin_rec709',
  27281. type: 'vec3',
  27282. inputs: [
  27283. { name: 'color', type: 'vec3' }
  27284. ]
  27285. } );
  27286. const mx_aastep = ( threshold, value ) => {
  27287. threshold = float( threshold );
  27288. value = float( value );
  27289. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  27290. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  27291. };
  27292. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  27293. const mx_ramplr = ( valuel, valuer, texcoord = uv() ) => _ramp( valuel, valuer, texcoord, 'x' );
  27294. const mx_ramptb = ( valuet, valueb, texcoord = uv() ) => _ramp( valuet, valueb, texcoord, 'y' );
  27295. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  27296. const mx_splitlr = ( valuel, valuer, center, texcoord = uv() ) => _split( valuel, valuer, center, texcoord, 'x' );
  27297. const mx_splittb = ( valuet, valueb, center, texcoord = uv() ) => _split( valuet, valueb, center, texcoord, 'y' );
  27298. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  27299. const mx_safepower = ( in1, in2 = 1 ) => {
  27300. in1 = float( in1 );
  27301. return in1.abs().pow( in2 ).mul( in1.sign() );
  27302. };
  27303. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  27304. const mx_noise_float = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  27305. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  27306. const mx_noise_vec3 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  27307. const mx_noise_vec4 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => {
  27308. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  27309. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  27310. return noise_vec4.mul( amplitude ).add( pivot );
  27311. };
  27312. const mx_worley_noise_float = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  27313. const mx_worley_noise_vec2 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  27314. const mx_worley_noise_vec3 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  27315. const mx_cell_noise_float = ( texcoord = uv() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  27316. const mx_fractal_noise_float = ( position = uv(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_float$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude );
  27317. const mx_fractal_noise_vec2 = ( position = uv(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec2$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude );
  27318. const mx_fractal_noise_vec3 = ( position = uv(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec3$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude );
  27319. const mx_fractal_noise_vec4 = ( position = uv(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec4$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude );
  27320. /** @module getParallaxCorrectNormal **/
  27321. /**
  27322. * This computes a parallax corrected normal which is used for box-projected cube mapping (BPCEM).
  27323. *
  27324. * Reference: {@link https://devlog-martinsh.blogspot.com/2011/09/box-projected-cube-environment-mapping.html}
  27325. *
  27326. * ```js
  27327. * const uvNode = getParallaxCorrectNormal( reflectVector, vec3( 200, 100, 100 ), vec3( 0, - 50, 0 ) );
  27328. * material.envNode = pmremTexture( renderTarget.texture, uvNode );
  27329. * ```
  27330. * @function
  27331. * @param {Node<vec3>} normal - The normal to correct.
  27332. * @param {Node<vec3>} cubeSize - The cube size should reflect the size of the environment (BPCEM is usually applied in closed environments like rooms).
  27333. * @param {Node<vec3>} cubePos - The cube position.
  27334. * @return {Node<vec3>} The parallax corrected normal.
  27335. */
  27336. const getParallaxCorrectNormal = /*@__PURE__*/ Fn( ( [ normal, cubeSize, cubePos ] ) => {
  27337. const nDir = normalize( normal ).toVar( 'nDir' );
  27338. const rbmax = sub( float( 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar( 'rbmax' );
  27339. const rbmin = sub( float( -0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar( 'rbmin' );
  27340. const rbminmax = vec3().toVar( 'rbminmax' );
  27341. rbminmax.x = nDir.x.greaterThan( float( 0 ) ).select( rbmax.x, rbmin.x );
  27342. rbminmax.y = nDir.y.greaterThan( float( 0 ) ).select( rbmax.y, rbmin.y );
  27343. rbminmax.z = nDir.z.greaterThan( float( 0 ) ).select( rbmax.z, rbmin.z );
  27344. const correction = min$1( min$1( rbminmax.x, rbminmax.y ), rbminmax.z ).toVar( 'correction' );
  27345. const boxIntersection = positionWorld.add( nDir.mul( correction ) ).toVar( 'boxIntersection' );
  27346. return boxIntersection.sub( cubePos );
  27347. } );
  27348. const getShIrradianceAt = /*@__PURE__*/ Fn( ( [ normal, shCoefficients ] ) => {
  27349. // normal is assumed to have unit length
  27350. const x = normal.x, y = normal.y, z = normal.z;
  27351. // band 0
  27352. let result = shCoefficients.element( 0 ).mul( 0.886227 );
  27353. // band 1
  27354. result = result.add( shCoefficients.element( 1 ).mul( 2.0 * 0.511664 ).mul( y ) );
  27355. result = result.add( shCoefficients.element( 2 ).mul( 2.0 * 0.511664 ).mul( z ) );
  27356. result = result.add( shCoefficients.element( 3 ).mul( 2.0 * 0.511664 ).mul( x ) );
  27357. // band 2
  27358. result = result.add( shCoefficients.element( 4 ).mul( 2.0 * 0.429043 ).mul( x ).mul( y ) );
  27359. result = result.add( shCoefficients.element( 5 ).mul( 2.0 * 0.429043 ).mul( y ).mul( z ) );
  27360. result = result.add( shCoefficients.element( 6 ).mul( z.mul( z ).mul( 0.743125 ).sub( 0.247708 ) ) );
  27361. result = result.add( shCoefficients.element( 7 ).mul( 2.0 * 0.429043 ).mul( x ).mul( z ) );
  27362. result = result.add( shCoefficients.element( 8 ).mul( 0.429043 ).mul( mul( x, x ).sub( mul( y, y ) ) ) );
  27363. return result;
  27364. } );
  27365. // constants
  27366. var TSL = /*#__PURE__*/Object.freeze({
  27367. __proto__: null,
  27368. BRDF_GGX: BRDF_GGX,
  27369. BRDF_Lambert: BRDF_Lambert,
  27370. BasicShadowFilter: BasicShadowFilter,
  27371. Break: Break,
  27372. Const: Const,
  27373. Continue: Continue,
  27374. DFGApprox: DFGApprox,
  27375. D_GGX: D_GGX,
  27376. Discard: Discard,
  27377. EPSILON: EPSILON,
  27378. F_Schlick: F_Schlick,
  27379. Fn: Fn,
  27380. INFINITY: INFINITY,
  27381. If: If,
  27382. Loop: Loop,
  27383. NodeAccess: NodeAccess,
  27384. NodeShaderStage: NodeShaderStage,
  27385. NodeType: NodeType,
  27386. NodeUpdateType: NodeUpdateType,
  27387. PCFShadowFilter: PCFShadowFilter,
  27388. PCFSoftShadowFilter: PCFSoftShadowFilter,
  27389. PI: PI,
  27390. PI2: PI2,
  27391. Return: Return,
  27392. Schlick_to_F0: Schlick_to_F0,
  27393. ScriptableNodeResources: ScriptableNodeResources,
  27394. ShaderNode: ShaderNode,
  27395. TBNViewMatrix: TBNViewMatrix,
  27396. VSMShadowFilter: VSMShadowFilter,
  27397. V_GGX_SmithCorrelated: V_GGX_SmithCorrelated,
  27398. Var: Var,
  27399. abs: abs,
  27400. acesFilmicToneMapping: acesFilmicToneMapping,
  27401. acos: acos,
  27402. add: add,
  27403. addMethodChaining: addMethodChaining,
  27404. addNodeElement: addNodeElement,
  27405. agxToneMapping: agxToneMapping,
  27406. all: all,
  27407. alphaT: alphaT,
  27408. and: and,
  27409. anisotropy: anisotropy,
  27410. anisotropyB: anisotropyB,
  27411. anisotropyT: anisotropyT,
  27412. any: any,
  27413. append: append,
  27414. array: array,
  27415. arrayBuffer: arrayBuffer,
  27416. asin: asin,
  27417. assign: assign,
  27418. atan: atan,
  27419. atan2: atan2,
  27420. atomicAdd: atomicAdd,
  27421. atomicAnd: atomicAnd,
  27422. atomicFunc: atomicFunc,
  27423. atomicLoad: atomicLoad,
  27424. atomicMax: atomicMax,
  27425. atomicMin: atomicMin,
  27426. atomicOr: atomicOr,
  27427. atomicStore: atomicStore,
  27428. atomicSub: atomicSub,
  27429. atomicXor: atomicXor,
  27430. attenuationColor: attenuationColor,
  27431. attenuationDistance: attenuationDistance,
  27432. attribute: attribute,
  27433. attributeArray: attributeArray,
  27434. backgroundBlurriness: backgroundBlurriness,
  27435. backgroundIntensity: backgroundIntensity,
  27436. backgroundRotation: backgroundRotation,
  27437. batch: batch,
  27438. billboarding: billboarding,
  27439. bitAnd: bitAnd,
  27440. bitNot: bitNot,
  27441. bitOr: bitOr,
  27442. bitXor: bitXor,
  27443. bitangentGeometry: bitangentGeometry,
  27444. bitangentLocal: bitangentLocal,
  27445. bitangentView: bitangentView,
  27446. bitangentWorld: bitangentWorld,
  27447. bitcast: bitcast,
  27448. blendBurn: blendBurn,
  27449. blendColor: blendColor,
  27450. blendDodge: blendDodge,
  27451. blendOverlay: blendOverlay,
  27452. blendScreen: blendScreen,
  27453. blur: blur,
  27454. bool: bool,
  27455. buffer: buffer,
  27456. bufferAttribute: bufferAttribute,
  27457. bumpMap: bumpMap,
  27458. burn: burn,
  27459. bvec2: bvec2,
  27460. bvec3: bvec3,
  27461. bvec4: bvec4,
  27462. bypass: bypass,
  27463. cache: cache,
  27464. call: call,
  27465. cameraFar: cameraFar,
  27466. cameraIndex: cameraIndex,
  27467. cameraNear: cameraNear,
  27468. cameraNormalMatrix: cameraNormalMatrix,
  27469. cameraPosition: cameraPosition,
  27470. cameraProjectionMatrix: cameraProjectionMatrix,
  27471. cameraProjectionMatrixInverse: cameraProjectionMatrixInverse,
  27472. cameraViewMatrix: cameraViewMatrix,
  27473. cameraWorldMatrix: cameraWorldMatrix,
  27474. cbrt: cbrt,
  27475. cdl: cdl,
  27476. ceil: ceil,
  27477. checker: checker,
  27478. cineonToneMapping: cineonToneMapping,
  27479. clamp: clamp,
  27480. clearcoat: clearcoat,
  27481. clearcoatRoughness: clearcoatRoughness,
  27482. code: code,
  27483. color: color,
  27484. colorSpaceToWorking: colorSpaceToWorking,
  27485. colorToDirection: colorToDirection,
  27486. compute: compute,
  27487. cond: cond,
  27488. context: context,
  27489. convert: convert,
  27490. convertColorSpace: convertColorSpace,
  27491. convertToTexture: convertToTexture,
  27492. cos: cos,
  27493. cross: cross,
  27494. cubeTexture: cubeTexture,
  27495. dFdx: dFdx,
  27496. dFdy: dFdy,
  27497. dashSize: dashSize,
  27498. defaultBuildStages: defaultBuildStages,
  27499. defaultShaderStages: defaultShaderStages,
  27500. defined: defined,
  27501. degrees: degrees,
  27502. deltaTime: deltaTime,
  27503. densityFog: densityFog,
  27504. densityFogFactor: densityFogFactor,
  27505. depth: depth,
  27506. depthPass: depthPass,
  27507. difference: difference,
  27508. diffuseColor: diffuseColor,
  27509. directPointLight: directPointLight,
  27510. directionToColor: directionToColor,
  27511. dispersion: dispersion,
  27512. distance: distance,
  27513. div: div,
  27514. dodge: dodge,
  27515. dot: dot,
  27516. drawIndex: drawIndex,
  27517. dynamicBufferAttribute: dynamicBufferAttribute,
  27518. element: element,
  27519. emissive: emissive,
  27520. equal: equal,
  27521. equals: equals,
  27522. equirectUV: equirectUV,
  27523. exp: exp,
  27524. exp2: exp2,
  27525. expression: expression,
  27526. faceDirection: faceDirection,
  27527. faceForward: faceForward,
  27528. faceforward: faceforward,
  27529. float: float,
  27530. floor: floor,
  27531. fog: fog,
  27532. fract: fract,
  27533. frameGroup: frameGroup,
  27534. frameId: frameId,
  27535. frontFacing: frontFacing,
  27536. fwidth: fwidth,
  27537. gain: gain,
  27538. gapSize: gapSize,
  27539. getConstNodeType: getConstNodeType,
  27540. getCurrentStack: getCurrentStack,
  27541. getDirection: getDirection,
  27542. getDistanceAttenuation: getDistanceAttenuation,
  27543. getGeometryRoughness: getGeometryRoughness,
  27544. getNormalFromDepth: getNormalFromDepth,
  27545. getParallaxCorrectNormal: getParallaxCorrectNormal,
  27546. getRoughness: getRoughness,
  27547. getScreenPosition: getScreenPosition,
  27548. getShIrradianceAt: getShIrradianceAt,
  27549. getTextureIndex: getTextureIndex,
  27550. getViewPosition: getViewPosition,
  27551. globalId: globalId,
  27552. glsl: glsl,
  27553. glslFn: glslFn,
  27554. grayscale: grayscale,
  27555. greaterThan: greaterThan,
  27556. greaterThanEqual: greaterThanEqual,
  27557. hash: hash,
  27558. highpModelNormalViewMatrix: highpModelNormalViewMatrix,
  27559. highpModelViewMatrix: highpModelViewMatrix,
  27560. hue: hue,
  27561. instance: instance,
  27562. instanceIndex: instanceIndex,
  27563. instancedArray: instancedArray,
  27564. instancedBufferAttribute: instancedBufferAttribute,
  27565. instancedDynamicBufferAttribute: instancedDynamicBufferAttribute,
  27566. instancedMesh: instancedMesh,
  27567. int: int,
  27568. inverseSqrt: inverseSqrt,
  27569. inversesqrt: inversesqrt,
  27570. invocationLocalIndex: invocationLocalIndex,
  27571. invocationSubgroupIndex: invocationSubgroupIndex,
  27572. ior: ior,
  27573. iridescence: iridescence,
  27574. iridescenceIOR: iridescenceIOR,
  27575. iridescenceThickness: iridescenceThickness,
  27576. ivec2: ivec2,
  27577. ivec3: ivec3,
  27578. ivec4: ivec4,
  27579. js: js,
  27580. label: label,
  27581. length: length,
  27582. lengthSq: lengthSq,
  27583. lessThan: lessThan,
  27584. lessThanEqual: lessThanEqual,
  27585. lightPosition: lightPosition,
  27586. lightProjectionUV: lightProjectionUV,
  27587. lightShadowMatrix: lightShadowMatrix,
  27588. lightTargetDirection: lightTargetDirection,
  27589. lightTargetPosition: lightTargetPosition,
  27590. lightViewPosition: lightViewPosition,
  27591. lightingContext: lightingContext,
  27592. lights: lights,
  27593. linearDepth: linearDepth,
  27594. linearToneMapping: linearToneMapping,
  27595. localId: localId,
  27596. log: log,
  27597. log2: log2,
  27598. logarithmicDepthToViewZ: logarithmicDepthToViewZ,
  27599. loop: loop,
  27600. luminance: luminance,
  27601. mat2: mat2,
  27602. mat3: mat3,
  27603. mat4: mat4,
  27604. matcapUV: matcapUV,
  27605. materialAO: materialAO,
  27606. materialAlphaTest: materialAlphaTest,
  27607. materialAnisotropy: materialAnisotropy,
  27608. materialAnisotropyVector: materialAnisotropyVector,
  27609. materialAttenuationColor: materialAttenuationColor,
  27610. materialAttenuationDistance: materialAttenuationDistance,
  27611. materialClearcoat: materialClearcoat,
  27612. materialClearcoatNormal: materialClearcoatNormal,
  27613. materialClearcoatRoughness: materialClearcoatRoughness,
  27614. materialColor: materialColor,
  27615. materialDispersion: materialDispersion,
  27616. materialEmissive: materialEmissive,
  27617. materialIOR: materialIOR,
  27618. materialIridescence: materialIridescence,
  27619. materialIridescenceIOR: materialIridescenceIOR,
  27620. materialIridescenceThickness: materialIridescenceThickness,
  27621. materialLightMap: materialLightMap,
  27622. materialLineDashOffset: materialLineDashOffset,
  27623. materialLineDashSize: materialLineDashSize,
  27624. materialLineGapSize: materialLineGapSize,
  27625. materialLineScale: materialLineScale,
  27626. materialLineWidth: materialLineWidth,
  27627. materialMetalness: materialMetalness,
  27628. materialNormal: materialNormal,
  27629. materialOpacity: materialOpacity,
  27630. materialPointSize: materialPointSize,
  27631. materialReference: materialReference,
  27632. materialReflectivity: materialReflectivity,
  27633. materialRefractionRatio: materialRefractionRatio,
  27634. materialRotation: materialRotation,
  27635. materialRoughness: materialRoughness,
  27636. materialSheen: materialSheen,
  27637. materialSheenRoughness: materialSheenRoughness,
  27638. materialShininess: materialShininess,
  27639. materialSpecular: materialSpecular,
  27640. materialSpecularColor: materialSpecularColor,
  27641. materialSpecularIntensity: materialSpecularIntensity,
  27642. materialSpecularStrength: materialSpecularStrength,
  27643. materialThickness: materialThickness,
  27644. materialTransmission: materialTransmission,
  27645. max: max$1,
  27646. maxMipLevel: maxMipLevel,
  27647. mediumpModelViewMatrix: mediumpModelViewMatrix,
  27648. metalness: metalness,
  27649. min: min$1,
  27650. mix: mix,
  27651. mixElement: mixElement,
  27652. mod: mod,
  27653. modInt: modInt,
  27654. modelDirection: modelDirection,
  27655. modelNormalMatrix: modelNormalMatrix,
  27656. modelPosition: modelPosition,
  27657. modelScale: modelScale,
  27658. modelViewMatrix: modelViewMatrix,
  27659. modelViewPosition: modelViewPosition,
  27660. modelViewProjection: modelViewProjection,
  27661. modelWorldMatrix: modelWorldMatrix,
  27662. modelWorldMatrixInverse: modelWorldMatrixInverse,
  27663. morphReference: morphReference,
  27664. mrt: mrt,
  27665. mul: mul,
  27666. mx_aastep: mx_aastep,
  27667. mx_cell_noise_float: mx_cell_noise_float,
  27668. mx_contrast: mx_contrast,
  27669. mx_fractal_noise_float: mx_fractal_noise_float,
  27670. mx_fractal_noise_vec2: mx_fractal_noise_vec2,
  27671. mx_fractal_noise_vec3: mx_fractal_noise_vec3,
  27672. mx_fractal_noise_vec4: mx_fractal_noise_vec4,
  27673. mx_hsvtorgb: mx_hsvtorgb,
  27674. mx_noise_float: mx_noise_float,
  27675. mx_noise_vec3: mx_noise_vec3,
  27676. mx_noise_vec4: mx_noise_vec4,
  27677. mx_ramplr: mx_ramplr,
  27678. mx_ramptb: mx_ramptb,
  27679. mx_rgbtohsv: mx_rgbtohsv,
  27680. mx_safepower: mx_safepower,
  27681. mx_splitlr: mx_splitlr,
  27682. mx_splittb: mx_splittb,
  27683. mx_srgb_texture_to_lin_rec709: mx_srgb_texture_to_lin_rec709,
  27684. mx_transform_uv: mx_transform_uv,
  27685. mx_worley_noise_float: mx_worley_noise_float,
  27686. mx_worley_noise_vec2: mx_worley_noise_vec2,
  27687. mx_worley_noise_vec3: mx_worley_noise_vec3,
  27688. negate: negate,
  27689. neutralToneMapping: neutralToneMapping,
  27690. nodeArray: nodeArray,
  27691. nodeImmutable: nodeImmutable,
  27692. nodeObject: nodeObject,
  27693. nodeObjects: nodeObjects,
  27694. nodeProxy: nodeProxy,
  27695. normalFlat: normalFlat,
  27696. normalGeometry: normalGeometry,
  27697. normalLocal: normalLocal,
  27698. normalMap: normalMap,
  27699. normalView: normalView,
  27700. normalWorld: normalWorld,
  27701. normalize: normalize,
  27702. not: not,
  27703. notEqual: notEqual,
  27704. numWorkgroups: numWorkgroups,
  27705. objectDirection: objectDirection,
  27706. objectGroup: objectGroup,
  27707. objectPosition: objectPosition,
  27708. objectScale: objectScale,
  27709. objectViewPosition: objectViewPosition,
  27710. objectWorldMatrix: objectWorldMatrix,
  27711. oneMinus: oneMinus,
  27712. or: or,
  27713. orthographicDepthToViewZ: orthographicDepthToViewZ,
  27714. oscSawtooth: oscSawtooth,
  27715. oscSine: oscSine,
  27716. oscSquare: oscSquare,
  27717. oscTriangle: oscTriangle,
  27718. output: output,
  27719. outputStruct: outputStruct,
  27720. overlay: overlay,
  27721. overloadingFn: overloadingFn,
  27722. parabola: parabola,
  27723. parallaxDirection: parallaxDirection,
  27724. parallaxUV: parallaxUV,
  27725. parameter: parameter,
  27726. pass: pass,
  27727. passTexture: passTexture,
  27728. pcurve: pcurve,
  27729. perspectiveDepthToViewZ: perspectiveDepthToViewZ,
  27730. pmremTexture: pmremTexture,
  27731. pointUV: pointUV,
  27732. pointWidth: pointWidth,
  27733. positionGeometry: positionGeometry,
  27734. positionLocal: positionLocal,
  27735. positionPrevious: positionPrevious,
  27736. positionView: positionView,
  27737. positionViewDirection: positionViewDirection,
  27738. positionWorld: positionWorld,
  27739. positionWorldDirection: positionWorldDirection,
  27740. posterize: posterize,
  27741. pow: pow,
  27742. pow2: pow2,
  27743. pow3: pow3,
  27744. pow4: pow4,
  27745. property: property,
  27746. radians: radians,
  27747. rand: rand,
  27748. range: range,
  27749. rangeFog: rangeFog,
  27750. rangeFogFactor: rangeFogFactor,
  27751. reciprocal: reciprocal,
  27752. reference: reference,
  27753. referenceBuffer: referenceBuffer,
  27754. reflect: reflect,
  27755. reflectVector: reflectVector,
  27756. reflectView: reflectView,
  27757. reflector: reflector,
  27758. refract: refract,
  27759. refractVector: refractVector,
  27760. refractView: refractView,
  27761. reinhardToneMapping: reinhardToneMapping,
  27762. remainder: remainder,
  27763. remap: remap,
  27764. remapClamp: remapClamp,
  27765. renderGroup: renderGroup,
  27766. renderOutput: renderOutput,
  27767. rendererReference: rendererReference,
  27768. rotate: rotate,
  27769. rotateUV: rotateUV,
  27770. roughness: roughness,
  27771. round: round,
  27772. rtt: rtt,
  27773. sRGBTransferEOTF: sRGBTransferEOTF,
  27774. sRGBTransferOETF: sRGBTransferOETF,
  27775. sampler: sampler,
  27776. saturate: saturate,
  27777. saturation: saturation,
  27778. screen: screen,
  27779. screenCoordinate: screenCoordinate,
  27780. screenSize: screenSize,
  27781. screenUV: screenUV,
  27782. scriptable: scriptable,
  27783. scriptableValue: scriptableValue,
  27784. select: select,
  27785. setCurrentStack: setCurrentStack,
  27786. shaderStages: shaderStages,
  27787. shadow: shadow,
  27788. shadowPositionWorld: shadowPositionWorld,
  27789. shapeCircle: shapeCircle,
  27790. sharedUniformGroup: sharedUniformGroup,
  27791. sheen: sheen,
  27792. sheenRoughness: sheenRoughness,
  27793. shiftLeft: shiftLeft,
  27794. shiftRight: shiftRight,
  27795. shininess: shininess,
  27796. sign: sign,
  27797. sin: sin,
  27798. sinc: sinc,
  27799. skinning: skinning,
  27800. skinningReference: skinningReference,
  27801. smoothstep: smoothstep,
  27802. smoothstepElement: smoothstepElement,
  27803. specularColor: specularColor,
  27804. specularF90: specularF90,
  27805. spherizeUV: spherizeUV,
  27806. split: split,
  27807. spritesheetUV: spritesheetUV,
  27808. sqrt: sqrt,
  27809. stack: stack,
  27810. step: step,
  27811. storage: storage,
  27812. storageBarrier: storageBarrier,
  27813. storageObject: storageObject,
  27814. storageTexture: storageTexture,
  27815. string: string,
  27816. sub: sub,
  27817. subgroupIndex: subgroupIndex,
  27818. subgroupSize: subgroupSize,
  27819. tan: tan,
  27820. tangentGeometry: tangentGeometry,
  27821. tangentLocal: tangentLocal,
  27822. tangentView: tangentView,
  27823. tangentWorld: tangentWorld,
  27824. temp: temp,
  27825. texture: texture,
  27826. texture3D: texture3D,
  27827. textureBarrier: textureBarrier,
  27828. textureBicubic: textureBicubic,
  27829. textureCubeUV: textureCubeUV,
  27830. textureLoad: textureLoad,
  27831. textureSize: textureSize,
  27832. textureStore: textureStore,
  27833. thickness: thickness,
  27834. time: time,
  27835. timerDelta: timerDelta,
  27836. timerGlobal: timerGlobal,
  27837. timerLocal: timerLocal,
  27838. toOutputColorSpace: toOutputColorSpace,
  27839. toWorkingColorSpace: toWorkingColorSpace,
  27840. toneMapping: toneMapping,
  27841. toneMappingExposure: toneMappingExposure,
  27842. toonOutlinePass: toonOutlinePass,
  27843. transformDirection: transformDirection,
  27844. transformNormal: transformNormal,
  27845. transformNormalToView: transformNormalToView,
  27846. transformedBentNormalView: transformedBentNormalView,
  27847. transformedBitangentView: transformedBitangentView,
  27848. transformedBitangentWorld: transformedBitangentWorld,
  27849. transformedClearcoatNormalView: transformedClearcoatNormalView,
  27850. transformedNormalView: transformedNormalView,
  27851. transformedNormalWorld: transformedNormalWorld,
  27852. transformedTangentView: transformedTangentView,
  27853. transformedTangentWorld: transformedTangentWorld,
  27854. transmission: transmission,
  27855. transpose: transpose,
  27856. triNoise3D: triNoise3D,
  27857. triplanarTexture: triplanarTexture,
  27858. triplanarTextures: triplanarTextures,
  27859. trunc: trunc,
  27860. tslFn: tslFn,
  27861. uint: uint,
  27862. uniform: uniform,
  27863. uniformArray: uniformArray,
  27864. uniformGroup: uniformGroup,
  27865. uniforms: uniforms,
  27866. userData: userData,
  27867. uv: uv,
  27868. uvec2: uvec2,
  27869. uvec3: uvec3,
  27870. uvec4: uvec4,
  27871. varying: varying,
  27872. varyingProperty: varyingProperty,
  27873. vec2: vec2,
  27874. vec3: vec3,
  27875. vec4: vec4,
  27876. vectorComponents: vectorComponents,
  27877. velocity: velocity,
  27878. vertexColor: vertexColor,
  27879. vertexIndex: vertexIndex,
  27880. vertexStage: vertexStage,
  27881. vibrance: vibrance,
  27882. viewZToLogarithmicDepth: viewZToLogarithmicDepth,
  27883. viewZToOrthographicDepth: viewZToOrthographicDepth,
  27884. viewZToPerspectiveDepth: viewZToPerspectiveDepth,
  27885. viewport: viewport,
  27886. viewportBottomLeft: viewportBottomLeft,
  27887. viewportCoordinate: viewportCoordinate,
  27888. viewportDepthTexture: viewportDepthTexture,
  27889. viewportLinearDepth: viewportLinearDepth,
  27890. viewportMipTexture: viewportMipTexture,
  27891. viewportResolution: viewportResolution,
  27892. viewportSafeUV: viewportSafeUV,
  27893. viewportSharedTexture: viewportSharedTexture,
  27894. viewportSize: viewportSize,
  27895. viewportTexture: viewportTexture,
  27896. viewportTopLeft: viewportTopLeft,
  27897. viewportUV: viewportUV,
  27898. wgsl: wgsl,
  27899. wgslFn: wgslFn,
  27900. workgroupArray: workgroupArray,
  27901. workgroupBarrier: workgroupBarrier,
  27902. workgroupId: workgroupId,
  27903. workingToColorSpace: workingToColorSpace,
  27904. xor: xor
  27905. });
  27906. const _clearColor$1 = /*@__PURE__*/ new Color4();
  27907. /**
  27908. * This renderer module manages the background.
  27909. *
  27910. * @private
  27911. * @augments DataMap
  27912. */
  27913. class Background extends DataMap {
  27914. /**
  27915. * Constructs a new background management component.
  27916. *
  27917. * @param {Renderer} renderer - The renderer.
  27918. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  27919. */
  27920. constructor( renderer, nodes ) {
  27921. super();
  27922. /**
  27923. * The renderer.
  27924. *
  27925. * @type {Renderer}
  27926. */
  27927. this.renderer = renderer;
  27928. /**
  27929. * Renderer component for managing nodes related logic.
  27930. *
  27931. * @type {Nodes}
  27932. */
  27933. this.nodes = nodes;
  27934. }
  27935. /**
  27936. * Updates the background for the given scene. Depending on how `Scene.background`
  27937. * or `Scene.backgroundNode` are configured, this method might configure a simple clear
  27938. * or add a mesh to the render list for rendering the background as a textured plane
  27939. * or skybox.
  27940. *
  27941. * @param {Scene} scene - The scene.
  27942. * @param {RenderList} renderList - The current render list.
  27943. * @param {RenderContext} renderContext - The current render context.
  27944. */
  27945. update( scene, renderList, renderContext ) {
  27946. const renderer = this.renderer;
  27947. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  27948. let forceClear = false;
  27949. if ( background === null ) {
  27950. // no background settings, use clear color configuration from the renderer
  27951. renderer._clearColor.getRGB( _clearColor$1, LinearSRGBColorSpace );
  27952. _clearColor$1.a = renderer._clearColor.a;
  27953. } else if ( background.isColor === true ) {
  27954. // background is an opaque color
  27955. background.getRGB( _clearColor$1, LinearSRGBColorSpace );
  27956. _clearColor$1.a = 1;
  27957. forceClear = true;
  27958. } else if ( background.isNode === true ) {
  27959. const sceneData = this.get( scene );
  27960. const backgroundNode = background;
  27961. _clearColor$1.copy( renderer._clearColor );
  27962. let backgroundMesh = sceneData.backgroundMesh;
  27963. if ( backgroundMesh === undefined ) {
  27964. const backgroundMeshNode = context( vec4( backgroundNode ).mul( backgroundIntensity ), {
  27965. // @TODO: Add Texture2D support using node context
  27966. getUV: () => backgroundRotation.mul( normalWorld ),
  27967. getTextureLevel: () => backgroundBlurriness
  27968. } );
  27969. let viewProj = modelViewProjection;
  27970. viewProj = viewProj.setZ( viewProj.w );
  27971. const nodeMaterial = new NodeMaterial();
  27972. nodeMaterial.name = 'Background.material';
  27973. nodeMaterial.side = BackSide;
  27974. nodeMaterial.depthTest = false;
  27975. nodeMaterial.depthWrite = false;
  27976. nodeMaterial.fog = false;
  27977. nodeMaterial.lights = false;
  27978. nodeMaterial.vertexNode = viewProj;
  27979. nodeMaterial.colorNode = backgroundMeshNode;
  27980. sceneData.backgroundMeshNode = backgroundMeshNode;
  27981. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  27982. backgroundMesh.frustumCulled = false;
  27983. backgroundMesh.name = 'Background.mesh';
  27984. backgroundMesh.onBeforeRender = function ( renderer, scene, camera ) {
  27985. this.matrixWorld.copyPosition( camera.matrixWorld );
  27986. };
  27987. }
  27988. const backgroundCacheKey = backgroundNode.getCacheKey();
  27989. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  27990. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  27991. sceneData.backgroundMeshNode.needsUpdate = true;
  27992. backgroundMesh.material.needsUpdate = true;
  27993. sceneData.backgroundCacheKey = backgroundCacheKey;
  27994. }
  27995. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null, null );
  27996. } else {
  27997. console.error( 'THREE.Renderer: Unsupported background configuration.', background );
  27998. }
  27999. //
  28000. const environmentBlendMode = renderer.xr.getEnvironmentBlendMode();
  28001. if ( environmentBlendMode === 'additive' ) {
  28002. _clearColor$1.set( 0, 0, 0, 1 );
  28003. } else if ( environmentBlendMode === 'alpha-blend' ) {
  28004. _clearColor$1.set( 0, 0, 0, 0 );
  28005. }
  28006. //
  28007. if ( renderer.autoClear === true || forceClear === true ) {
  28008. const clearColorValue = renderContext.clearColorValue;
  28009. clearColorValue.r = _clearColor$1.r;
  28010. clearColorValue.g = _clearColor$1.g;
  28011. clearColorValue.b = _clearColor$1.b;
  28012. clearColorValue.a = _clearColor$1.a;
  28013. // premultiply alpha
  28014. if ( renderer.backend.isWebGLBackend === true || renderer.alpha === true ) {
  28015. clearColorValue.r *= clearColorValue.a;
  28016. clearColorValue.g *= clearColorValue.a;
  28017. clearColorValue.b *= clearColorValue.a;
  28018. }
  28019. //
  28020. renderContext.depthClearValue = renderer._clearDepth;
  28021. renderContext.stencilClearValue = renderer._clearStencil;
  28022. renderContext.clearColor = renderer.autoClearColor === true;
  28023. renderContext.clearDepth = renderer.autoClearDepth === true;
  28024. renderContext.clearStencil = renderer.autoClearStencil === true;
  28025. } else {
  28026. renderContext.clearColor = false;
  28027. renderContext.clearDepth = false;
  28028. renderContext.clearStencil = false;
  28029. }
  28030. }
  28031. }
  28032. let _id$6 = 0;
  28033. /**
  28034. * A bind group represents a collection of bindings and thus a collection
  28035. * or resources. Bind groups are assigned to pipelines to provide them
  28036. * with the required resources (like uniform buffers or textures).
  28037. *
  28038. * @private
  28039. */
  28040. class BindGroup {
  28041. /**
  28042. * Constructs a new bind group.
  28043. *
  28044. * @param {String} name - The bind group's name.
  28045. * @param {Array<Binding>} bindings - An array of bindings.
  28046. * @param {Number} index - The group index.
  28047. * @param {Array<Binding>} bindingsReference - An array of reference bindings.
  28048. */
  28049. constructor( name = '', bindings = [], index = 0, bindingsReference = [] ) {
  28050. /**
  28051. * The bind group's name.
  28052. *
  28053. * @type {String}
  28054. */
  28055. this.name = name;
  28056. /**
  28057. * An array of bindings.
  28058. *
  28059. * @type {Array<Binding>}
  28060. */
  28061. this.bindings = bindings;
  28062. /**
  28063. * The group index.
  28064. *
  28065. * @type {Number}
  28066. */
  28067. this.index = index;
  28068. /**
  28069. * An array of reference bindings.
  28070. *
  28071. * @type {Array<Binding>}
  28072. */
  28073. this.bindingsReference = bindingsReference;
  28074. /**
  28075. * The group's ID.
  28076. *
  28077. * @type {Number}
  28078. */
  28079. this.id = _id$6 ++;
  28080. }
  28081. }
  28082. /**
  28083. * This module represents the state of a node builder after it was
  28084. * used to build the nodes for a render object. The state holds the
  28085. * results of the build for further processing in the renderer.
  28086. *
  28087. * Render objects with identical cache keys share the same node builder state.
  28088. *
  28089. * @private
  28090. */
  28091. class NodeBuilderState {
  28092. /**
  28093. * Constructs a new node builder state.
  28094. *
  28095. * @param {String?} vertexShader - The native vertex shader code.
  28096. * @param {String?} fragmentShader - The native fragment shader code.
  28097. * @param {String?} computeShader - The native compute shader code.
  28098. * @param {Array<NodeAttribute>} nodeAttributes - An array of node attributes.
  28099. * @param {Array<BindGroup>} bindings - An array of bind groups.
  28100. * @param {Array<Node>} updateNodes - An array of nodes that implement their `update()` method.
  28101. * @param {Array<Node>} updateBeforeNodes - An array of nodes that implement their `updateBefore()` method.
  28102. * @param {Array<Node>} updateAfterNodes - An array of nodes that implement their `updateAfter()` method.
  28103. * @param {NodeMaterialObserver} observer - A node material observer.
  28104. * @param {Array<Object>} transforms - An array with transform attribute objects. Only relevant when using compute shaders with WebGL 2.
  28105. */
  28106. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, observer, transforms = [] ) {
  28107. /**
  28108. * The native vertex shader code.
  28109. *
  28110. * @type {String}
  28111. */
  28112. this.vertexShader = vertexShader;
  28113. /**
  28114. * The native fragment shader code.
  28115. *
  28116. * @type {String}
  28117. */
  28118. this.fragmentShader = fragmentShader;
  28119. /**
  28120. * The native compute shader code.
  28121. *
  28122. * @type {String}
  28123. */
  28124. this.computeShader = computeShader;
  28125. /**
  28126. * An array with transform attribute objects.
  28127. * Only relevant when using compute shaders with WebGL 2.
  28128. *
  28129. * @type {Array<Object>}
  28130. */
  28131. this.transforms = transforms;
  28132. /**
  28133. * An array of node attributes representing
  28134. * the attributes of the shaders.
  28135. *
  28136. * @type {Array<NodeAttribute>}
  28137. */
  28138. this.nodeAttributes = nodeAttributes;
  28139. /**
  28140. * An array of bind groups representing the uniform or storage
  28141. * buffers, texture or samplers of the shader.
  28142. *
  28143. * @type {Array<BindGroup>}
  28144. */
  28145. this.bindings = bindings;
  28146. /**
  28147. * An array of nodes that implement their `update()` method.
  28148. *
  28149. * @type {Array<Node>}
  28150. */
  28151. this.updateNodes = updateNodes;
  28152. /**
  28153. * An array of nodes that implement their `updateBefore()` method.
  28154. *
  28155. * @type {Array<Node>}
  28156. */
  28157. this.updateBeforeNodes = updateBeforeNodes;
  28158. /**
  28159. * An array of nodes that implement their `updateAfter()` method.
  28160. *
  28161. * @type {Array<Node>}
  28162. */
  28163. this.updateAfterNodes = updateAfterNodes;
  28164. /**
  28165. * A node material observer.
  28166. *
  28167. * @type {NodeMaterialObserver}
  28168. */
  28169. this.observer = observer;
  28170. /**
  28171. * How often this state is used by render objects.
  28172. *
  28173. * @type {Number}
  28174. */
  28175. this.usedTimes = 0;
  28176. }
  28177. /**
  28178. * This method is used to create a array of bind groups based
  28179. * on the existing bind groups of this state. Shared groups are
  28180. * not cloned.
  28181. *
  28182. * @return {Array<BindGroup>} A array of bind groups.
  28183. */
  28184. createBindings() {
  28185. const bindings = [];
  28186. for ( const instanceGroup of this.bindings ) {
  28187. const shared = instanceGroup.bindings[ 0 ].groupNode.shared; // All bindings in the group must have the same groupNode.
  28188. if ( shared !== true ) {
  28189. const bindingsGroup = new BindGroup( instanceGroup.name, [], instanceGroup.index, instanceGroup );
  28190. bindings.push( bindingsGroup );
  28191. for ( const instanceBinding of instanceGroup.bindings ) {
  28192. bindingsGroup.bindings.push( instanceBinding.clone() );
  28193. }
  28194. } else {
  28195. bindings.push( instanceGroup );
  28196. }
  28197. }
  28198. return bindings;
  28199. }
  28200. }
  28201. /**
  28202. * {@link NodeBuilder} is going to create instances of this class during the build process
  28203. * of nodes. They represent the final shader attributes that are going to be generated
  28204. * by the builder. Arrays of node attributes is maintained in {@link NodeBuilder#attributes}
  28205. * and {@link NodeBuilder#bufferAttributes} for this purpose.
  28206. */
  28207. class NodeAttribute {
  28208. /**
  28209. * Constructs a new node attribute.
  28210. *
  28211. * @param {String} name - The name of the attribute.
  28212. * @param {String} type - The type of the attribute.
  28213. * @param {Node?} node - An optional reference to the node.
  28214. */
  28215. constructor( name, type, node = null ) {
  28216. /**
  28217. * This flag can be used for type testing.
  28218. *
  28219. * @type {Boolean}
  28220. * @readonly
  28221. * @default true
  28222. */
  28223. this.isNodeAttribute = true;
  28224. /**
  28225. * The name of the attribute.
  28226. *
  28227. * @type {String}
  28228. */
  28229. this.name = name;
  28230. /**
  28231. * The type of the attribute.
  28232. *
  28233. * @type {String}
  28234. */
  28235. this.type = type;
  28236. /**
  28237. * An optional reference to the node.
  28238. *
  28239. * @type {Node?}
  28240. * @default null
  28241. */
  28242. this.node = node;
  28243. }
  28244. }
  28245. /**
  28246. * {@link NodeBuilder} is going to create instances of this class during the build process
  28247. * of nodes. They represent the final shader uniforms that are going to be generated
  28248. * by the builder. A dictionary of node uniforms is maintained in {@link NodeBuilder#uniforms}
  28249. * for this purpose.
  28250. */
  28251. class NodeUniform {
  28252. /**
  28253. * Constructs a new node uniform.
  28254. *
  28255. * @param {String} name - The name of the uniform.
  28256. * @param {String} type - The type of the uniform.
  28257. * @param {UniformNode} node - An reference to the node.
  28258. */
  28259. constructor( name, type, node ) {
  28260. /**
  28261. * This flag can be used for type testing.
  28262. *
  28263. * @type {Boolean}
  28264. * @readonly
  28265. * @default true
  28266. */
  28267. this.isNodeUniform = true;
  28268. /**
  28269. * The name of the uniform.
  28270. *
  28271. * @type {String}
  28272. */
  28273. this.name = name;
  28274. /**
  28275. * The type of the uniform.
  28276. *
  28277. * @type {String}
  28278. */
  28279. this.type = type;
  28280. /**
  28281. * An reference to the node.
  28282. *
  28283. * @type {UniformNode}
  28284. */
  28285. this.node = node.getSelf();
  28286. }
  28287. /**
  28288. * The value of the uniform node.
  28289. *
  28290. * @type {Any}
  28291. */
  28292. get value() {
  28293. return this.node.value;
  28294. }
  28295. set value( val ) {
  28296. this.node.value = val;
  28297. }
  28298. /**
  28299. * The id of the uniform node.
  28300. *
  28301. * @type {Number}
  28302. */
  28303. get id() {
  28304. return this.node.id;
  28305. }
  28306. /**
  28307. * The uniform node's group.
  28308. *
  28309. * @type {UniformGroupNode}
  28310. */
  28311. get groupNode() {
  28312. return this.node.groupNode;
  28313. }
  28314. }
  28315. /**
  28316. * {@link NodeBuilder} is going to create instances of this class during the build process
  28317. * of nodes. They represent the final shader variables that are going to be generated
  28318. * by the builder. A dictionary of node variables is maintained in {@link NodeBuilder#vars} for
  28319. * this purpose.
  28320. */
  28321. class NodeVar {
  28322. /**
  28323. * Constructs a new node variable.
  28324. *
  28325. * @param {String} name - The name of the variable.
  28326. * @param {String} type - The type of the variable.
  28327. * @param {Boolean} [readOnly=false] - The read-only flag.
  28328. * @param {Number?} [count=null] - The size.
  28329. */
  28330. constructor( name, type, readOnly = false, count = null ) {
  28331. /**
  28332. * This flag can be used for type testing.
  28333. *
  28334. * @type {Boolean}
  28335. * @readonly
  28336. * @default true
  28337. */
  28338. this.isNodeVar = true;
  28339. /**
  28340. * The name of the variable.
  28341. *
  28342. * @type {String}
  28343. */
  28344. this.name = name;
  28345. /**
  28346. * The type of the variable.
  28347. *
  28348. * @type {String}
  28349. */
  28350. this.type = type;
  28351. /**
  28352. * The read-only flag.
  28353. *
  28354. * @type {Boolean}
  28355. */
  28356. this.readOnly = readOnly;
  28357. /**
  28358. * The size.
  28359. *
  28360. * @type {Number?}
  28361. */
  28362. this.count = count;
  28363. }
  28364. }
  28365. /**
  28366. * {@link NodeBuilder} is going to create instances of this class during the build process
  28367. * of nodes. They represent the final shader varyings that are going to be generated
  28368. * by the builder. An array of node varyings is maintained in {@link NodeBuilder#varyings} for
  28369. * this purpose.
  28370. *
  28371. * @augments NodeVar
  28372. */
  28373. class NodeVarying extends NodeVar {
  28374. /**
  28375. * Constructs a new node varying.
  28376. *
  28377. * @param {String} name - The name of the varying.
  28378. * @param {String} type - The type of the varying.
  28379. */
  28380. constructor( name, type ) {
  28381. super( name, type );
  28382. /**
  28383. * Whether this varying requires interpolation or not. This property can be used
  28384. * to check if the varying can be optimized for a variable.
  28385. *
  28386. * @type {Boolean}
  28387. * @default false
  28388. */
  28389. this.needsInterpolation = false;
  28390. /**
  28391. * This flag can be used for type testing.
  28392. *
  28393. * @type {Boolean}
  28394. * @readonly
  28395. * @default true
  28396. */
  28397. this.isNodeVarying = true;
  28398. }
  28399. }
  28400. /**
  28401. * {@link NodeBuilder} is going to create instances of this class during the build process
  28402. * of nodes. They represent user-defined, native shader code portions that are going to be
  28403. * injected by the builder. A dictionary of node codes is maintained in {@link NodeBuilder#codes}
  28404. * for this purpose.
  28405. */
  28406. class NodeCode {
  28407. /**
  28408. * Constructs a new code node.
  28409. *
  28410. * @param {String} name - The name of the code.
  28411. * @param {String} type - The node type.
  28412. * @param {String} [code=''] - The native shader code.
  28413. */
  28414. constructor( name, type, code = '' ) {
  28415. /**
  28416. * The name of the code.
  28417. *
  28418. * @type {String}
  28419. */
  28420. this.name = name;
  28421. /**
  28422. * The node type.
  28423. *
  28424. * @type {String}
  28425. */
  28426. this.type = type;
  28427. /**
  28428. * The native shader code.
  28429. *
  28430. * @type {String}
  28431. * @default ''
  28432. */
  28433. this.code = code;
  28434. Object.defineProperty( this, 'isNodeCode', { value: true } );
  28435. }
  28436. }
  28437. let _id$5 = 0;
  28438. /**
  28439. * This utility class is used in {@link NodeBuilder} as an internal
  28440. * cache data structure for node data.
  28441. */
  28442. class NodeCache {
  28443. /**
  28444. * Constructs a new node cache.
  28445. *
  28446. * @param {NodeCache?} parent - A reference to a parent cache.
  28447. */
  28448. constructor( parent = null ) {
  28449. /**
  28450. * The id of the cache.
  28451. *
  28452. * @type {Number}
  28453. * @readonly
  28454. */
  28455. this.id = _id$5 ++;
  28456. /**
  28457. * A weak map for managing node data.
  28458. *
  28459. * @type {WeakMap<Node, Object>}
  28460. */
  28461. this.nodesData = new WeakMap();
  28462. /**
  28463. * Reference to a parent node cache.
  28464. *
  28465. * @type {NodeCache?}
  28466. * @default null
  28467. */
  28468. this.parent = parent;
  28469. }
  28470. /**
  28471. * Returns the data for the given node.
  28472. *
  28473. * @param {Node} node - The node.
  28474. * @return {Object?} The data for the node.
  28475. */
  28476. getData( node ) {
  28477. let data = this.nodesData.get( node );
  28478. if ( data === undefined && this.parent !== null ) {
  28479. data = this.parent.getData( node );
  28480. }
  28481. return data;
  28482. }
  28483. /**
  28484. * Sets the data for a given node.
  28485. *
  28486. * @param {Node} node - The node.
  28487. * @param {Object} data - The data that should be cached.
  28488. */
  28489. setData( node, data ) {
  28490. this.nodesData.set( node, data );
  28491. }
  28492. }
  28493. /**
  28494. * {@link NodeBuilder} is going to create instances of this class during the build process
  28495. * of nodes. They represent the final shader struct data that are going to be generated
  28496. * by the builder. A dictionary of struct types is maintained in {@link NodeBuilder#structs}
  28497. * for this purpose.
  28498. */
  28499. class StructTypeNode extends Node {
  28500. static get type() {
  28501. return 'StructTypeNode';
  28502. }
  28503. /**
  28504. * Constructs a new struct type node.
  28505. *
  28506. * @param {String} name - The name of the struct.
  28507. * @param {Array<String>} types - An array of types.
  28508. */
  28509. constructor( name, types ) {
  28510. super();
  28511. /**
  28512. * The name of the struct.
  28513. *
  28514. * @type {String}
  28515. */
  28516. this.name = name;
  28517. /**
  28518. * An array of types.
  28519. *
  28520. * @type {Array<String>}
  28521. */
  28522. this.types = types;
  28523. /**
  28524. * This flag can be used for type testing.
  28525. *
  28526. * @type {Boolean}
  28527. * @readonly
  28528. * @default true
  28529. */
  28530. this.isStructTypeNode = true;
  28531. }
  28532. /**
  28533. * Returns the member types.
  28534. *
  28535. * @return {Array<String>} The types.
  28536. */
  28537. getMemberTypes() {
  28538. return this.types;
  28539. }
  28540. }
  28541. /**
  28542. * Abstract base class for uniforms.
  28543. *
  28544. * @abstract
  28545. * @private
  28546. */
  28547. class Uniform {
  28548. /**
  28549. * Constructs a new uniform.
  28550. *
  28551. * @param {String} name - The uniform's name.
  28552. * @param {Any} value - The uniform's value.
  28553. */
  28554. constructor( name, value ) {
  28555. /**
  28556. * The uniform's name.
  28557. *
  28558. * @type {String}
  28559. */
  28560. this.name = name;
  28561. /**
  28562. * The uniform's value.
  28563. *
  28564. * @type {Any}
  28565. */
  28566. this.value = value;
  28567. /**
  28568. * Used to build the uniform buffer according to the STD140 layout.
  28569. * Derived uniforms will set this property to a data type specific
  28570. * value.
  28571. *
  28572. * @type {Number}
  28573. */
  28574. this.boundary = 0;
  28575. /**
  28576. * The item size. Derived uniforms will set this property to a data
  28577. * type specific value.
  28578. *
  28579. * @type {Number}
  28580. */
  28581. this.itemSize = 0;
  28582. /**
  28583. * This property is set by {@link UniformsGroup} and marks
  28584. * the start position in the uniform buffer.
  28585. *
  28586. * @type {Number}
  28587. */
  28588. this.offset = 0;
  28589. }
  28590. /**
  28591. * Sets the uniform's value.
  28592. *
  28593. * @param {Any} value - The value to set.
  28594. */
  28595. setValue( value ) {
  28596. this.value = value;
  28597. }
  28598. /**
  28599. * Returns the uniform's value.
  28600. *
  28601. * @return {Any} The value.
  28602. */
  28603. getValue() {
  28604. return this.value;
  28605. }
  28606. }
  28607. /**
  28608. * Represents a Number uniform.
  28609. *
  28610. * @private
  28611. * @augments Uniform
  28612. */
  28613. class NumberUniform extends Uniform {
  28614. /**
  28615. * Constructs a new Number uniform.
  28616. *
  28617. * @param {String} name - The uniform's name.
  28618. * @param {Number} value - The uniform's value.
  28619. */
  28620. constructor( name, value = 0 ) {
  28621. super( name, value );
  28622. /**
  28623. * This flag can be used for type testing.
  28624. *
  28625. * @type {Boolean}
  28626. * @readonly
  28627. * @default true
  28628. */
  28629. this.isNumberUniform = true;
  28630. this.boundary = 4;
  28631. this.itemSize = 1;
  28632. }
  28633. }
  28634. /**
  28635. * Represents a Vector2 uniform.
  28636. *
  28637. * @private
  28638. * @augments Uniform
  28639. */
  28640. class Vector2Uniform extends Uniform {
  28641. /**
  28642. * Constructs a new Number uniform.
  28643. *
  28644. * @param {String} name - The uniform's name.
  28645. * @param {Vector2} value - The uniform's value.
  28646. */
  28647. constructor( name, value = new Vector2() ) {
  28648. super( name, value );
  28649. /**
  28650. * This flag can be used for type testing.
  28651. *
  28652. * @type {Boolean}
  28653. * @readonly
  28654. * @default true
  28655. */
  28656. this.isVector2Uniform = true;
  28657. this.boundary = 8;
  28658. this.itemSize = 2;
  28659. }
  28660. }
  28661. /**
  28662. * Represents a Vector3 uniform.
  28663. *
  28664. * @private
  28665. * @augments Uniform
  28666. */
  28667. class Vector3Uniform extends Uniform {
  28668. /**
  28669. * Constructs a new Number uniform.
  28670. *
  28671. * @param {String} name - The uniform's name.
  28672. * @param {Vector3} value - The uniform's value.
  28673. */
  28674. constructor( name, value = new Vector3() ) {
  28675. super( name, value );
  28676. /**
  28677. * This flag can be used for type testing.
  28678. *
  28679. * @type {Boolean}
  28680. * @readonly
  28681. * @default true
  28682. */
  28683. this.isVector3Uniform = true;
  28684. this.boundary = 16;
  28685. this.itemSize = 3;
  28686. }
  28687. }
  28688. /**
  28689. * Represents a Vector4 uniform.
  28690. *
  28691. * @private
  28692. * @augments Uniform
  28693. */
  28694. class Vector4Uniform extends Uniform {
  28695. /**
  28696. * Constructs a new Number uniform.
  28697. *
  28698. * @param {String} name - The uniform's name.
  28699. * @param {Vector4} value - The uniform's value.
  28700. */
  28701. constructor( name, value = new Vector4() ) {
  28702. super( name, value );
  28703. /**
  28704. * This flag can be used for type testing.
  28705. *
  28706. * @type {Boolean}
  28707. * @readonly
  28708. * @default true
  28709. */
  28710. this.isVector4Uniform = true;
  28711. this.boundary = 16;
  28712. this.itemSize = 4;
  28713. }
  28714. }
  28715. /**
  28716. * Represents a Color uniform.
  28717. *
  28718. * @private
  28719. * @augments Uniform
  28720. */
  28721. class ColorUniform extends Uniform {
  28722. /**
  28723. * Constructs a new Number uniform.
  28724. *
  28725. * @param {String} name - The uniform's name.
  28726. * @param {Color} value - The uniform's value.
  28727. */
  28728. constructor( name, value = new Color() ) {
  28729. super( name, value );
  28730. /**
  28731. * This flag can be used for type testing.
  28732. *
  28733. * @type {Boolean}
  28734. * @readonly
  28735. * @default true
  28736. */
  28737. this.isColorUniform = true;
  28738. this.boundary = 16;
  28739. this.itemSize = 3;
  28740. }
  28741. }
  28742. /**
  28743. * Represents a Matrix2 uniform.
  28744. *
  28745. * @private
  28746. * @augments Uniform
  28747. */
  28748. class Matrix2Uniform extends Uniform {
  28749. /**
  28750. * Constructs a new Number uniform.
  28751. *
  28752. * @param {String} name - The uniform's name.
  28753. * @param {Matrix2} value - The uniform's value.
  28754. */
  28755. constructor( name, value = new Matrix2() ) {
  28756. super( name, value );
  28757. /**
  28758. * This flag can be used for type testing.
  28759. *
  28760. * @type {Boolean}
  28761. * @readonly
  28762. * @default true
  28763. */
  28764. this.isMatrix2Uniform = true;
  28765. this.boundary = 16;
  28766. this.itemSize = 4;
  28767. }
  28768. }
  28769. /**
  28770. * Represents a Matrix3 uniform.
  28771. *
  28772. * @private
  28773. * @augments Uniform
  28774. */
  28775. class Matrix3Uniform extends Uniform {
  28776. /**
  28777. * Constructs a new Number uniform.
  28778. *
  28779. * @param {String} name - The uniform's name.
  28780. * @param {Matrix3} value - The uniform's value.
  28781. */
  28782. constructor( name, value = new Matrix3() ) {
  28783. super( name, value );
  28784. /**
  28785. * This flag can be used for type testing.
  28786. *
  28787. * @type {Boolean}
  28788. * @readonly
  28789. * @default true
  28790. */
  28791. this.isMatrix3Uniform = true;
  28792. this.boundary = 48;
  28793. this.itemSize = 12;
  28794. }
  28795. }
  28796. /**
  28797. * Represents a Matrix4 uniform.
  28798. *
  28799. * @private
  28800. * @augments Uniform
  28801. */
  28802. class Matrix4Uniform extends Uniform {
  28803. /**
  28804. * Constructs a new Number uniform.
  28805. *
  28806. * @param {String} name - The uniform's name.
  28807. * @param {Matrix4} value - The uniform's value.
  28808. */
  28809. constructor( name, value = new Matrix4() ) {
  28810. super( name, value );
  28811. /**
  28812. * This flag can be used for type testing.
  28813. *
  28814. * @type {Boolean}
  28815. * @readonly
  28816. * @default true
  28817. */
  28818. this.isMatrix4Uniform = true;
  28819. this.boundary = 64;
  28820. this.itemSize = 16;
  28821. }
  28822. }
  28823. /**
  28824. * A special form of Number uniform binding type.
  28825. * It's value is managed by a node object.
  28826. *
  28827. * @private
  28828. * @augments NumberUniform
  28829. */
  28830. class NumberNodeUniform extends NumberUniform {
  28831. /**
  28832. * Constructs a new node-based Number uniform.
  28833. *
  28834. * @param {NodeUniform} nodeUniform - The node uniform.
  28835. */
  28836. constructor( nodeUniform ) {
  28837. super( nodeUniform.name, nodeUniform.value );
  28838. /**
  28839. * The node uniform.
  28840. *
  28841. * @type {NodeUniform}
  28842. */
  28843. this.nodeUniform = nodeUniform;
  28844. }
  28845. /**
  28846. * Overwritten to return the value of the node uniform.
  28847. *
  28848. * @return {Number} The value.
  28849. */
  28850. getValue() {
  28851. return this.nodeUniform.value;
  28852. }
  28853. /**
  28854. * Returns the node uniform data type.
  28855. *
  28856. * @return {String} The data type.
  28857. */
  28858. getType() {
  28859. return this.nodeUniform.type;
  28860. }
  28861. }
  28862. /**
  28863. * A special form of Vector2 uniform binding type.
  28864. * It's value is managed by a node object.
  28865. *
  28866. * @private
  28867. * @augments Vector2Uniform
  28868. */
  28869. class Vector2NodeUniform extends Vector2Uniform {
  28870. /**
  28871. * Constructs a new node-based Vector2 uniform.
  28872. *
  28873. * @param {NodeUniform} nodeUniform - The node uniform.
  28874. */
  28875. constructor( nodeUniform ) {
  28876. super( nodeUniform.name, nodeUniform.value );
  28877. /**
  28878. * The node uniform.
  28879. *
  28880. * @type {NodeUniform}
  28881. */
  28882. this.nodeUniform = nodeUniform;
  28883. }
  28884. /**
  28885. * Overwritten to return the value of the node uniform.
  28886. *
  28887. * @return {Vector2} The value.
  28888. */
  28889. getValue() {
  28890. return this.nodeUniform.value;
  28891. }
  28892. /**
  28893. * Returns the node uniform data type.
  28894. *
  28895. * @return {String} The data type.
  28896. */
  28897. getType() {
  28898. return this.nodeUniform.type;
  28899. }
  28900. }
  28901. /**
  28902. * A special form of Vector3 uniform binding type.
  28903. * It's value is managed by a node object.
  28904. *
  28905. * @private
  28906. * @augments Vector3Uniform
  28907. */
  28908. class Vector3NodeUniform extends Vector3Uniform {
  28909. /**
  28910. * Constructs a new node-based Vector3 uniform.
  28911. *
  28912. * @param {NodeUniform} nodeUniform - The node uniform.
  28913. */
  28914. constructor( nodeUniform ) {
  28915. super( nodeUniform.name, nodeUniform.value );
  28916. /**
  28917. * The node uniform.
  28918. *
  28919. * @type {NodeUniform}
  28920. */
  28921. this.nodeUniform = nodeUniform;
  28922. }
  28923. /**
  28924. * Overwritten to return the value of the node uniform.
  28925. *
  28926. * @return {Vector3} The value.
  28927. */
  28928. getValue() {
  28929. return this.nodeUniform.value;
  28930. }
  28931. /**
  28932. * Returns the node uniform data type.
  28933. *
  28934. * @return {String} The data type.
  28935. */
  28936. getType() {
  28937. return this.nodeUniform.type;
  28938. }
  28939. }
  28940. /**
  28941. * A special form of Vector4 uniform binding type.
  28942. * It's value is managed by a node object.
  28943. *
  28944. * @private
  28945. * @augments Vector4Uniform
  28946. */
  28947. class Vector4NodeUniform extends Vector4Uniform {
  28948. /**
  28949. * Constructs a new node-based Vector4 uniform.
  28950. *
  28951. * @param {NodeUniform} nodeUniform - The node uniform.
  28952. */
  28953. constructor( nodeUniform ) {
  28954. super( nodeUniform.name, nodeUniform.value );
  28955. /**
  28956. * The node uniform.
  28957. *
  28958. * @type {NodeUniform}
  28959. */
  28960. this.nodeUniform = nodeUniform;
  28961. }
  28962. /**
  28963. * Overwritten to return the value of the node uniform.
  28964. *
  28965. * @return {Vector4} The value.
  28966. */
  28967. getValue() {
  28968. return this.nodeUniform.value;
  28969. }
  28970. /**
  28971. * Returns the node uniform data type.
  28972. *
  28973. * @return {String} The data type.
  28974. */
  28975. getType() {
  28976. return this.nodeUniform.type;
  28977. }
  28978. }
  28979. /**
  28980. * A special form of Color uniform binding type.
  28981. * It's value is managed by a node object.
  28982. *
  28983. * @private
  28984. * @augments ColorUniform
  28985. */
  28986. class ColorNodeUniform extends ColorUniform {
  28987. /**
  28988. * Constructs a new node-based Color uniform.
  28989. *
  28990. * @param {NodeUniform} nodeUniform - The node uniform.
  28991. */
  28992. constructor( nodeUniform ) {
  28993. super( nodeUniform.name, nodeUniform.value );
  28994. /**
  28995. * The node uniform.
  28996. *
  28997. * @type {NodeUniform}
  28998. */
  28999. this.nodeUniform = nodeUniform;
  29000. }
  29001. /**
  29002. * Overwritten to return the value of the node uniform.
  29003. *
  29004. * @return {Color} The value.
  29005. */
  29006. getValue() {
  29007. return this.nodeUniform.value;
  29008. }
  29009. /**
  29010. * Returns the node uniform data type.
  29011. *
  29012. * @return {String} The data type.
  29013. */
  29014. getType() {
  29015. return this.nodeUniform.type;
  29016. }
  29017. }
  29018. /**
  29019. * A special form of Matrix2 uniform binding type.
  29020. * It's value is managed by a node object.
  29021. *
  29022. * @private
  29023. * @augments Matrix2Uniform
  29024. */
  29025. class Matrix2NodeUniform extends Matrix2Uniform {
  29026. /**
  29027. * Constructs a new node-based Matrix2 uniform.
  29028. *
  29029. * @param {NodeUniform} nodeUniform - The node uniform.
  29030. */
  29031. constructor( nodeUniform ) {
  29032. super( nodeUniform.name, nodeUniform.value );
  29033. /**
  29034. * The node uniform.
  29035. *
  29036. * @type {NodeUniform}
  29037. */
  29038. this.nodeUniform = nodeUniform;
  29039. }
  29040. /**
  29041. * Overwritten to return the value of the node uniform.
  29042. *
  29043. * @return {Matrix2} The value.
  29044. */
  29045. getValue() {
  29046. return this.nodeUniform.value;
  29047. }
  29048. /**
  29049. * Returns the node uniform data type.
  29050. *
  29051. * @return {String} The data type.
  29052. */
  29053. getType() {
  29054. return this.nodeUniform.type;
  29055. }
  29056. }
  29057. /**
  29058. * A special form of Matrix3 uniform binding type.
  29059. * It's value is managed by a node object.
  29060. *
  29061. * @private
  29062. * @augments Matrix3Uniform
  29063. */
  29064. class Matrix3NodeUniform extends Matrix3Uniform {
  29065. /**
  29066. * Constructs a new node-based Matrix3 uniform.
  29067. *
  29068. * @param {NodeUniform} nodeUniform - The node uniform.
  29069. */
  29070. constructor( nodeUniform ) {
  29071. super( nodeUniform.name, nodeUniform.value );
  29072. /**
  29073. * The node uniform.
  29074. *
  29075. * @type {NodeUniform}
  29076. */
  29077. this.nodeUniform = nodeUniform;
  29078. }
  29079. /**
  29080. * Overwritten to return the value of the node uniform.
  29081. *
  29082. * @return {Matrix3} The value.
  29083. */
  29084. getValue() {
  29085. return this.nodeUniform.value;
  29086. }
  29087. /**
  29088. * Returns the node uniform data type.
  29089. *
  29090. * @return {String} The data type.
  29091. */
  29092. getType() {
  29093. return this.nodeUniform.type;
  29094. }
  29095. }
  29096. /**
  29097. * A special form of Matrix4 uniform binding type.
  29098. * It's value is managed by a node object.
  29099. *
  29100. * @private
  29101. * @augments Matrix4Uniform
  29102. */
  29103. class Matrix4NodeUniform extends Matrix4Uniform {
  29104. /**
  29105. * Constructs a new node-based Matrix4 uniform.
  29106. *
  29107. * @param {NodeUniform} nodeUniform - The node uniform.
  29108. */
  29109. constructor( nodeUniform ) {
  29110. super( nodeUniform.name, nodeUniform.value );
  29111. /**
  29112. * The node uniform.
  29113. *
  29114. * @type {NodeUniform}
  29115. */
  29116. this.nodeUniform = nodeUniform;
  29117. }
  29118. /**
  29119. * Overwritten to return the value of the node uniform.
  29120. *
  29121. * @return {Matrix4} The value.
  29122. */
  29123. getValue() {
  29124. return this.nodeUniform.value;
  29125. }
  29126. /**
  29127. * Returns the node uniform data type.
  29128. *
  29129. * @return {String} The data type.
  29130. */
  29131. getType() {
  29132. return this.nodeUniform.type;
  29133. }
  29134. }
  29135. const LOD_MIN = 4;
  29136. // The standard deviations (radians) associated with the extra mips. These are
  29137. // chosen to approximate a Trowbridge-Reitz distribution function times the
  29138. // geometric shadowing function. These sigma values squared must match the
  29139. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  29140. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  29141. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  29142. // samples and exit early, but not recompile the shader.
  29143. const MAX_SAMPLES = 20;
  29144. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  29145. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  29146. const _clearColor = /*@__PURE__*/ new Color();
  29147. let _oldTarget = null;
  29148. let _oldActiveCubeFace = 0;
  29149. let _oldActiveMipmapLevel = 0;
  29150. // Golden Ratio
  29151. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  29152. const INV_PHI = 1 / PHI;
  29153. // Vertices of a dodecahedron (except the opposites, which represent the
  29154. // same axis), used as axis directions evenly spread on a sphere.
  29155. const _axisDirections = [
  29156. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  29157. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  29158. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  29159. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  29160. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  29161. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  29162. /*@__PURE__*/ new Vector3( -1, 1, -1 ),
  29163. /*@__PURE__*/ new Vector3( 1, 1, -1 ),
  29164. /*@__PURE__*/ new Vector3( -1, 1, 1 ),
  29165. /*@__PURE__*/ new Vector3( 1, 1, 1 )
  29166. ];
  29167. // maps blur materials to their uniforms dictionary
  29168. const _uniformsMap = new WeakMap();
  29169. // WebGPU Face indices
  29170. const _faceLib = [
  29171. 3, 1, 5,
  29172. 0, 4, 2
  29173. ];
  29174. const _direction = /*@__PURE__*/ getDirection( uv(), attribute( 'faceIndex' ) ).normalize();
  29175. const _outputDirection = /*@__PURE__*/ vec3( _direction.x, _direction.y, _direction.z );
  29176. /**
  29177. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  29178. * (PMREM) from a cubeMap environment texture. This allows different levels of
  29179. * blur to be quickly accessed based on material roughness. It is packed into a
  29180. * special CubeUV format that allows us to perform custom interpolation so that
  29181. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  29182. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  29183. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  29184. * higher roughness levels. In this way we maintain resolution to smoothly
  29185. * interpolate diffuse lighting while limiting sampling computation.
  29186. *
  29187. * Paper: Fast, Accurate Image-Based Lighting
  29188. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  29189. */
  29190. class PMREMGenerator {
  29191. constructor( renderer ) {
  29192. this._renderer = renderer;
  29193. this._pingPongRenderTarget = null;
  29194. this._lodMax = 0;
  29195. this._cubeSize = 0;
  29196. this._lodPlanes = [];
  29197. this._sizeLods = [];
  29198. this._sigmas = [];
  29199. this._lodMeshes = [];
  29200. this._blurMaterial = null;
  29201. this._cubemapMaterial = null;
  29202. this._equirectMaterial = null;
  29203. this._backgroundBox = null;
  29204. }
  29205. get _hasInitialized() {
  29206. return this._renderer.hasInitialized();
  29207. }
  29208. /**
  29209. * Generates a PMREM from a supplied Scene, which can be faster than using an
  29210. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  29211. * in radians to be applied to the scene before PMREM generation. Optional near
  29212. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  29213. * is placed at the origin).
  29214. *
  29215. * @param {Scene} scene - The scene to be captured.
  29216. * @param {Number} [sigma=0] - The blur radius in radians.
  29217. * @param {Number} [near=0.1] - The near plane distance.
  29218. * @param {Number} [far=100] - The far plane distance.
  29219. * @param {RenderTarget?} [renderTarget=null] - The render target to use.
  29220. * @return {RenderTarget} The resulting PMREM.
  29221. * @see fromSceneAsync
  29222. */
  29223. fromScene( scene, sigma = 0, near = 0.1, far = 100, renderTarget = null ) {
  29224. this._setSize( 256 );
  29225. if ( this._hasInitialized === false ) {
  29226. console.warn( 'THREE.PMREMGenerator: .fromScene() called before the backend is initialized. Try using .fromSceneAsync() instead.' );
  29227. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  29228. this.fromSceneAsync( scene, sigma, near, far, cubeUVRenderTarget );
  29229. return cubeUVRenderTarget;
  29230. }
  29231. _oldTarget = this._renderer.getRenderTarget();
  29232. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  29233. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  29234. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  29235. cubeUVRenderTarget.depthBuffer = true;
  29236. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  29237. if ( sigma > 0 ) {
  29238. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  29239. }
  29240. this._applyPMREM( cubeUVRenderTarget );
  29241. this._cleanup( cubeUVRenderTarget );
  29242. return cubeUVRenderTarget;
  29243. }
  29244. /**
  29245. * Generates a PMREM from a supplied Scene, which can be faster than using an
  29246. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  29247. * in radians to be applied to the scene before PMREM generation. Optional near
  29248. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  29249. * is placed at the origin).
  29250. *
  29251. * @param {Scene} scene - The scene to be captured.
  29252. * @param {Number} [sigma=0] - The blur radius in radians.
  29253. * @param {Number} [near=0.1] - The near plane distance.
  29254. * @param {Number} [far=100] - The far plane distance.
  29255. * @param {RenderTarget?} [renderTarget=null] - The render target to use.
  29256. * @return {Promise<RenderTarget>} The resulting PMREM.
  29257. * @see fromScene
  29258. */
  29259. async fromSceneAsync( scene, sigma = 0, near = 0.1, far = 100, renderTarget = null ) {
  29260. if ( this._hasInitialized === false ) await this._renderer.init();
  29261. return this.fromScene( scene, sigma, near, far, renderTarget );
  29262. }
  29263. /**
  29264. * Generates a PMREM from an equirectangular texture, which can be either LDR
  29265. * or HDR. The ideal input image size is 1k (1024 x 512),
  29266. * as this matches best with the 256 x 256 cubemap output.
  29267. *
  29268. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  29269. * @param {RenderTarget?} [renderTarget=null] - The render target to use.
  29270. * @return {RenderTarget} The resulting PMREM.
  29271. * @see fromEquirectangularAsync
  29272. */
  29273. fromEquirectangular( equirectangular, renderTarget = null ) {
  29274. if ( this._hasInitialized === false ) {
  29275. console.warn( 'THREE.PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using .fromEquirectangularAsync() instead.' );
  29276. this._setSizeFromTexture( equirectangular );
  29277. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  29278. this.fromEquirectangularAsync( equirectangular, cubeUVRenderTarget );
  29279. return cubeUVRenderTarget;
  29280. }
  29281. return this._fromTexture( equirectangular, renderTarget );
  29282. }
  29283. /**
  29284. * Generates a PMREM from an equirectangular texture, which can be either LDR
  29285. * or HDR. The ideal input image size is 1k (1024 x 512),
  29286. * as this matches best with the 256 x 256 cubemap output.
  29287. *
  29288. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  29289. * @param {RenderTarget?} [renderTarget=null] - The render target to use.
  29290. * @return {Promise<RenderTarget>} The resulting PMREM.
  29291. * @see fromEquirectangular
  29292. */
  29293. async fromEquirectangularAsync( equirectangular, renderTarget = null ) {
  29294. if ( this._hasInitialized === false ) await this._renderer.init();
  29295. return this._fromTexture( equirectangular, renderTarget );
  29296. }
  29297. /**
  29298. * Generates a PMREM from an cubemap texture, which can be either LDR
  29299. * or HDR. The ideal input cube size is 256 x 256,
  29300. * as this matches best with the 256 x 256 cubemap output.
  29301. *
  29302. * @param {Texture} cubemap - The cubemap texture to be converted.
  29303. * @param {RenderTarget?} [renderTarget=null] - The render target to use.
  29304. * @return {RenderTarget} The resulting PMREM.
  29305. * @see fromCubemapAsync
  29306. */
  29307. fromCubemap( cubemap, renderTarget = null ) {
  29308. if ( this._hasInitialized === false ) {
  29309. console.warn( 'THREE.PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead.' );
  29310. this._setSizeFromTexture( cubemap );
  29311. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  29312. this.fromCubemapAsync( cubemap, renderTarget );
  29313. return cubeUVRenderTarget;
  29314. }
  29315. return this._fromTexture( cubemap, renderTarget );
  29316. }
  29317. /**
  29318. * Generates a PMREM from an cubemap texture, which can be either LDR
  29319. * or HDR. The ideal input cube size is 256 x 256,
  29320. * with the 256 x 256 cubemap output.
  29321. *
  29322. * @param {Texture} cubemap - The cubemap texture to be converted.
  29323. * @param {RenderTarget?} [renderTarget=null] - The render target to use.
  29324. * @return {Promise<RenderTarget>} The resulting PMREM.
  29325. * @see fromCubemap
  29326. */
  29327. async fromCubemapAsync( cubemap, renderTarget = null ) {
  29328. if ( this._hasInitialized === false ) await this._renderer.init();
  29329. return this._fromTexture( cubemap, renderTarget );
  29330. }
  29331. /**
  29332. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  29333. * your texture's network fetch for increased concurrency.
  29334. *
  29335. * @returns {Promise}
  29336. */
  29337. async compileCubemapShader() {
  29338. if ( this._cubemapMaterial === null ) {
  29339. this._cubemapMaterial = _getCubemapMaterial();
  29340. await this._compileMaterial( this._cubemapMaterial );
  29341. }
  29342. }
  29343. /**
  29344. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  29345. * your texture's network fetch for increased concurrency.
  29346. *
  29347. * @returns {Promise}
  29348. */
  29349. async compileEquirectangularShader() {
  29350. if ( this._equirectMaterial === null ) {
  29351. this._equirectMaterial = _getEquirectMaterial();
  29352. await this._compileMaterial( this._equirectMaterial );
  29353. }
  29354. }
  29355. /**
  29356. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  29357. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  29358. * one of them will cause any others to also become unusable.
  29359. */
  29360. dispose() {
  29361. this._dispose();
  29362. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  29363. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  29364. if ( this._backgroundBox !== null ) {
  29365. this._backgroundBox.geometry.dispose();
  29366. this._backgroundBox.material.dispose();
  29367. }
  29368. }
  29369. // private interface
  29370. _setSizeFromTexture( texture ) {
  29371. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  29372. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  29373. } else { // Equirectangular
  29374. this._setSize( texture.image.width / 4 );
  29375. }
  29376. }
  29377. _setSize( cubeSize ) {
  29378. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  29379. this._cubeSize = Math.pow( 2, this._lodMax );
  29380. }
  29381. _dispose() {
  29382. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  29383. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  29384. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  29385. this._lodPlanes[ i ].dispose();
  29386. }
  29387. }
  29388. _cleanup( outputTarget ) {
  29389. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  29390. outputTarget.scissorTest = false;
  29391. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  29392. }
  29393. _fromTexture( texture, renderTarget ) {
  29394. this._setSizeFromTexture( texture );
  29395. _oldTarget = this._renderer.getRenderTarget();
  29396. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  29397. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  29398. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  29399. this._textureToCubeUV( texture, cubeUVRenderTarget );
  29400. this._applyPMREM( cubeUVRenderTarget );
  29401. this._cleanup( cubeUVRenderTarget );
  29402. return cubeUVRenderTarget;
  29403. }
  29404. _allocateTargets() {
  29405. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  29406. const height = 4 * this._cubeSize;
  29407. const params = {
  29408. magFilter: LinearFilter,
  29409. minFilter: LinearFilter,
  29410. generateMipmaps: false,
  29411. type: HalfFloatType,
  29412. format: RGBAFormat,
  29413. colorSpace: LinearSRGBColorSpace,
  29414. //depthBuffer: false
  29415. };
  29416. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  29417. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  29418. if ( this._pingPongRenderTarget !== null ) {
  29419. this._dispose();
  29420. }
  29421. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  29422. const { _lodMax } = this;
  29423. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas, lodMeshes: this._lodMeshes } = _createPlanes( _lodMax ) );
  29424. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  29425. }
  29426. return cubeUVRenderTarget;
  29427. }
  29428. async _compileMaterial( material ) {
  29429. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  29430. await this._renderer.compile( tmpMesh, _flatCamera );
  29431. }
  29432. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  29433. const cubeCamera = _cubeCamera;
  29434. cubeCamera.near = near;
  29435. cubeCamera.far = far;
  29436. // px, py, pz, nx, ny, nz
  29437. const upSign = [ 1, 1, 1, 1, -1, 1 ];
  29438. const forwardSign = [ 1, -1, 1, -1, 1, -1 ];
  29439. const renderer = this._renderer;
  29440. const originalAutoClear = renderer.autoClear;
  29441. renderer.getClearColor( _clearColor );
  29442. renderer.autoClear = false;
  29443. let backgroundBox = this._backgroundBox;
  29444. if ( backgroundBox === null ) {
  29445. const backgroundMaterial = new MeshBasicMaterial( {
  29446. name: 'PMREM.Background',
  29447. side: BackSide,
  29448. depthWrite: false,
  29449. depthTest: false
  29450. } );
  29451. backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  29452. }
  29453. let useSolidColor = false;
  29454. const background = scene.background;
  29455. if ( background ) {
  29456. if ( background.isColor ) {
  29457. backgroundBox.material.color.copy( background );
  29458. scene.background = null;
  29459. useSolidColor = true;
  29460. }
  29461. } else {
  29462. backgroundBox.material.color.copy( _clearColor );
  29463. useSolidColor = true;
  29464. }
  29465. renderer.setRenderTarget( cubeUVRenderTarget );
  29466. renderer.clear();
  29467. if ( useSolidColor ) {
  29468. renderer.render( backgroundBox, cubeCamera );
  29469. }
  29470. for ( let i = 0; i < 6; i ++ ) {
  29471. const col = i % 3;
  29472. if ( col === 0 ) {
  29473. cubeCamera.up.set( 0, upSign[ i ], 0 );
  29474. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  29475. } else if ( col === 1 ) {
  29476. cubeCamera.up.set( 0, 0, upSign[ i ] );
  29477. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  29478. } else {
  29479. cubeCamera.up.set( 0, upSign[ i ], 0 );
  29480. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  29481. }
  29482. const size = this._cubeSize;
  29483. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  29484. renderer.render( scene, cubeCamera );
  29485. }
  29486. renderer.autoClear = originalAutoClear;
  29487. scene.background = background;
  29488. }
  29489. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  29490. const renderer = this._renderer;
  29491. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  29492. if ( isCubeTexture ) {
  29493. if ( this._cubemapMaterial === null ) {
  29494. this._cubemapMaterial = _getCubemapMaterial( texture );
  29495. }
  29496. } else {
  29497. if ( this._equirectMaterial === null ) {
  29498. this._equirectMaterial = _getEquirectMaterial( texture );
  29499. }
  29500. }
  29501. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  29502. material.fragmentNode.value = texture;
  29503. const mesh = this._lodMeshes[ 0 ];
  29504. mesh.material = material;
  29505. const size = this._cubeSize;
  29506. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  29507. renderer.setRenderTarget( cubeUVRenderTarget );
  29508. renderer.render( mesh, _flatCamera );
  29509. }
  29510. _applyPMREM( cubeUVRenderTarget ) {
  29511. const renderer = this._renderer;
  29512. const autoClear = renderer.autoClear;
  29513. renderer.autoClear = false;
  29514. const n = this._lodPlanes.length;
  29515. for ( let i = 1; i < n; i ++ ) {
  29516. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  29517. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  29518. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  29519. }
  29520. renderer.autoClear = autoClear;
  29521. }
  29522. /**
  29523. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  29524. * vertically and horizontally, but this breaks down on a cube. Here we apply
  29525. * the blur latitudinally (around the poles), and then longitudinally (towards
  29526. * the poles) to approximate the orthogonally-separable blur. It is least
  29527. * accurate at the poles, but still does a decent job.
  29528. *
  29529. * @param {RenderTarget} cubeUVRenderTarget - The cubemap render target.
  29530. * @param {Number} lodIn - The input level-of-detail.
  29531. * @param {Number} lodOut - The output level-of-detail.
  29532. * @param {Number} sigma - The blur radius in radians.
  29533. * @param {Vector3} [poleAxis] - The pole axis.
  29534. */
  29535. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  29536. const pingPongRenderTarget = this._pingPongRenderTarget;
  29537. this._halfBlur(
  29538. cubeUVRenderTarget,
  29539. pingPongRenderTarget,
  29540. lodIn,
  29541. lodOut,
  29542. sigma,
  29543. 'latitudinal',
  29544. poleAxis );
  29545. this._halfBlur(
  29546. pingPongRenderTarget,
  29547. cubeUVRenderTarget,
  29548. lodOut,
  29549. lodOut,
  29550. sigma,
  29551. 'longitudinal',
  29552. poleAxis );
  29553. }
  29554. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  29555. const renderer = this._renderer;
  29556. const blurMaterial = this._blurMaterial;
  29557. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  29558. console.error( 'blur direction must be either latitudinal or longitudinal!' );
  29559. }
  29560. // Number of standard deviations at which to cut off the discrete approximation.
  29561. const STANDARD_DEVIATIONS = 3;
  29562. const blurMesh = this._lodMeshes[ lodOut ];
  29563. blurMesh.material = blurMaterial;
  29564. const blurUniforms = _uniformsMap.get( blurMaterial );
  29565. const pixels = this._sizeLods[ lodIn ] - 1;
  29566. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  29567. const sigmaPixels = sigmaRadians / radiansPerPixel;
  29568. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  29569. if ( samples > MAX_SAMPLES ) {
  29570. console.warn( `sigmaRadians, ${
  29571. sigmaRadians}, is too large and will clip, as it requested ${
  29572. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  29573. }
  29574. const weights = [];
  29575. let sum = 0;
  29576. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  29577. const x = i / sigmaPixels;
  29578. const weight = Math.exp( - x * x / 2 );
  29579. weights.push( weight );
  29580. if ( i === 0 ) {
  29581. sum += weight;
  29582. } else if ( i < samples ) {
  29583. sum += 2 * weight;
  29584. }
  29585. }
  29586. for ( let i = 0; i < weights.length; i ++ ) {
  29587. weights[ i ] = weights[ i ] / sum;
  29588. }
  29589. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  29590. blurUniforms.envMap.value = targetIn.texture;
  29591. blurUniforms.samples.value = samples;
  29592. blurUniforms.weights.array = weights;
  29593. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  29594. if ( poleAxis ) {
  29595. blurUniforms.poleAxis.value = poleAxis;
  29596. }
  29597. const { _lodMax } = this;
  29598. blurUniforms.dTheta.value = radiansPerPixel;
  29599. blurUniforms.mipInt.value = _lodMax - lodIn;
  29600. const outputSize = this._sizeLods[ lodOut ];
  29601. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  29602. const y = 4 * ( this._cubeSize - outputSize );
  29603. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  29604. renderer.setRenderTarget( targetOut );
  29605. renderer.render( blurMesh, _flatCamera );
  29606. }
  29607. }
  29608. function _createPlanes( lodMax ) {
  29609. const lodPlanes = [];
  29610. const sizeLods = [];
  29611. const sigmas = [];
  29612. const lodMeshes = [];
  29613. let lod = lodMax;
  29614. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  29615. for ( let i = 0; i < totalLods; i ++ ) {
  29616. const sizeLod = Math.pow( 2, lod );
  29617. sizeLods.push( sizeLod );
  29618. let sigma = 1.0 / sizeLod;
  29619. if ( i > lodMax - LOD_MIN ) {
  29620. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  29621. } else if ( i === 0 ) {
  29622. sigma = 0;
  29623. }
  29624. sigmas.push( sigma );
  29625. const texelSize = 1.0 / ( sizeLod - 2 );
  29626. const min = - texelSize;
  29627. const max = 1 + texelSize;
  29628. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  29629. const cubeFaces = 6;
  29630. const vertices = 6;
  29631. const positionSize = 3;
  29632. const uvSize = 2;
  29633. const faceIndexSize = 1;
  29634. const position = new Float32Array( positionSize * vertices * cubeFaces );
  29635. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  29636. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  29637. for ( let face = 0; face < cubeFaces; face ++ ) {
  29638. const x = ( face % 3 ) * 2 / 3 - 1;
  29639. const y = face > 2 ? 0 : -1;
  29640. const coordinates = [
  29641. x, y, 0,
  29642. x + 2 / 3, y, 0,
  29643. x + 2 / 3, y + 1, 0,
  29644. x, y, 0,
  29645. x + 2 / 3, y + 1, 0,
  29646. x, y + 1, 0
  29647. ];
  29648. const faceIdx = _faceLib[ face ];
  29649. position.set( coordinates, positionSize * vertices * faceIdx );
  29650. uv.set( uv1, uvSize * vertices * faceIdx );
  29651. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  29652. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  29653. }
  29654. const planes = new BufferGeometry();
  29655. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  29656. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  29657. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  29658. lodPlanes.push( planes );
  29659. lodMeshes.push( new Mesh( planes, null ) );
  29660. if ( lod > LOD_MIN ) {
  29661. lod --;
  29662. }
  29663. }
  29664. return { lodPlanes, sizeLods, sigmas, lodMeshes };
  29665. }
  29666. function _createRenderTarget( width, height, params ) {
  29667. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  29668. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  29669. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  29670. cubeUVRenderTarget.texture.isPMREMTexture = true;
  29671. cubeUVRenderTarget.scissorTest = true;
  29672. return cubeUVRenderTarget;
  29673. }
  29674. function _setViewport( target, x, y, width, height ) {
  29675. target.viewport.set( x, y, width, height );
  29676. target.scissor.set( x, y, width, height );
  29677. }
  29678. function _getMaterial( type ) {
  29679. const material = new NodeMaterial();
  29680. material.depthTest = false;
  29681. material.depthWrite = false;
  29682. material.blending = NoBlending;
  29683. material.name = `PMREM_${ type }`;
  29684. return material;
  29685. }
  29686. function _getBlurShader( lodMax, width, height ) {
  29687. const weights = uniformArray( new Array( MAX_SAMPLES ).fill( 0 ) );
  29688. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  29689. const dTheta = uniform( 0 );
  29690. const n = float( MAX_SAMPLES );
  29691. const latitudinal = uniform( 0 ); // false, bool
  29692. const samples = uniform( 1 ); // int
  29693. const envMap = texture( null );
  29694. const mipInt = uniform( 0 ); // int
  29695. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  29696. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  29697. const CUBEUV_MAX_MIP = float( lodMax );
  29698. const materialUniforms = {
  29699. n,
  29700. latitudinal,
  29701. weights,
  29702. poleAxis,
  29703. outputDirection: _outputDirection,
  29704. dTheta,
  29705. samples,
  29706. envMap,
  29707. mipInt,
  29708. CUBEUV_TEXEL_WIDTH,
  29709. CUBEUV_TEXEL_HEIGHT,
  29710. CUBEUV_MAX_MIP
  29711. };
  29712. const material = _getMaterial( 'blur' );
  29713. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  29714. _uniformsMap.set( material, materialUniforms );
  29715. return material;
  29716. }
  29717. function _getCubemapMaterial( envTexture ) {
  29718. const material = _getMaterial( 'cubemap' );
  29719. material.fragmentNode = cubeTexture( envTexture, _outputDirection );
  29720. return material;
  29721. }
  29722. function _getEquirectMaterial( envTexture ) {
  29723. const material = _getMaterial( 'equirect' );
  29724. material.fragmentNode = texture( envTexture, equirectUV( _outputDirection ), 0 );
  29725. return material;
  29726. }
  29727. const rendererCache = new WeakMap();
  29728. const typeFromArray = new Map( [
  29729. [ Int8Array, 'int' ],
  29730. [ Int16Array, 'int' ],
  29731. [ Int32Array, 'int' ],
  29732. [ Uint8Array, 'uint' ],
  29733. [ Uint16Array, 'uint' ],
  29734. [ Uint32Array, 'uint' ],
  29735. [ Float32Array, 'float' ]
  29736. ] );
  29737. const toFloat = ( value ) => {
  29738. if ( /e/g.test( value ) ) {
  29739. return String( value ).replace( /\+/g, '' );
  29740. } else {
  29741. value = Number( value );
  29742. return value + ( value % 1 ? '' : '.0' );
  29743. }
  29744. };
  29745. /**
  29746. * Base class for builders which generate a shader program based
  29747. * on a 3D object and its node material definition.
  29748. */
  29749. class NodeBuilder {
  29750. /**
  29751. * Constructs a new node builder.
  29752. *
  29753. * @param {Object3D} object - The 3D object.
  29754. * @param {Renderer} renderer - The current renderer.
  29755. * @param {NodeParser} parser - A reference to a node parser.
  29756. */
  29757. constructor( object, renderer, parser ) {
  29758. /**
  29759. * The 3D object.
  29760. *
  29761. * @type {Object3D}
  29762. */
  29763. this.object = object;
  29764. /**
  29765. * The material of the 3D object.
  29766. *
  29767. * @type {Material?}
  29768. */
  29769. this.material = ( object && object.material ) || null;
  29770. /**
  29771. * The geometry of the 3D object.
  29772. *
  29773. * @type {BufferGeometry?}
  29774. */
  29775. this.geometry = ( object && object.geometry ) || null;
  29776. /**
  29777. * The current renderer.
  29778. *
  29779. * @type {Renderer}
  29780. */
  29781. this.renderer = renderer;
  29782. /**
  29783. * A reference to a node parser.
  29784. *
  29785. * @type {NodeParser}
  29786. */
  29787. this.parser = parser;
  29788. /**
  29789. * The scene the 3D object belongs to.
  29790. *
  29791. * @type {Scene?}
  29792. * @default null
  29793. */
  29794. this.scene = null;
  29795. /**
  29796. * The camera the 3D object is rendered with.
  29797. *
  29798. * @type {Camera?}
  29799. * @default null
  29800. */
  29801. this.camera = null;
  29802. /**
  29803. * A list of all nodes the builder is processing
  29804. * for this 3D object.
  29805. *
  29806. * @type {Array<Node>}
  29807. */
  29808. this.nodes = [];
  29809. /**
  29810. * A list of all sequential nodes.
  29811. *
  29812. * @type {Array<Node>}
  29813. */
  29814. this.sequentialNodes = [];
  29815. /**
  29816. * A list of all nodes which {@link Node#update} method should be executed.
  29817. *
  29818. * @type {Array<Node>}
  29819. */
  29820. this.updateNodes = [];
  29821. /**
  29822. * A list of all nodes which {@link Node#updateBefore} method should be executed.
  29823. *
  29824. * @type {Array<Node>}
  29825. */
  29826. this.updateBeforeNodes = [];
  29827. /**
  29828. * A list of all nodes which {@link Node#updateAfter} method should be executed.
  29829. *
  29830. * @type {Array<Node>}
  29831. */
  29832. this.updateAfterNodes = [];
  29833. /**
  29834. * A dictionary that assigns each node to a unique hash.
  29835. *
  29836. * @type {Object<Number,Node>}
  29837. */
  29838. this.hashNodes = {};
  29839. /**
  29840. * A reference to a node material observer.
  29841. *
  29842. * @type {NodeMaterialObserver?}
  29843. * @default null
  29844. */
  29845. this.observer = null;
  29846. /**
  29847. * A reference to the current lights node.
  29848. *
  29849. * @type {LightsNode?}
  29850. * @default null
  29851. */
  29852. this.lightsNode = null;
  29853. /**
  29854. * A reference to the current environment node.
  29855. *
  29856. * @type {Node?}
  29857. * @default null
  29858. */
  29859. this.environmentNode = null;
  29860. /**
  29861. * A reference to the current fog node.
  29862. *
  29863. * @type {FogNode?}
  29864. * @default null
  29865. */
  29866. this.fogNode = null;
  29867. /**
  29868. * The current clipping context.
  29869. *
  29870. * @type {ClippingContext?}
  29871. */
  29872. this.clippingContext = null;
  29873. /**
  29874. * The generated vertex shader.
  29875. *
  29876. * @type {String?}
  29877. */
  29878. this.vertexShader = null;
  29879. /**
  29880. * The generated fragment shader.
  29881. *
  29882. * @type {String?}
  29883. */
  29884. this.fragmentShader = null;
  29885. /**
  29886. * The generated compute shader.
  29887. *
  29888. * @type {String?}
  29889. */
  29890. this.computeShader = null;
  29891. /**
  29892. * Nodes used in the primary flow of code generation.
  29893. *
  29894. * @type {Object<String,Array<Node>>}
  29895. */
  29896. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  29897. /**
  29898. * Nodes code from `.flowNodes`.
  29899. *
  29900. * @type {Object<String,String>}
  29901. */
  29902. this.flowCode = { vertex: '', fragment: '', compute: '' };
  29903. /**
  29904. * This dictionary holds the node uniforms of the builder.
  29905. * The uniforms are maintained in an array for each shader stage.
  29906. *
  29907. * @type {Object}
  29908. */
  29909. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  29910. /**
  29911. * This dictionary holds the output structs of the builder.
  29912. * The structs are maintained in an array for each shader stage.
  29913. *
  29914. * @type {Object}
  29915. */
  29916. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  29917. /**
  29918. * This dictionary holds the bindings for each shader stage.
  29919. *
  29920. * @type {Object}
  29921. */
  29922. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  29923. /**
  29924. * This dictionary maintains the binding indices per bind group.
  29925. *
  29926. * @type {Object}
  29927. */
  29928. this.bindingsIndexes = {};
  29929. /**
  29930. * Reference to the array of bind groups.
  29931. *
  29932. * @type {Array<BindGroup>?}
  29933. */
  29934. this.bindGroups = null;
  29935. /**
  29936. * This array holds the node attributes of this builder
  29937. * created via {@link AttributeNode}.
  29938. *
  29939. * @type {Array<NodeAttribute>}
  29940. */
  29941. this.attributes = [];
  29942. /**
  29943. * This array holds the node attributes of this builder
  29944. * created via {@link BufferAttributeNode}.
  29945. *
  29946. * @type {Array<NodeAttribute>}
  29947. */
  29948. this.bufferAttributes = [];
  29949. /**
  29950. * This array holds the node varyings of this builder.
  29951. *
  29952. * @type {Array<NodeVarying>}
  29953. */
  29954. this.varyings = [];
  29955. /**
  29956. * This dictionary holds the (native) node codes of this builder.
  29957. * The codes are maintained in an array for each shader stage.
  29958. *
  29959. * @type {Object<String,Array<NodeCode>>}
  29960. */
  29961. this.codes = {};
  29962. /**
  29963. * This dictionary holds the node variables of this builder.
  29964. * The variables are maintained in an array for each shader stage.
  29965. *
  29966. * @type {Object<String,Array<NodeVar>>}
  29967. */
  29968. this.vars = {};
  29969. /**
  29970. * Current code flow.
  29971. * All code generated in this stack will be stored in `.flow`.
  29972. *
  29973. * @type {{code: String}}
  29974. */
  29975. this.flow = { code: '' };
  29976. /**
  29977. * A chain of nodes.
  29978. * Used to check recursive calls in node-graph.
  29979. *
  29980. * @type {Array<Node>}
  29981. */
  29982. this.chaining = [];
  29983. /**
  29984. * The current stack.
  29985. * This reflects the current process in the code block hierarchy,
  29986. * it is useful to know if the current process is inside a conditional for example.
  29987. *
  29988. * @type {StackNode}
  29989. */
  29990. this.stack = stack();
  29991. /**
  29992. * List of stack nodes.
  29993. * The current stack hierarchy is stored in an array.
  29994. *
  29995. * @type {Array<StackNode>}
  29996. */
  29997. this.stacks = [];
  29998. /**
  29999. * A tab value. Used for shader string generation.
  30000. *
  30001. * @type {String}
  30002. * @default '\t'
  30003. */
  30004. this.tab = '\t';
  30005. /**
  30006. * Reference to the current function node.
  30007. *
  30008. * @type {FunctionNode?}
  30009. * @default null
  30010. */
  30011. this.currentFunctionNode = null;
  30012. /**
  30013. * The builder's context.
  30014. *
  30015. * @type {Object}
  30016. */
  30017. this.context = {
  30018. material: this.material
  30019. };
  30020. /**
  30021. * The builder's cache.
  30022. *
  30023. * @type {NodeCache}
  30024. */
  30025. this.cache = new NodeCache();
  30026. /**
  30027. * Since the {@link NodeBuilder#cache} might be temporarily
  30028. * overwritten by other caches, this member retains the reference
  30029. * to the builder's own cache.
  30030. *
  30031. * @type {NodeCache}
  30032. * @default this.cache
  30033. */
  30034. this.globalCache = this.cache;
  30035. this.flowsData = new WeakMap();
  30036. /**
  30037. * The current shader stage.
  30038. *
  30039. * @type {('vertex'|'fragment'|'compute'|'any')?}
  30040. */
  30041. this.shaderStage = null;
  30042. /**
  30043. * The current build stage.
  30044. *
  30045. * @type {('setup'|'analyze'|'generate')?}
  30046. */
  30047. this.buildStage = null;
  30048. /**
  30049. * Whether comparison in shader code are generated with methods or not.
  30050. *
  30051. * @type {Boolean}
  30052. * @default false
  30053. */
  30054. this.useComparisonMethod = false;
  30055. }
  30056. /**
  30057. * Returns the bind groups of the current renderer.
  30058. *
  30059. * @return {ChainMap} The cache.
  30060. */
  30061. getBindGroupsCache() {
  30062. let bindGroupsCache = rendererCache.get( this.renderer );
  30063. if ( bindGroupsCache === undefined ) {
  30064. bindGroupsCache = new ChainMap();
  30065. rendererCache.set( this.renderer, bindGroupsCache );
  30066. }
  30067. return bindGroupsCache;
  30068. }
  30069. /**
  30070. * Factory method for creating an instance of {@link RenderTarget} with the given
  30071. * dimensions and options.
  30072. *
  30073. * @param {Number} width - The width of the render target.
  30074. * @param {Number} height - The height of the render target.
  30075. * @param {Object} options - The options of the render target.
  30076. * @return {RenderTarget} The render target.
  30077. */
  30078. createRenderTarget( width, height, options ) {
  30079. return new RenderTarget( width, height, options );
  30080. }
  30081. /**
  30082. * Factory method for creating an instance of {@link CubeRenderTarget} with the given
  30083. * dimensions and options.
  30084. *
  30085. * @param {Number} size - The size of the cube render target.
  30086. * @param {Object} options - The options of the cube render target.
  30087. * @return {CubeRenderTarget} The cube render target.
  30088. */
  30089. createCubeRenderTarget( size, options ) {
  30090. return new CubeRenderTarget( size, options );
  30091. }
  30092. /**
  30093. * Factory method for creating an instance of {@link PMREMGenerator}.
  30094. *
  30095. * @return {PMREMGenerator} The PMREM generator.
  30096. */
  30097. createPMREMGenerator() {
  30098. // TODO: Move Materials.js to outside of the Nodes.js in order to remove this function and improve tree-shaking support
  30099. return new PMREMGenerator( this.renderer );
  30100. }
  30101. /**
  30102. * Whether the given node is included in the internal array of nodes or not.
  30103. *
  30104. * @param {Node} node - The node to test.
  30105. * @return {Boolean} Whether the given node is included in the internal array of nodes or not.
  30106. */
  30107. includes( node ) {
  30108. return this.nodes.includes( node );
  30109. }
  30110. /**
  30111. * Returns the output struct name which is required by
  30112. * {@link module:OutputStructNode}.
  30113. *
  30114. * @abstract
  30115. * @return {String} The name of the output struct.
  30116. */
  30117. getOutputStructName() {}
  30118. /**
  30119. * Returns a bind group for the given group name and binding.
  30120. *
  30121. * @private
  30122. * @param {String} groupName - The group name.
  30123. * @param {Array<NodeUniformsGroup>} bindings - List of bindings.
  30124. * @return {BindGroup} The bind group
  30125. */
  30126. _getBindGroup( groupName, bindings ) {
  30127. const bindGroupsCache = this.getBindGroupsCache();
  30128. //
  30129. const bindingsArray = [];
  30130. let sharedGroup = true;
  30131. for ( const binding of bindings ) {
  30132. bindingsArray.push( binding );
  30133. sharedGroup = sharedGroup && binding.groupNode.shared !== true;
  30134. }
  30135. //
  30136. let bindGroup;
  30137. if ( sharedGroup ) {
  30138. bindGroup = bindGroupsCache.get( bindingsArray );
  30139. if ( bindGroup === undefined ) {
  30140. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  30141. bindGroupsCache.set( bindingsArray, bindGroup );
  30142. }
  30143. } else {
  30144. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  30145. }
  30146. return bindGroup;
  30147. }
  30148. /**
  30149. * Returns an array of node uniform groups for the given group name and shader stage.
  30150. *
  30151. * @param {String} groupName - The group name.
  30152. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  30153. * @return {Array<NodeUniformsGroup>} The array of node uniform groups.
  30154. */
  30155. getBindGroupArray( groupName, shaderStage ) {
  30156. const bindings = this.bindings[ shaderStage ];
  30157. let bindGroup = bindings[ groupName ];
  30158. if ( bindGroup === undefined ) {
  30159. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  30160. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  30161. }
  30162. bindings[ groupName ] = bindGroup = [];
  30163. }
  30164. return bindGroup;
  30165. }
  30166. /**
  30167. * Returns a list bindings of all shader stages separated by groups.
  30168. *
  30169. * @return {Array<BindGroup>} The list of bindings.
  30170. */
  30171. getBindings() {
  30172. let bindingsGroups = this.bindGroups;
  30173. if ( bindingsGroups === null ) {
  30174. const groups = {};
  30175. const bindings = this.bindings;
  30176. for ( const shaderStage of shaderStages ) {
  30177. for ( const groupName in bindings[ shaderStage ] ) {
  30178. const uniforms = bindings[ shaderStage ][ groupName ];
  30179. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  30180. groupUniforms.push( ...uniforms );
  30181. }
  30182. }
  30183. bindingsGroups = [];
  30184. for ( const groupName in groups ) {
  30185. const group = groups[ groupName ];
  30186. const bindingsGroup = this._getBindGroup( groupName, group );
  30187. bindingsGroups.push( bindingsGroup );
  30188. }
  30189. this.bindGroups = bindingsGroups;
  30190. }
  30191. return bindingsGroups;
  30192. }
  30193. /**
  30194. * Sorts the bind groups and updates {@link NodeBuilder#bindingsIndexes}.
  30195. */
  30196. sortBindingGroups() {
  30197. const bindingsGroups = this.getBindings();
  30198. bindingsGroups.sort( ( a, b ) => ( a.bindings[ 0 ].groupNode.order - b.bindings[ 0 ].groupNode.order ) );
  30199. for ( let i = 0; i < bindingsGroups.length; i ++ ) {
  30200. const bindingGroup = bindingsGroups[ i ];
  30201. this.bindingsIndexes[ bindingGroup.name ].group = i;
  30202. bindingGroup.index = i;
  30203. }
  30204. }
  30205. /**
  30206. * The builder maintains each node in a hash-based dictionary.
  30207. * This method sets the given node (value) with the given hash (key) into this dictionary.
  30208. *
  30209. * @param {Node} node - The node to add.
  30210. * @param {Number} hash - The hash of the node.
  30211. */
  30212. setHashNode( node, hash ) {
  30213. this.hashNodes[ hash ] = node;
  30214. }
  30215. /**
  30216. * Adds a node to this builder.
  30217. *
  30218. * @param {Node} node - The node to add.
  30219. */
  30220. addNode( node ) {
  30221. if ( this.nodes.includes( node ) === false ) {
  30222. this.nodes.push( node );
  30223. this.setHashNode( node, node.getHash( this ) );
  30224. }
  30225. }
  30226. /**
  30227. * It is used to add Nodes that will be used as FRAME and RENDER events,
  30228. * and need to follow a certain sequence in the calls to work correctly.
  30229. * This function should be called after 'setup()' in the 'build()' process to ensure that the child nodes are processed first.
  30230. *
  30231. * @param {Node} node - The node to add.
  30232. */
  30233. addSequentialNode( node ) {
  30234. if ( this.sequentialNodes.includes( node ) === false ) {
  30235. this.sequentialNodes.push( node );
  30236. }
  30237. }
  30238. /**
  30239. * Checks the update types of nodes
  30240. */
  30241. buildUpdateNodes() {
  30242. for ( const node of this.nodes ) {
  30243. const updateType = node.getUpdateType();
  30244. if ( updateType !== NodeUpdateType.NONE ) {
  30245. this.updateNodes.push( node.getSelf() );
  30246. }
  30247. }
  30248. for ( const node of this.sequentialNodes ) {
  30249. const updateBeforeType = node.getUpdateBeforeType();
  30250. const updateAfterType = node.getUpdateAfterType();
  30251. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  30252. this.updateBeforeNodes.push( node.getSelf() );
  30253. }
  30254. if ( updateAfterType !== NodeUpdateType.NONE ) {
  30255. this.updateAfterNodes.push( node.getSelf() );
  30256. }
  30257. }
  30258. }
  30259. /**
  30260. * A reference the current node which is the
  30261. * last node in the chain of nodes.
  30262. *
  30263. * @type {Node}
  30264. */
  30265. get currentNode() {
  30266. return this.chaining[ this.chaining.length - 1 ];
  30267. }
  30268. /**
  30269. * Whether the given texture is filtered or not.
  30270. *
  30271. * @param {Texture} texture - The texture to check.
  30272. * @return {Boolean} Whether the given texture is filtered or not.
  30273. */
  30274. isFilteredTexture( texture ) {
  30275. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  30276. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  30277. }
  30278. /**
  30279. * Adds the given node to the internal node chain.
  30280. * This is used to check recursive calls in node-graph.
  30281. *
  30282. * @param {Node} node - The node to add.
  30283. */
  30284. addChain( node ) {
  30285. /*
  30286. if ( this.chaining.indexOf( node ) !== - 1 ) {
  30287. console.warn( 'Recursive node: ', node );
  30288. }
  30289. */
  30290. this.chaining.push( node );
  30291. }
  30292. /**
  30293. * Removes the given node from the internal node chain.
  30294. *
  30295. * @param {Node} node - The node to remove.
  30296. */
  30297. removeChain( node ) {
  30298. const lastChain = this.chaining.pop();
  30299. if ( lastChain !== node ) {
  30300. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  30301. }
  30302. }
  30303. /**
  30304. * Returns the native shader method name for a given generic name. E.g.
  30305. * the method name `textureDimensions` matches the WGSL name but must be
  30306. * resolved to `textureSize` in GLSL.
  30307. *
  30308. * @abstract
  30309. * @param {String} method - The method name to resolve.
  30310. * @return {String} The resolved method name.
  30311. */
  30312. getMethod( method ) {
  30313. return method;
  30314. }
  30315. /**
  30316. * Returns a node for the given hash, see {@link NodeBuilder#setHashNode}.
  30317. *
  30318. * @param {Number} hash - The hash of the node.
  30319. * @return {Node} The found node.
  30320. */
  30321. getNodeFromHash( hash ) {
  30322. return this.hashNodes[ hash ];
  30323. }
  30324. /**
  30325. * Adds the Node to a target flow so that it can generate code in the 'generate' process.
  30326. *
  30327. * @param {('vertex'|'fragment'|'compute')} shaderStage - The shader stage.
  30328. * @param {Node} node - The node to add.
  30329. * @return {Node} The node.
  30330. */
  30331. addFlow( shaderStage, node ) {
  30332. this.flowNodes[ shaderStage ].push( node );
  30333. return node;
  30334. }
  30335. /**
  30336. * Sets builder's context.
  30337. *
  30338. * @param {Object} context - The context to set.
  30339. */
  30340. setContext( context ) {
  30341. this.context = context;
  30342. }
  30343. /**
  30344. * Returns the builder's current context.
  30345. *
  30346. * @return {Object} The builder's current context.
  30347. */
  30348. getContext() {
  30349. return this.context;
  30350. }
  30351. /**
  30352. * Gets a context used in shader construction that can be shared across different materials.
  30353. * This is necessary since the renderer cache can reuse shaders generated in one material and use them in another.
  30354. *
  30355. * @return {Object} The builder's current context without material.
  30356. */
  30357. getSharedContext() {
  30358. ({ ...this.context });
  30359. return this.context;
  30360. }
  30361. /**
  30362. * Sets builder's cache.
  30363. *
  30364. * @param {NodeCache} cache - The cache to set.
  30365. */
  30366. setCache( cache ) {
  30367. this.cache = cache;
  30368. }
  30369. /**
  30370. * Returns the builder's current cache.
  30371. *
  30372. * @return {NodeCache} The builder's current cache.
  30373. */
  30374. getCache() {
  30375. return this.cache;
  30376. }
  30377. /**
  30378. * Returns a cache for the given node.
  30379. *
  30380. * @param {Node} node - The node.
  30381. * @param {Boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  30382. * @return {NodeCache} The cache.
  30383. */
  30384. getCacheFromNode( node, parent = true ) {
  30385. const data = this.getDataFromNode( node );
  30386. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  30387. return data.cache;
  30388. }
  30389. /**
  30390. * Whether the requested feature is available or not.
  30391. *
  30392. * @abstract
  30393. * @param {String} name - The requested feature.
  30394. * @return {Boolean} Whether the requested feature is supported or not.
  30395. */
  30396. isAvailable( /*name*/ ) {
  30397. return false;
  30398. }
  30399. /**
  30400. * Returns the vertexIndex input variable as a native shader string.
  30401. *
  30402. * @abstract
  30403. * @return {String} The instanceIndex shader string.
  30404. */
  30405. getVertexIndex() {
  30406. console.warn( 'Abstract function.' );
  30407. }
  30408. /**
  30409. * Returns the instanceIndex input variable as a native shader string.
  30410. *
  30411. * @abstract
  30412. * @return {String} The instanceIndex shader string.
  30413. */
  30414. getInstanceIndex() {
  30415. console.warn( 'Abstract function.' );
  30416. }
  30417. /**
  30418. * Returns the drawIndex input variable as a native shader string.
  30419. * Only relevant for WebGL and its `WEBGL_multi_draw` extension.
  30420. *
  30421. * @abstract
  30422. * @return {String} The drawIndex shader string.
  30423. */
  30424. getDrawIndex() {
  30425. console.warn( 'Abstract function.' );
  30426. }
  30427. /**
  30428. * Returns the frontFacing input variable as a native shader string.
  30429. *
  30430. * @abstract
  30431. * @return {String} The frontFacing shader string.
  30432. */
  30433. getFrontFacing() {
  30434. console.warn( 'Abstract function.' );
  30435. }
  30436. /**
  30437. * Returns the fragCoord input variable as a native shader string.
  30438. *
  30439. * @abstract
  30440. * @return {String} The fragCoord shader string.
  30441. */
  30442. getFragCoord() {
  30443. console.warn( 'Abstract function.' );
  30444. }
  30445. /**
  30446. * Whether to flip texture data along its vertical axis or not. WebGL needs
  30447. * this method evaluate to `true`, WebGPU to `false`.
  30448. *
  30449. * @abstract
  30450. * @return {Boolean} Whether to flip texture data along its vertical axis or not.
  30451. */
  30452. isFlipY() {
  30453. return false;
  30454. }
  30455. /**
  30456. * Calling this method increases the usage count for the given node by one.
  30457. *
  30458. * @param {Node} node - The node to increase the usage count for.
  30459. * @return {Number} The updated usage count.
  30460. */
  30461. increaseUsage( node ) {
  30462. const nodeData = this.getDataFromNode( node );
  30463. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  30464. return nodeData.usageCount;
  30465. }
  30466. /**
  30467. * Generates a texture sample shader string for the given texture data.
  30468. *
  30469. * @abstract
  30470. * @param {Texture} texture - The texture.
  30471. * @param {String} textureProperty - The texture property name.
  30472. * @param {String} uvSnippet - Snippet defining the texture coordinates.
  30473. * @return {String} The generated shader string.
  30474. */
  30475. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  30476. console.warn( 'Abstract function.' );
  30477. }
  30478. /**
  30479. * Generates a texture LOD shader string for the given texture data.
  30480. *
  30481. * @abstract
  30482. * @param {Texture} texture - The texture.
  30483. * @param {String} textureProperty - The texture property name.
  30484. * @param {String} uvSnippet - Snippet defining the texture coordinates.
  30485. * @param {String?} depthSnippet - Snippet defining the 0-based texture array index to sample.
  30486. * @param {String} levelSnippet - Snippet defining the mip level.
  30487. * @return {String} The generated shader string.
  30488. */
  30489. generateTextureLod( /* texture, textureProperty, uvSnippet, depthSnippet, levelSnippet */ ) {
  30490. console.warn( 'Abstract function.' );
  30491. }
  30492. /**
  30493. * Generates the array declaration string.
  30494. *
  30495. * @param {String} type - The type.
  30496. * @param {Number?} [count] - The count.
  30497. * @return {String} The generated value as a shader string.
  30498. */
  30499. generateArrayDeclaration( type, count ) {
  30500. return this.getType( type ) + '[ ' + count + ' ]';
  30501. }
  30502. /**
  30503. * Generates the array shader string for the given type and value.
  30504. *
  30505. * @param {String} type - The type.
  30506. * @param {Number?} [count] - The count.
  30507. * @param {Array<Node>?} [values=null] - The default values.
  30508. * @return {String} The generated value as a shader string.
  30509. */
  30510. generateArray( type, count, values = null ) {
  30511. let snippet = this.generateArrayDeclaration( type, count ) + '( ';
  30512. for ( let i = 0; i < count; i ++ ) {
  30513. const value = values ? values[ i ] : null;
  30514. if ( value !== null ) {
  30515. snippet += value.build( this, type );
  30516. } else {
  30517. snippet += this.generateConst( type );
  30518. }
  30519. if ( i < count - 1 ) snippet += ', ';
  30520. }
  30521. snippet += ' )';
  30522. return snippet;
  30523. }
  30524. /**
  30525. * Generates the shader string for the given type and value.
  30526. *
  30527. * @param {String} type - The type.
  30528. * @param {Any?} [value=null] - The value.
  30529. * @return {String} The generated value as a shader string.
  30530. */
  30531. generateConst( type, value = null ) {
  30532. if ( value === null ) {
  30533. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  30534. else if ( type === 'bool' ) value = false;
  30535. else if ( type === 'color' ) value = new Color();
  30536. else if ( type === 'vec2' ) value = new Vector2();
  30537. else if ( type === 'vec3' ) value = new Vector3();
  30538. else if ( type === 'vec4' ) value = new Vector4();
  30539. }
  30540. if ( type === 'float' ) return toFloat( value );
  30541. if ( type === 'int' ) return `${ Math.round( value ) }`;
  30542. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  30543. if ( type === 'bool' ) return value ? 'true' : 'false';
  30544. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  30545. const typeLength = this.getTypeLength( type );
  30546. const componentType = this.getComponentType( type );
  30547. const generateConst = value => this.generateConst( componentType, value );
  30548. if ( typeLength === 2 ) {
  30549. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  30550. } else if ( typeLength === 3 ) {
  30551. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  30552. } else if ( typeLength === 4 ) {
  30553. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  30554. } else if ( typeLength > 4 && value && ( value.isMatrix3 || value.isMatrix4 ) ) {
  30555. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  30556. } else if ( typeLength > 4 ) {
  30557. return `${ this.getType( type ) }()`;
  30558. }
  30559. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  30560. }
  30561. /**
  30562. * It might be necessary to convert certain data types to different ones
  30563. * so this method can be used to hide the conversion.
  30564. *
  30565. * @param {String} type - The type.
  30566. * @return {String} The updated type.
  30567. */
  30568. getType( type ) {
  30569. if ( type === 'color' ) return 'vec3';
  30570. return type;
  30571. }
  30572. /**
  30573. * Whether the given attribute name is defined in the geometry or not.
  30574. *
  30575. * @param {String} name - The attribute name.
  30576. * @return {Boolean} Whether the given attribute name is defined in the geometry.
  30577. */
  30578. hasGeometryAttribute( name ) {
  30579. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  30580. }
  30581. /**
  30582. * Returns a node attribute for the given name and type.
  30583. *
  30584. * @param {String} name - The attribute's name.
  30585. * @param {String} type - The attribute's type.
  30586. * @return {NodeAttribute} The node attribute.
  30587. */
  30588. getAttribute( name, type ) {
  30589. const attributes = this.attributes;
  30590. // find attribute
  30591. for ( const attribute of attributes ) {
  30592. if ( attribute.name === name ) {
  30593. return attribute;
  30594. }
  30595. }
  30596. // create a new if no exist
  30597. const attribute = new NodeAttribute( name, type );
  30598. attributes.push( attribute );
  30599. return attribute;
  30600. }
  30601. /**
  30602. * Returns for the given node and shader stage the property name for the shader.
  30603. *
  30604. * @param {Node} node - The node.
  30605. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  30606. * @return {String} The property name.
  30607. */
  30608. getPropertyName( node/*, shaderStage*/ ) {
  30609. return node.name;
  30610. }
  30611. /**
  30612. * Whether the given type is a vector type or not.
  30613. *
  30614. * @param {String} type - The type to check.
  30615. * @return {Boolean} Whether the given type is a vector type or not.
  30616. */
  30617. isVector( type ) {
  30618. return /vec\d/.test( type );
  30619. }
  30620. /**
  30621. * Whether the given type is a matrix type or not.
  30622. *
  30623. * @param {String} type - The type to check.
  30624. * @return {Boolean} Whether the given type is a matrix type or not.
  30625. */
  30626. isMatrix( type ) {
  30627. return /mat\d/.test( type );
  30628. }
  30629. /**
  30630. * Whether the given type is a reference type or not.
  30631. *
  30632. * @param {String} type - The type to check.
  30633. * @return {Boolean} Whether the given type is a reference type or not.
  30634. */
  30635. isReference( type ) {
  30636. return type === 'void' || type === 'property' || type === 'sampler' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  30637. }
  30638. /**
  30639. * Checks if the given texture requires a manual conversion to the working color space.
  30640. *
  30641. * @abstract
  30642. * @param {Texture} texture - The texture to check.
  30643. * @return {Boolean} Whether the given texture requires a conversion to working color space or not.
  30644. */
  30645. needsToWorkingColorSpace( /*texture*/ ) {
  30646. return false;
  30647. }
  30648. /**
  30649. * Returns the component type of a given texture.
  30650. *
  30651. * @param {Texture} texture - The texture.
  30652. * @return {String} The component type.
  30653. */
  30654. getComponentTypeFromTexture( texture ) {
  30655. const type = texture.type;
  30656. if ( texture.isDataTexture ) {
  30657. if ( type === IntType ) return 'int';
  30658. if ( type === UnsignedIntType ) return 'uint';
  30659. }
  30660. return 'float';
  30661. }
  30662. /**
  30663. * Returns the element type for a given type.
  30664. *
  30665. * @param {String} type - The type.
  30666. * @return {String} The element type.
  30667. */
  30668. getElementType( type ) {
  30669. if ( type === 'mat2' ) return 'vec2';
  30670. if ( type === 'mat3' ) return 'vec3';
  30671. if ( type === 'mat4' ) return 'vec4';
  30672. return this.getComponentType( type );
  30673. }
  30674. /**
  30675. * Returns the component type for a given type.
  30676. *
  30677. * @param {String} type - The type.
  30678. * @return {String} The component type.
  30679. */
  30680. getComponentType( type ) {
  30681. type = this.getVectorType( type );
  30682. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  30683. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  30684. if ( componentType === null ) return null;
  30685. if ( componentType[ 1 ] === 'b' ) return 'bool';
  30686. if ( componentType[ 1 ] === 'i' ) return 'int';
  30687. if ( componentType[ 1 ] === 'u' ) return 'uint';
  30688. return 'float';
  30689. }
  30690. /**
  30691. * Returns the vector type for a given type.
  30692. *
  30693. * @param {String} type - The type.
  30694. * @return {String} The vector type.
  30695. */
  30696. getVectorType( type ) {
  30697. if ( type === 'color' ) return 'vec3';
  30698. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  30699. return type;
  30700. }
  30701. /**
  30702. * Returns the data type for the given the length and component type.
  30703. *
  30704. * @param {Number} length - The length.
  30705. * @param {String} [componentType='float'] - The component type.
  30706. * @return {String} The type.
  30707. */
  30708. getTypeFromLength( length, componentType = 'float' ) {
  30709. if ( length === 1 ) return componentType;
  30710. let baseType = getTypeFromLength( length );
  30711. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  30712. // fix edge case for mat2x2 being same size as vec4
  30713. if ( /mat2/.test( componentType ) === true ) {
  30714. baseType = baseType.replace( 'vec', 'mat' );
  30715. }
  30716. return prefix + baseType;
  30717. }
  30718. /**
  30719. * Returns the type for a given typed array.
  30720. *
  30721. * @param {TypedArray} array - The typed array.
  30722. * @return {String} The type.
  30723. */
  30724. getTypeFromArray( array ) {
  30725. return typeFromArray.get( array.constructor );
  30726. }
  30727. /**
  30728. * Returns the type for a given buffer attribute.
  30729. *
  30730. * @param {BufferAttribute} attribute - The buffer attribute.
  30731. * @return {String} The type.
  30732. */
  30733. getTypeFromAttribute( attribute ) {
  30734. let dataAttribute = attribute;
  30735. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  30736. const array = dataAttribute.array;
  30737. const itemSize = attribute.itemSize;
  30738. const normalized = attribute.normalized;
  30739. let arrayType;
  30740. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  30741. arrayType = this.getTypeFromArray( array );
  30742. }
  30743. return this.getTypeFromLength( itemSize, arrayType );
  30744. }
  30745. /**
  30746. * Returns the length for the given data type.
  30747. *
  30748. * @param {String} type - The data type.
  30749. * @return {Number} The length.
  30750. */
  30751. getTypeLength( type ) {
  30752. const vecType = this.getVectorType( type );
  30753. const vecNum = /vec([2-4])/.exec( vecType );
  30754. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  30755. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  30756. if ( /mat2/.test( type ) === true ) return 4;
  30757. if ( /mat3/.test( type ) === true ) return 9;
  30758. if ( /mat4/.test( type ) === true ) return 16;
  30759. return 0;
  30760. }
  30761. /**
  30762. * Returns the vector type for a given matrix type.
  30763. *
  30764. * @param {String} type - The matrix type.
  30765. * @return {String} The vector type.
  30766. */
  30767. getVectorFromMatrix( type ) {
  30768. return type.replace( 'mat', 'vec' );
  30769. }
  30770. /**
  30771. * For a given type this method changes the component type to the
  30772. * given value. E.g. `vec4` should be changed to the new component type
  30773. * `uint` which results in `uvec4`.
  30774. *
  30775. * @param {String} type - The type.
  30776. * @param {String} newComponentType - The new component type.
  30777. * @return {String} The new type.
  30778. */
  30779. changeComponentType( type, newComponentType ) {
  30780. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  30781. }
  30782. /**
  30783. * Returns the integer type pendant for the given type.
  30784. *
  30785. * @param {String} type - The type.
  30786. * @return {String} The integer type.
  30787. */
  30788. getIntegerType( type ) {
  30789. const componentType = this.getComponentType( type );
  30790. if ( componentType === 'int' || componentType === 'uint' ) return type;
  30791. return this.changeComponentType( type, 'int' );
  30792. }
  30793. /**
  30794. * Adds a stack node to the internal stack.
  30795. *
  30796. * @return {StackNode} The added stack node.
  30797. */
  30798. addStack() {
  30799. this.stack = stack( this.stack );
  30800. this.stacks.push( getCurrentStack() || this.stack );
  30801. setCurrentStack( this.stack );
  30802. return this.stack;
  30803. }
  30804. /**
  30805. * Removes the last stack node from the internal stack.
  30806. *
  30807. * @return {StackNode} The removed stack node.
  30808. */
  30809. removeStack() {
  30810. const lastStack = this.stack;
  30811. this.stack = lastStack.parent;
  30812. setCurrentStack( this.stacks.pop() );
  30813. return lastStack;
  30814. }
  30815. /**
  30816. * The builder maintains (cached) data for each node during the building process. This method
  30817. * can be used to get these data for a specific shader stage and cache.
  30818. *
  30819. * @param {Node} node - The node to get the data for.
  30820. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  30821. * @param {NodeCache?} cache - An optional cache.
  30822. * @return {Object} The node data.
  30823. */
  30824. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  30825. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  30826. let nodeData = cache.getData( node );
  30827. if ( nodeData === undefined ) {
  30828. nodeData = {};
  30829. cache.setData( node, nodeData );
  30830. }
  30831. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  30832. return nodeData[ shaderStage ];
  30833. }
  30834. /**
  30835. * Returns the properties for the given node and shader stage.
  30836. *
  30837. * @param {Node} node - The node to get the properties for.
  30838. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage='any'] - The shader stage.
  30839. * @return {Object} The node properties.
  30840. */
  30841. getNodeProperties( node, shaderStage = 'any' ) {
  30842. const nodeData = this.getDataFromNode( node, shaderStage );
  30843. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  30844. }
  30845. /**
  30846. * Returns an instance of {@link NodeAttribute} for the given buffer attribute node.
  30847. *
  30848. * @param {BufferAttributeNode} node - The buffer attribute node.
  30849. * @param {String} type - The node type.
  30850. * @return {NodeAttribute} The node attribute.
  30851. */
  30852. getBufferAttributeFromNode( node, type ) {
  30853. const nodeData = this.getDataFromNode( node );
  30854. let bufferAttribute = nodeData.bufferAttribute;
  30855. if ( bufferAttribute === undefined ) {
  30856. const index = this.uniforms.index ++;
  30857. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  30858. this.bufferAttributes.push( bufferAttribute );
  30859. nodeData.bufferAttribute = bufferAttribute;
  30860. }
  30861. return bufferAttribute;
  30862. }
  30863. /**
  30864. * Returns an instance of {@link StructTypeNode} for the given output struct node.
  30865. *
  30866. * @param {OutputStructNode} node - The output struct node.
  30867. * @param {Array<String>} types - The output struct types.
  30868. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  30869. * @return {StructTypeNode} The struct type attribute.
  30870. */
  30871. getStructTypeFromNode( node, types, shaderStage = this.shaderStage ) {
  30872. const nodeData = this.getDataFromNode( node, shaderStage );
  30873. let structType = nodeData.structType;
  30874. if ( structType === undefined ) {
  30875. const index = this.structs.index ++;
  30876. structType = new StructTypeNode( 'StructType' + index, types );
  30877. this.structs[ shaderStage ].push( structType );
  30878. nodeData.structType = structType;
  30879. }
  30880. return structType;
  30881. }
  30882. /**
  30883. * Returns an instance of {@link NodeUniform} for the given uniform node.
  30884. *
  30885. * @param {UniformNode} node - The uniform node.
  30886. * @param {String} type - The uniform type.
  30887. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  30888. * @param {String?} name - The name of the uniform.
  30889. * @return {NodeUniform} The node uniform.
  30890. */
  30891. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  30892. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  30893. let nodeUniform = nodeData.uniform;
  30894. if ( nodeUniform === undefined ) {
  30895. const index = this.uniforms.index ++;
  30896. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  30897. this.uniforms[ shaderStage ].push( nodeUniform );
  30898. nodeData.uniform = nodeUniform;
  30899. }
  30900. return nodeUniform;
  30901. }
  30902. /**
  30903. * Returns the array length.
  30904. *
  30905. * @param {Node} node - The node.
  30906. * @return {Number?} The array length.
  30907. */
  30908. getArrayCount( node ) {
  30909. let count = null;
  30910. if ( node.isArrayNode ) count = node.count;
  30911. else if ( node.isVarNode && node.node.isArrayNode ) count = node.node.count;
  30912. return count;
  30913. }
  30914. /**
  30915. * Returns an instance of {@link NodeVar} for the given variable node.
  30916. *
  30917. * @param {VarNode} node - The variable node.
  30918. * @param {String?} name - The variable's name.
  30919. * @param {String} [type=node.getNodeType( this )] - The variable's type.
  30920. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  30921. * @param {Boolean} [readOnly=false] - Whether the variable is read-only or not.
  30922. *
  30923. * @return {NodeVar} The node variable.
  30924. */
  30925. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage, readOnly = false ) {
  30926. const nodeData = this.getDataFromNode( node, shaderStage );
  30927. let nodeVar = nodeData.variable;
  30928. if ( nodeVar === undefined ) {
  30929. const idNS = readOnly ? '_const' : '_var';
  30930. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  30931. const id = this.vars[ idNS ] || ( this.vars[ idNS ] = 0 );
  30932. if ( name === null ) {
  30933. name = ( readOnly ? 'nodeConst' : 'nodeVar' ) + id;
  30934. this.vars[ idNS ] ++;
  30935. }
  30936. //
  30937. const count = this.getArrayCount( node );
  30938. nodeVar = new NodeVar( name, type, readOnly, count );
  30939. if ( ! readOnly ) {
  30940. vars.push( nodeVar );
  30941. }
  30942. nodeData.variable = nodeVar;
  30943. }
  30944. return nodeVar;
  30945. }
  30946. /**
  30947. * Returns whether a Node or its flow is deterministic, useful for use in `const`.
  30948. *
  30949. * @param {Node} node - The varying node.
  30950. * @return {Boolean} Returns true if deterministic.
  30951. */
  30952. isDeterministic( node ) {
  30953. if ( node.isMathNode ) {
  30954. return this.isDeterministic( node.aNode ) &&
  30955. ( node.bNode ? this.isDeterministic( node.bNode ) : true ) &&
  30956. ( node.cNode ? this.isDeterministic( node.cNode ) : true );
  30957. } else if ( node.isOperatorNode ) {
  30958. return this.isDeterministic( node.aNode ) &&
  30959. ( node.bNode ? this.isDeterministic( node.bNode ) : true );
  30960. } else if ( node.isArrayNode ) {
  30961. if ( node.values !== null ) {
  30962. for ( const n of node.values ) {
  30963. if ( ! this.isDeterministic( n ) ) {
  30964. return false;
  30965. }
  30966. }
  30967. }
  30968. return true;
  30969. } else if ( node.isConstNode ) {
  30970. return true;
  30971. }
  30972. return false;
  30973. }
  30974. /**
  30975. * Returns an instance of {@link NodeVarying} for the given varying node.
  30976. *
  30977. * @param {(VaryingNode|PropertyNode)} node - The varying node.
  30978. * @param {String?} name - The varying's name.
  30979. * @param {String} [type=node.getNodeType( this )] - The varying's type.
  30980. * @return {NodeVar} The node varying.
  30981. */
  30982. getVaryingFromNode( node, name = null, type = node.getNodeType( this ) ) {
  30983. const nodeData = this.getDataFromNode( node, 'any' );
  30984. let nodeVarying = nodeData.varying;
  30985. if ( nodeVarying === undefined ) {
  30986. const varyings = this.varyings;
  30987. const index = varyings.length;
  30988. if ( name === null ) name = 'nodeVarying' + index;
  30989. nodeVarying = new NodeVarying( name, type );
  30990. varyings.push( nodeVarying );
  30991. nodeData.varying = nodeVarying;
  30992. }
  30993. return nodeVarying;
  30994. }
  30995. /**
  30996. * Returns an instance of {@link NodeCode} for the given code node.
  30997. *
  30998. * @param {CodeNode} node - The code node.
  30999. * @param {String} type - The node type.
  31000. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  31001. * @return {NodeCode} The node code.
  31002. */
  31003. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  31004. const nodeData = this.getDataFromNode( node );
  31005. let nodeCode = nodeData.code;
  31006. if ( nodeCode === undefined ) {
  31007. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  31008. const index = codes.length;
  31009. nodeCode = new NodeCode( 'nodeCode' + index, type );
  31010. codes.push( nodeCode );
  31011. nodeData.code = nodeCode;
  31012. }
  31013. return nodeCode;
  31014. }
  31015. /**
  31016. * Adds a code flow based on the code-block hierarchy.
  31017. * This is used so that code-blocks like If,Else create their variables locally if the Node
  31018. * is only used inside one of these conditionals in the current shader stage.
  31019. *
  31020. * @param {Node} node - The node to add.
  31021. * @param {Node} nodeBlock - Node-based code-block. Usually 'ConditionalNode'.
  31022. */
  31023. addFlowCodeHierarchy( node, nodeBlock ) {
  31024. const { flowCodes, flowCodeBlock } = this.getDataFromNode( node );
  31025. let needsFlowCode = true;
  31026. let nodeBlockHierarchy = nodeBlock;
  31027. while ( nodeBlockHierarchy ) {
  31028. if ( flowCodeBlock.get( nodeBlockHierarchy ) === true ) {
  31029. needsFlowCode = false;
  31030. break;
  31031. }
  31032. nodeBlockHierarchy = this.getDataFromNode( nodeBlockHierarchy ).parentNodeBlock;
  31033. }
  31034. if ( needsFlowCode ) {
  31035. for ( const flowCode of flowCodes ) {
  31036. this.addLineFlowCode( flowCode );
  31037. }
  31038. }
  31039. }
  31040. /**
  31041. * Add a inline-code to the current flow code-block.
  31042. *
  31043. * @param {Node} node - The node to add.
  31044. * @param {String} code - The code to add.
  31045. * @param {Node} nodeBlock - Current ConditionalNode
  31046. */
  31047. addLineFlowCodeBlock( node, code, nodeBlock ) {
  31048. const nodeData = this.getDataFromNode( node );
  31049. const flowCodes = nodeData.flowCodes || ( nodeData.flowCodes = [] );
  31050. const codeBlock = nodeData.flowCodeBlock || ( nodeData.flowCodeBlock = new WeakMap() );
  31051. flowCodes.push( code );
  31052. codeBlock.set( nodeBlock, true );
  31053. }
  31054. /**
  31055. * Add a inline-code to the current flow.
  31056. *
  31057. * @param {String} code - The code to add.
  31058. * @param {Node?} [node= null] - Optional Node, can help the system understand if the Node is part of a code-block.
  31059. * @return {NodeBuilder} A reference to this node builder.
  31060. */
  31061. addLineFlowCode( code, node = null ) {
  31062. if ( code === '' ) return this;
  31063. if ( node !== null && this.context.nodeBlock ) {
  31064. this.addLineFlowCodeBlock( node, code, this.context.nodeBlock );
  31065. }
  31066. code = this.tab + code;
  31067. if ( ! /;\s*$/.test( code ) ) {
  31068. code = code + ';\n';
  31069. }
  31070. this.flow.code += code;
  31071. return this;
  31072. }
  31073. /**
  31074. * Adds a code to the current code flow.
  31075. *
  31076. * @param {String} code - Shader code.
  31077. * @return {NodeBuilder} A reference to this node builder.
  31078. */
  31079. addFlowCode( code ) {
  31080. this.flow.code += code;
  31081. return this;
  31082. }
  31083. /**
  31084. * Add tab in the code that will be generated so that other snippets respect the current tabulation.
  31085. * Typically used in codes with If,Else.
  31086. *
  31087. * @return {NodeBuilder} A reference to this node builder.
  31088. */
  31089. addFlowTab() {
  31090. this.tab += '\t';
  31091. return this;
  31092. }
  31093. /**
  31094. * Removes a tab.
  31095. *
  31096. * @return {NodeBuilder} A reference to this node builder.
  31097. */
  31098. removeFlowTab() {
  31099. this.tab = this.tab.slice( 0, -1 );
  31100. return this;
  31101. }
  31102. /**
  31103. * Gets the current flow data based on a Node.
  31104. *
  31105. * @param {Node} node - Node that the flow was started.
  31106. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  31107. * @return {Object} The flow data.
  31108. */
  31109. getFlowData( node/*, shaderStage*/ ) {
  31110. return this.flowsData.get( node );
  31111. }
  31112. /**
  31113. * Executes the node flow based on a root node to generate the final shader code.
  31114. *
  31115. * @param {Node} node - The node to execute.
  31116. * @return {Object} The code flow.
  31117. */
  31118. flowNode( node ) {
  31119. const output = node.getNodeType( this );
  31120. const flowData = this.flowChildNode( node, output );
  31121. this.flowsData.set( node, flowData );
  31122. return flowData;
  31123. }
  31124. /**
  31125. * Returns the native shader operator name for a given generic name.
  31126. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  31127. *
  31128. * @param {ShaderNodeInternal} shaderNode - The shader node to build the function node with.
  31129. * @return {FunctionNode} The build function node.
  31130. */
  31131. buildFunctionNode( shaderNode ) {
  31132. const fn = new FunctionNode();
  31133. const previous = this.currentFunctionNode;
  31134. this.currentFunctionNode = fn;
  31135. fn.code = this.buildFunctionCode( shaderNode );
  31136. this.currentFunctionNode = previous;
  31137. return fn;
  31138. }
  31139. /**
  31140. * Generates a code flow based on a TSL function: Fn().
  31141. *
  31142. * @param {ShaderNodeInternal} shaderNode - A function code will be generated based on the input.
  31143. * @return {Object}
  31144. */
  31145. flowShaderNode( shaderNode ) {
  31146. const layout = shaderNode.layout;
  31147. const inputs = {
  31148. [ Symbol.iterator ]() {
  31149. let index = 0;
  31150. const values = Object.values( this );
  31151. return {
  31152. next: () => ( {
  31153. value: values[ index ],
  31154. done: index ++ >= values.length
  31155. } )
  31156. };
  31157. }
  31158. };
  31159. for ( const input of layout.inputs ) {
  31160. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  31161. }
  31162. //
  31163. shaderNode.layout = null;
  31164. const callNode = shaderNode.call( inputs );
  31165. const flowData = this.flowStagesNode( callNode, layout.type );
  31166. shaderNode.layout = layout;
  31167. return flowData;
  31168. }
  31169. /**
  31170. * Runs the node flow through all the steps of creation, 'setup', 'analyze', 'generate'.
  31171. *
  31172. * @param {Node} node - The node to execute.
  31173. * @param {String?} output - Expected output type. For example 'vec3'.
  31174. * @return {Object}
  31175. */
  31176. flowStagesNode( node, output = null ) {
  31177. const previousFlow = this.flow;
  31178. const previousVars = this.vars;
  31179. const previousCache = this.cache;
  31180. const previousBuildStage = this.buildStage;
  31181. const previousStack = this.stack;
  31182. const flow = {
  31183. code: ''
  31184. };
  31185. this.flow = flow;
  31186. this.vars = {};
  31187. this.cache = new NodeCache();
  31188. this.stack = stack();
  31189. for ( const buildStage of defaultBuildStages ) {
  31190. this.setBuildStage( buildStage );
  31191. flow.result = node.build( this, output );
  31192. }
  31193. flow.vars = this.getVars( this.shaderStage );
  31194. this.flow = previousFlow;
  31195. this.vars = previousVars;
  31196. this.cache = previousCache;
  31197. this.stack = previousStack;
  31198. this.setBuildStage( previousBuildStage );
  31199. return flow;
  31200. }
  31201. /**
  31202. * Returns the native shader operator name for a given generic name.
  31203. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  31204. *
  31205. * @abstract
  31206. * @param {String} op - The operator name to resolve.
  31207. * @return {String} The resolved operator name.
  31208. */
  31209. getFunctionOperator( /* op */ ) {
  31210. return null;
  31211. }
  31212. /**
  31213. * Generates a code flow based on a child Node.
  31214. *
  31215. * @param {Node} node - The node to execute.
  31216. * @param {String?} output - Expected output type. For example 'vec3'.
  31217. * @return {Object} The code flow.
  31218. */
  31219. flowChildNode( node, output = null ) {
  31220. const previousFlow = this.flow;
  31221. const flow = {
  31222. code: ''
  31223. };
  31224. this.flow = flow;
  31225. flow.result = node.build( this, output );
  31226. this.flow = previousFlow;
  31227. return flow;
  31228. }
  31229. /**
  31230. * Executes a flow of code in a different stage.
  31231. *
  31232. * Some nodes like `varying()` have the ability to compute code in vertex-stage and
  31233. * return the value in fragment-stage even if it is being executed in an input fragment.
  31234. *
  31235. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  31236. * @param {Node} node - The node to execute.
  31237. * @param {String?} output - Expected output type. For example 'vec3'.
  31238. * @param {String?} propertyName - The property name to assign the result.
  31239. * @return {Object}
  31240. */
  31241. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  31242. const previousShaderStage = this.shaderStage;
  31243. this.setShaderStage( shaderStage );
  31244. const flowData = this.flowChildNode( node, output );
  31245. if ( propertyName !== null ) {
  31246. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  31247. }
  31248. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  31249. this.setShaderStage( previousShaderStage );
  31250. return flowData;
  31251. }
  31252. /**
  31253. * Returns an array holding all node attributes of this node builder.
  31254. *
  31255. * @return {Array<NodeAttribute>} The node attributes of this builder.
  31256. */
  31257. getAttributesArray() {
  31258. return this.attributes.concat( this.bufferAttributes );
  31259. }
  31260. /**
  31261. * Returns the attribute definitions as a shader string for the given shader stage.
  31262. *
  31263. * @abstract
  31264. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  31265. * @return {String} The attribute code section.
  31266. */
  31267. getAttributes( /*shaderStage*/ ) {
  31268. console.warn( 'Abstract function.' );
  31269. }
  31270. /**
  31271. * Returns the varying definitions as a shader string for the given shader stage.
  31272. *
  31273. * @abstract
  31274. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  31275. * @return {String} The varying code section.
  31276. */
  31277. getVaryings( /*shaderStage*/ ) {
  31278. console.warn( 'Abstract function.' );
  31279. }
  31280. /**
  31281. * Returns a single variable definition as a shader string for the given variable type and name.
  31282. *
  31283. * @param {String} type - The variable's type.
  31284. * @param {String} name - The variable's name.
  31285. * @param {Number?} [count=null] - The array length.
  31286. * @return {String} The shader string.
  31287. */
  31288. getVar( type, name, count = null ) {
  31289. return `${ count !== null ? this.generateArrayDeclaration( type, count ) : this.getType( type ) } ${ name }`;
  31290. }
  31291. /**
  31292. * Returns the variable definitions as a shader string for the given shader stage.
  31293. *
  31294. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  31295. * @return {String} The variable code section.
  31296. */
  31297. getVars( shaderStage ) {
  31298. let snippet = '';
  31299. const vars = this.vars[ shaderStage ];
  31300. if ( vars !== undefined ) {
  31301. for ( const variable of vars ) {
  31302. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  31303. }
  31304. }
  31305. return snippet;
  31306. }
  31307. /**
  31308. * Returns the uniform definitions as a shader string for the given shader stage.
  31309. *
  31310. * @abstract
  31311. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  31312. * @return {String} The uniform code section.
  31313. */
  31314. getUniforms( /*shaderStage*/ ) {
  31315. console.warn( 'Abstract function.' );
  31316. }
  31317. /**
  31318. * Returns the native code definitions as a shader string for the given shader stage.
  31319. *
  31320. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  31321. * @return {String} The native code section.
  31322. */
  31323. getCodes( shaderStage ) {
  31324. const codes = this.codes[ shaderStage ];
  31325. let code = '';
  31326. if ( codes !== undefined ) {
  31327. for ( const nodeCode of codes ) {
  31328. code += nodeCode.code + '\n';
  31329. }
  31330. }
  31331. return code;
  31332. }
  31333. /**
  31334. * Returns the hash of this node builder.
  31335. *
  31336. * @return {String} The hash.
  31337. */
  31338. getHash() {
  31339. return this.vertexShader + this.fragmentShader + this.computeShader;
  31340. }
  31341. /**
  31342. * Sets the current shader stage.
  31343. *
  31344. * @param {('vertex'|'fragment'|'compute'|'any')?} shaderStage - The shader stage to set.
  31345. */
  31346. setShaderStage( shaderStage ) {
  31347. this.shaderStage = shaderStage;
  31348. }
  31349. /**
  31350. * Returns the current shader stage.
  31351. *
  31352. * @return {('vertex'|'fragment'|'compute'|'any')?} The current shader stage.
  31353. */
  31354. getShaderStage() {
  31355. return this.shaderStage;
  31356. }
  31357. /**
  31358. * Sets the current build stage.
  31359. *
  31360. * @param {('setup'|'analyze'|'generate')?} buildStage - The build stage to set.
  31361. */
  31362. setBuildStage( buildStage ) {
  31363. this.buildStage = buildStage;
  31364. }
  31365. /**
  31366. * Returns the current build stage.
  31367. *
  31368. * @return {('setup'|'analyze'|'generate')?} The current build stage.
  31369. */
  31370. getBuildStage() {
  31371. return this.buildStage;
  31372. }
  31373. /**
  31374. * Controls the code build of the shader stages.
  31375. *
  31376. * @abstract
  31377. */
  31378. buildCode() {
  31379. console.warn( 'Abstract function.' );
  31380. }
  31381. /**
  31382. * Central build method which controls the build for the given object.
  31383. *
  31384. * @return {NodeBuilder} A reference to this node builder.
  31385. */
  31386. build() {
  31387. const { object, material, renderer } = this;
  31388. if ( material !== null ) {
  31389. let nodeMaterial = renderer.library.fromMaterial( material );
  31390. if ( nodeMaterial === null ) {
  31391. console.error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  31392. nodeMaterial = new NodeMaterial();
  31393. }
  31394. nodeMaterial.build( this );
  31395. } else {
  31396. this.addFlow( 'compute', object );
  31397. }
  31398. // setup() -> stage 1: create possible new nodes and returns an output reference node
  31399. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  31400. // generate() -> stage 3: generate shader
  31401. for ( const buildStage of defaultBuildStages ) {
  31402. this.setBuildStage( buildStage );
  31403. if ( this.context.vertex && this.context.vertex.isNode ) {
  31404. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  31405. }
  31406. for ( const shaderStage of shaderStages ) {
  31407. this.setShaderStage( shaderStage );
  31408. const flowNodes = this.flowNodes[ shaderStage ];
  31409. for ( const node of flowNodes ) {
  31410. if ( buildStage === 'generate' ) {
  31411. this.flowNode( node );
  31412. } else {
  31413. node.build( this );
  31414. }
  31415. }
  31416. }
  31417. }
  31418. this.setBuildStage( null );
  31419. this.setShaderStage( null );
  31420. // stage 4: build code for a specific output
  31421. this.buildCode();
  31422. this.buildUpdateNodes();
  31423. return this;
  31424. }
  31425. /**
  31426. * Returns a uniform representation which is later used for UBO generation and rendering.
  31427. *
  31428. * @param {NodeUniform} uniformNode - The uniform node.
  31429. * @param {String} type - The requested type.
  31430. * @return {Uniform} The uniform.
  31431. */
  31432. getNodeUniform( uniformNode, type ) {
  31433. if ( type === 'float' || type === 'int' || type === 'uint' ) return new NumberNodeUniform( uniformNode );
  31434. if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) return new Vector2NodeUniform( uniformNode );
  31435. if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) return new Vector3NodeUniform( uniformNode );
  31436. if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) return new Vector4NodeUniform( uniformNode );
  31437. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  31438. if ( type === 'mat2' ) return new Matrix2NodeUniform( uniformNode );
  31439. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  31440. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  31441. throw new Error( `Uniform "${type}" not declared.` );
  31442. }
  31443. /**
  31444. * Formats the given shader snippet from a given type into another one. E.g.
  31445. * this method might be used to convert a simple float string `"1.0"` into a
  31446. * `vec3` representation: `"vec3<f32>( 1.0 )"`.
  31447. *
  31448. * @param {String} snippet - The shader snippet.
  31449. * @param {String} fromType - The source type.
  31450. * @param {String} toType - The target type.
  31451. * @return {String} The updated shader string.
  31452. */
  31453. format( snippet, fromType, toType ) {
  31454. fromType = this.getVectorType( fromType );
  31455. toType = this.getVectorType( toType );
  31456. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  31457. return snippet;
  31458. }
  31459. const fromTypeLength = this.getTypeLength( fromType );
  31460. const toTypeLength = this.getTypeLength( toType );
  31461. if ( fromTypeLength === 16 && toTypeLength === 9 ) {
  31462. return `${ this.getType( toType ) }(${ snippet }[0].xyz, ${ snippet }[1].xyz, ${ snippet }[2].xyz)`;
  31463. }
  31464. if ( fromTypeLength === 9 && toTypeLength === 4 ) {
  31465. return `${ this.getType( toType ) }(${ snippet }[0].xy, ${ snippet }[1].xy)`;
  31466. }
  31467. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  31468. // @TODO: ignore for now
  31469. return snippet;
  31470. }
  31471. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  31472. // @TODO: ignore for now
  31473. return snippet;
  31474. }
  31475. if ( fromTypeLength === toTypeLength ) {
  31476. return `${ this.getType( toType ) }( ${ snippet } )`;
  31477. }
  31478. if ( fromTypeLength > toTypeLength ) {
  31479. return this.format( `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  31480. }
  31481. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  31482. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  31483. }
  31484. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  31485. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  31486. }
  31487. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  31488. // convert a number value to vector type, e.g:
  31489. // vec3( 1u ) -> vec3( float( 1u ) )
  31490. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  31491. }
  31492. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  31493. }
  31494. /**
  31495. * Returns a signature with the engine's current revision.
  31496. *
  31497. * @return {String} The signature.
  31498. */
  31499. getSignature() {
  31500. return `// Three.js r${ REVISION } - Node System\n`;
  31501. }
  31502. // Deprecated
  31503. /**
  31504. * @function
  31505. * @deprecated since r168. Use `new NodeMaterial()` instead, with targeted node material name.
  31506. *
  31507. * @param {String} [type='NodeMaterial'] - The node material type.
  31508. * @throws {Error}
  31509. */
  31510. createNodeMaterial( type = 'NodeMaterial' ) { // @deprecated, r168
  31511. throw new Error( `THREE.NodeBuilder: createNodeMaterial() was deprecated. Use new ${ type }() instead.` );
  31512. }
  31513. }
  31514. /**
  31515. * Management class for updating nodes. The module tracks metrics like
  31516. * the elapsed time, delta time, the render and frame ID to correctly
  31517. * call the node update methods {@link Node#updateBefore}, {@link Node#update}
  31518. * and {@link Node#updateAfter} depending on the node's configuration.
  31519. */
  31520. class NodeFrame {
  31521. /**
  31522. * Constructs a new node fame.
  31523. */
  31524. constructor() {
  31525. /**
  31526. * The elapsed time in seconds.
  31527. *
  31528. * @type {Number}
  31529. * @default 0
  31530. */
  31531. this.time = 0;
  31532. /**
  31533. * The delta time in seconds.
  31534. *
  31535. * @type {Number}
  31536. * @default 0
  31537. */
  31538. this.deltaTime = 0;
  31539. /**
  31540. * The frame ID.
  31541. *
  31542. * @type {Number}
  31543. * @default 0
  31544. */
  31545. this.frameId = 0;
  31546. /**
  31547. * The render ID.
  31548. *
  31549. * @type {Number}
  31550. * @default 0
  31551. */
  31552. this.renderId = 0;
  31553. /**
  31554. * Used to control the {@link Node#update} call.
  31555. *
  31556. * @type {WeakMap<Node, Object>}
  31557. */
  31558. this.updateMap = new WeakMap();
  31559. /**
  31560. * Used to control the {@link Node#updateBefore} call.
  31561. *
  31562. * @type {WeakMap<Node, Object>}
  31563. */
  31564. this.updateBeforeMap = new WeakMap();
  31565. /**
  31566. * Used to control the {@link Node#updateAfter} call.
  31567. *
  31568. * @type {WeakMap<Node, Object>}
  31569. */
  31570. this.updateAfterMap = new WeakMap();
  31571. /**
  31572. * A reference to the current renderer.
  31573. *
  31574. * @type {Renderer?}
  31575. * @default null
  31576. */
  31577. this.renderer = null;
  31578. /**
  31579. * A reference to the current material.
  31580. *
  31581. * @type {Material?}
  31582. * @default null
  31583. */
  31584. this.material = null;
  31585. /**
  31586. * A reference to the current camera.
  31587. *
  31588. * @type {Camera?}
  31589. * @default null
  31590. */
  31591. this.camera = null;
  31592. /**
  31593. * A reference to the current 3D object.
  31594. *
  31595. * @type {Object3D?}
  31596. * @default null
  31597. */
  31598. this.object = null;
  31599. /**
  31600. * A reference to the current scene.
  31601. *
  31602. * @type {Scene?}
  31603. * @default null
  31604. */
  31605. this.scene = null;
  31606. }
  31607. /**
  31608. * Returns a dictionary for a given node and update map which
  31609. * is used to correctly call node update methods per frame or render.
  31610. *
  31611. * @private
  31612. * @param {WeakMap<Node, Object>} referenceMap - The reference weak map.
  31613. * @param {Node} nodeRef - The reference to the current node.
  31614. * @return {Object<String,WeakMap>} The dictionary.
  31615. */
  31616. _getMaps( referenceMap, nodeRef ) {
  31617. let maps = referenceMap.get( nodeRef );
  31618. if ( maps === undefined ) {
  31619. maps = {
  31620. renderMap: new WeakMap(),
  31621. frameMap: new WeakMap()
  31622. };
  31623. referenceMap.set( nodeRef, maps );
  31624. }
  31625. return maps;
  31626. }
  31627. /**
  31628. * This method executes the {@link Node#updateBefore} for the given node.
  31629. * It makes sure {@link Node#updateBeforeType} is honored meaning the update
  31630. * is only executed once per frame, render or object depending on the update
  31631. * type.
  31632. *
  31633. * @param {Node} node - The node that should be updated.
  31634. */
  31635. updateBeforeNode( node ) {
  31636. const updateType = node.getUpdateBeforeType();
  31637. const reference = node.updateReference( this );
  31638. if ( updateType === NodeUpdateType.FRAME ) {
  31639. const { frameMap } = this._getMaps( this.updateBeforeMap, reference );
  31640. if ( frameMap.get( reference ) !== this.frameId ) {
  31641. if ( node.updateBefore( this ) !== false ) {
  31642. frameMap.set( reference, this.frameId );
  31643. }
  31644. }
  31645. } else if ( updateType === NodeUpdateType.RENDER ) {
  31646. const { renderMap } = this._getMaps( this.updateBeforeMap, reference );
  31647. if ( renderMap.get( reference ) !== this.renderId ) {
  31648. if ( node.updateBefore( this ) !== false ) {
  31649. renderMap.set( reference, this.renderId );
  31650. }
  31651. }
  31652. } else if ( updateType === NodeUpdateType.OBJECT ) {
  31653. node.updateBefore( this );
  31654. }
  31655. }
  31656. /**
  31657. * This method executes the {@link Node#updateAfter} for the given node.
  31658. * It makes sure {@link Node#updateAfterType} is honored meaning the update
  31659. * is only executed once per frame, render or object depending on the update
  31660. * type.
  31661. *
  31662. * @param {Node} node - The node that should be updated.
  31663. */
  31664. updateAfterNode( node ) {
  31665. const updateType = node.getUpdateAfterType();
  31666. const reference = node.updateReference( this );
  31667. if ( updateType === NodeUpdateType.FRAME ) {
  31668. const { frameMap } = this._getMaps( this.updateAfterMap, reference );
  31669. if ( frameMap.get( reference ) !== this.frameId ) {
  31670. if ( node.updateAfter( this ) !== false ) {
  31671. frameMap.set( reference, this.frameId );
  31672. }
  31673. }
  31674. } else if ( updateType === NodeUpdateType.RENDER ) {
  31675. const { renderMap } = this._getMaps( this.updateAfterMap, reference );
  31676. if ( renderMap.get( reference ) !== this.renderId ) {
  31677. if ( node.updateAfter( this ) !== false ) {
  31678. renderMap.set( reference, this.renderId );
  31679. }
  31680. }
  31681. } else if ( updateType === NodeUpdateType.OBJECT ) {
  31682. node.updateAfter( this );
  31683. }
  31684. }
  31685. /**
  31686. * This method executes the {@link Node#update} for the given node.
  31687. * It makes sure {@link Node#updateType} is honored meaning the update
  31688. * is only executed once per frame, render or object depending on the update
  31689. * type.
  31690. *
  31691. * @param {Node} node - The node that should be updated.
  31692. */
  31693. updateNode( node ) {
  31694. const updateType = node.getUpdateType();
  31695. const reference = node.updateReference( this );
  31696. if ( updateType === NodeUpdateType.FRAME ) {
  31697. const { frameMap } = this._getMaps( this.updateMap, reference );
  31698. if ( frameMap.get( reference ) !== this.frameId ) {
  31699. if ( node.update( this ) !== false ) {
  31700. frameMap.set( reference, this.frameId );
  31701. }
  31702. }
  31703. } else if ( updateType === NodeUpdateType.RENDER ) {
  31704. const { renderMap } = this._getMaps( this.updateMap, reference );
  31705. if ( renderMap.get( reference ) !== this.renderId ) {
  31706. if ( node.update( this ) !== false ) {
  31707. renderMap.set( reference, this.renderId );
  31708. }
  31709. }
  31710. } else if ( updateType === NodeUpdateType.OBJECT ) {
  31711. node.update( this );
  31712. }
  31713. }
  31714. /**
  31715. * Updates the internal state of the node frame. This method is
  31716. * called by the renderer in its internal animation loop.
  31717. */
  31718. update() {
  31719. this.frameId ++;
  31720. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  31721. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  31722. this.lastTime = performance.now();
  31723. this.time += this.deltaTime;
  31724. }
  31725. }
  31726. /**
  31727. * Describes the input of a {@link NodeFunction}.
  31728. */
  31729. class NodeFunctionInput {
  31730. /**
  31731. * Constructs a new node function input.
  31732. *
  31733. * @param {String} type - The input type.
  31734. * @param {String} name - The input name.
  31735. * @param {Number?} [count=null] - If the input is an Array, count will be the length.
  31736. * @param {('in'|'out'|'inout')} [qualifier=''] - The parameter qualifier (only relevant for GLSL).
  31737. * @param {Boolean} [isConst=false] - Whether the input uses a const qualifier or not (only relevant for GLSL).
  31738. */
  31739. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  31740. /**
  31741. * The input type.
  31742. *
  31743. * @type {String}
  31744. */
  31745. this.type = type;
  31746. /**
  31747. * The input name.
  31748. *
  31749. * @type {String}
  31750. */
  31751. this.name = name;
  31752. /**
  31753. * If the input is an Array, count will be the length.
  31754. *
  31755. * @type {Number?}
  31756. * @default null
  31757. */
  31758. this.count = count;
  31759. /**
  31760. *The parameter qualifier (only relevant for GLSL).
  31761. *
  31762. * @type {('in'|'out'|'inout')}
  31763. * @default ''
  31764. */
  31765. this.qualifier = qualifier;
  31766. /**
  31767. * Whether the input uses a const qualifier or not (only relevant for GLSL).
  31768. *
  31769. * @type {Boolean}
  31770. * @default false
  31771. */
  31772. this.isConst = isConst;
  31773. }
  31774. }
  31775. NodeFunctionInput.isNodeFunctionInput = true;
  31776. /**
  31777. * Module for representing directional lights as nodes.
  31778. *
  31779. * @augments AnalyticLightNode
  31780. */
  31781. class DirectionalLightNode extends AnalyticLightNode {
  31782. static get type() {
  31783. return 'DirectionalLightNode';
  31784. }
  31785. /**
  31786. * Constructs a new directional light node.
  31787. *
  31788. * @param {DirectionalLight?} [light=null] - The directional light source.
  31789. */
  31790. constructor( light = null ) {
  31791. super( light );
  31792. }
  31793. setup( builder ) {
  31794. super.setup( builder );
  31795. const lightingModel = builder.context.lightingModel;
  31796. const lightColor = this.colorNode;
  31797. const lightDirection = lightTargetDirection( this.light );
  31798. const reflectedLight = builder.context.reflectedLight;
  31799. lightingModel.direct( {
  31800. lightDirection,
  31801. lightColor,
  31802. reflectedLight
  31803. }, builder.stack, builder );
  31804. }
  31805. }
  31806. const _matrix41 = /*@__PURE__*/ new Matrix4();
  31807. const _matrix42 = /*@__PURE__*/ new Matrix4();
  31808. let _ltcLib = null;
  31809. /**
  31810. * Module for representing rect area lights as nodes.
  31811. *
  31812. * @augments AnalyticLightNode
  31813. */
  31814. class RectAreaLightNode extends AnalyticLightNode {
  31815. static get type() {
  31816. return 'RectAreaLightNode';
  31817. }
  31818. /**
  31819. * Constructs a new rect area light node.
  31820. *
  31821. * @param {RectAreaLight?} [light=null] - The rect area light source.
  31822. */
  31823. constructor( light = null ) {
  31824. super( light );
  31825. /**
  31826. * Uniform node representing the half height of the are light.
  31827. *
  31828. * @type {UniformNode<vec3>}
  31829. */
  31830. this.halfHeight = uniform( new Vector3() ).setGroup( renderGroup );
  31831. /**
  31832. * Uniform node representing the half width of the are light.
  31833. *
  31834. * @type {UniformNode<vec3>}
  31835. */
  31836. this.halfWidth = uniform( new Vector3() ).setGroup( renderGroup );
  31837. /**
  31838. * The `updateType` is set to `NodeUpdateType.RENDER` since the light
  31839. * relies on `viewMatrix` which might vary per render call.
  31840. *
  31841. * @type {String}
  31842. * @default 'render'
  31843. */
  31844. this.updateType = NodeUpdateType.RENDER;
  31845. }
  31846. /**
  31847. * Overwritten to updated rect area light specific uniforms.
  31848. *
  31849. * @param {NodeFrame} frame - A reference to the current node frame.
  31850. */
  31851. update( frame ) {
  31852. super.update( frame );
  31853. const { light } = this;
  31854. const viewMatrix = frame.camera.matrixWorldInverse;
  31855. _matrix42.identity();
  31856. _matrix41.copy( light.matrixWorld );
  31857. _matrix41.premultiply( viewMatrix );
  31858. _matrix42.extractRotation( _matrix41 );
  31859. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  31860. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  31861. this.halfWidth.value.applyMatrix4( _matrix42 );
  31862. this.halfHeight.value.applyMatrix4( _matrix42 );
  31863. }
  31864. setup( builder ) {
  31865. super.setup( builder );
  31866. let ltc_1, ltc_2;
  31867. if ( builder.isAvailable( 'float32Filterable' ) ) {
  31868. ltc_1 = texture( _ltcLib.LTC_FLOAT_1 );
  31869. ltc_2 = texture( _ltcLib.LTC_FLOAT_2 );
  31870. } else {
  31871. ltc_1 = texture( _ltcLib.LTC_HALF_1 );
  31872. ltc_2 = texture( _ltcLib.LTC_HALF_2 );
  31873. }
  31874. const { colorNode, light } = this;
  31875. const lightingModel = builder.context.lightingModel;
  31876. const lightPosition = lightViewPosition( light );
  31877. const reflectedLight = builder.context.reflectedLight;
  31878. lightingModel.directRectArea( {
  31879. lightColor: colorNode,
  31880. lightPosition,
  31881. halfWidth: this.halfWidth,
  31882. halfHeight: this.halfHeight,
  31883. reflectedLight,
  31884. ltc_1,
  31885. ltc_2
  31886. }, builder.stack, builder );
  31887. }
  31888. /**
  31889. * Used to configure the internal BRDF approximation texture data.
  31890. *
  31891. * @param {RectAreaLightTexturesLib} ltc - The BRDF approximation texture data.
  31892. */
  31893. static setLTC( ltc ) {
  31894. _ltcLib = ltc;
  31895. }
  31896. }
  31897. /**
  31898. * Module for representing spot lights as nodes.
  31899. *
  31900. * @augments AnalyticLightNode
  31901. */
  31902. class SpotLightNode extends AnalyticLightNode {
  31903. static get type() {
  31904. return 'SpotLightNode';
  31905. }
  31906. /**
  31907. * Constructs a new spot light node.
  31908. *
  31909. * @param {SpotLight?} [light=null] - The spot light source.
  31910. */
  31911. constructor( light = null ) {
  31912. super( light );
  31913. /**
  31914. * Uniform node representing the cone cosine.
  31915. *
  31916. * @type {UniformNode<float>}
  31917. */
  31918. this.coneCosNode = uniform( 0 ).setGroup( renderGroup );
  31919. /**
  31920. * Uniform node representing the penumbra cosine.
  31921. *
  31922. * @type {UniformNode<float>}
  31923. */
  31924. this.penumbraCosNode = uniform( 0 ).setGroup( renderGroup );
  31925. /**
  31926. * Uniform node representing the cutoff distance.
  31927. *
  31928. * @type {UniformNode<float>}
  31929. */
  31930. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  31931. /**
  31932. * Uniform node representing the decay exponent.
  31933. *
  31934. * @type {UniformNode<float>}
  31935. */
  31936. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  31937. }
  31938. /**
  31939. * Overwritten to updated spot light specific uniforms.
  31940. *
  31941. * @param {NodeFrame} frame - A reference to the current node frame.
  31942. */
  31943. update( frame ) {
  31944. super.update( frame );
  31945. const { light } = this;
  31946. this.coneCosNode.value = Math.cos( light.angle );
  31947. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  31948. this.cutoffDistanceNode.value = light.distance;
  31949. this.decayExponentNode.value = light.decay;
  31950. }
  31951. /**
  31952. * Computes the spot attenuation for the given angle.
  31953. *
  31954. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  31955. * @return {Node<float>} The spot attenuation.
  31956. */
  31957. getSpotAttenuation( angleCosine ) {
  31958. const { coneCosNode, penumbraCosNode } = this;
  31959. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  31960. }
  31961. setup( builder ) {
  31962. super.setup( builder );
  31963. const lightingModel = builder.context.lightingModel;
  31964. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  31965. const lVector = lightViewPosition( light ).sub( positionView ); // @TODO: Add it into LightNode
  31966. const lightDirection = lVector.normalize();
  31967. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  31968. const spotAttenuation = this.getSpotAttenuation( angleCos );
  31969. const lightDistance = lVector.length();
  31970. const lightAttenuation = getDistanceAttenuation( {
  31971. lightDistance,
  31972. cutoffDistance: cutoffDistanceNode,
  31973. decayExponent: decayExponentNode
  31974. } );
  31975. let lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  31976. if ( light.map ) {
  31977. const spotLightCoord = lightProjectionUV( light );
  31978. const projectedTexture = texture( light.map, spotLightCoord.xy ).onRenderUpdate( () => light.map );
  31979. const inSpotLightMap = spotLightCoord.mul( 2. ).sub( 1. ).abs().lessThan( 1. ).all();
  31980. lightColor = inSpotLightMap.select( lightColor.mul( projectedTexture ), lightColor );
  31981. }
  31982. const reflectedLight = builder.context.reflectedLight;
  31983. lightingModel.direct( {
  31984. lightDirection,
  31985. lightColor,
  31986. reflectedLight
  31987. }, builder.stack, builder );
  31988. }
  31989. }
  31990. /**
  31991. * An IES version of the default spot light node.
  31992. *
  31993. * @augments SpotLightNode
  31994. */
  31995. class IESSpotLightNode extends SpotLightNode {
  31996. static get type() {
  31997. return 'IESSpotLightNode';
  31998. }
  31999. /**
  32000. * Overwrites the default implementation to compute an IES conform spot attenuation.
  32001. *
  32002. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  32003. * @return {Node<float>} The spot attenuation.
  32004. */
  32005. getSpotAttenuation( angleCosine ) {
  32006. const iesMap = this.light.iesMap;
  32007. let spotAttenuation = null;
  32008. if ( iesMap && iesMap.isTexture === true ) {
  32009. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  32010. spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r;
  32011. } else {
  32012. spotAttenuation = super.getSpotAttenuation( angleCosine );
  32013. }
  32014. return spotAttenuation;
  32015. }
  32016. }
  32017. /**
  32018. * Module for representing ambient lights as nodes.
  32019. *
  32020. * @augments AnalyticLightNode
  32021. */
  32022. class AmbientLightNode extends AnalyticLightNode {
  32023. static get type() {
  32024. return 'AmbientLightNode';
  32025. }
  32026. /**
  32027. * Constructs a new ambient light node.
  32028. *
  32029. * @param {AmbientLight?} [light=null] - The ambient light source.
  32030. */
  32031. constructor( light = null ) {
  32032. super( light );
  32033. }
  32034. setup( { context } ) {
  32035. context.irradiance.addAssign( this.colorNode );
  32036. }
  32037. }
  32038. /**
  32039. * Module for representing hemisphere lights as nodes.
  32040. *
  32041. * @augments AnalyticLightNode
  32042. */
  32043. class HemisphereLightNode extends AnalyticLightNode {
  32044. static get type() {
  32045. return 'HemisphereLightNode';
  32046. }
  32047. /**
  32048. * Constructs a new hemisphere light node.
  32049. *
  32050. * @param {HemisphereLight?} [light=null] - The hemisphere light source.
  32051. */
  32052. constructor( light = null ) {
  32053. super( light );
  32054. /**
  32055. * Uniform node representing the light's position.
  32056. *
  32057. * @type {UniformNode<vec3>}
  32058. */
  32059. this.lightPositionNode = lightPosition( light );
  32060. /**
  32061. * A node representing the light's direction.
  32062. *
  32063. * @type {Node<vec3>}
  32064. */
  32065. this.lightDirectionNode = this.lightPositionNode.normalize();
  32066. /**
  32067. * Uniform node representing the light's ground color.
  32068. *
  32069. * @type {UniformNode<vec3>}
  32070. */
  32071. this.groundColorNode = uniform( new Color() ).setGroup( renderGroup );
  32072. }
  32073. /**
  32074. * Overwritten to updated hemisphere light specific uniforms.
  32075. *
  32076. * @param {NodeFrame} frame - A reference to the current node frame.
  32077. */
  32078. update( frame ) {
  32079. const { light } = this;
  32080. super.update( frame );
  32081. this.lightPositionNode.object3d = light;
  32082. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  32083. }
  32084. setup( builder ) {
  32085. const { colorNode, groundColorNode, lightDirectionNode } = this;
  32086. const dotNL = normalView.dot( lightDirectionNode );
  32087. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  32088. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  32089. builder.context.irradiance.addAssign( irradiance );
  32090. }
  32091. }
  32092. /**
  32093. * Module for representing light probes as nodes.
  32094. *
  32095. * @augments AnalyticLightNode
  32096. */
  32097. class LightProbeNode extends AnalyticLightNode {
  32098. static get type() {
  32099. return 'LightProbeNode';
  32100. }
  32101. /**
  32102. * Constructs a new light probe node.
  32103. *
  32104. * @param {LightProbe?} [light=null] - The light probe.
  32105. */
  32106. constructor( light = null ) {
  32107. super( light );
  32108. const array = [];
  32109. for ( let i = 0; i < 9; i ++ ) array.push( new Vector3() );
  32110. /**
  32111. * Light probe represented as a uniform of spherical harmonics.
  32112. *
  32113. * @type {UniformArrayNode}
  32114. */
  32115. this.lightProbe = uniformArray( array );
  32116. }
  32117. /**
  32118. * Overwritten to updated light probe specific uniforms.
  32119. *
  32120. * @param {NodeFrame} frame - A reference to the current node frame.
  32121. */
  32122. update( frame ) {
  32123. const { light } = this;
  32124. super.update( frame );
  32125. //
  32126. for ( let i = 0; i < 9; i ++ ) {
  32127. this.lightProbe.array[ i ].copy( light.sh.coefficients[ i ] ).multiplyScalar( light.intensity );
  32128. }
  32129. }
  32130. setup( builder ) {
  32131. const irradiance = getShIrradianceAt( normalWorld, this.lightProbe );
  32132. builder.context.irradiance.addAssign( irradiance );
  32133. }
  32134. }
  32135. /**
  32136. * Base class for node parsers. A derived parser must be implemented
  32137. * for each supported native shader language.
  32138. */
  32139. class NodeParser {
  32140. /**
  32141. * The method parses the given native code an returns a node function.
  32142. *
  32143. * @abstract
  32144. * @param {String} source - The native shader code.
  32145. * @return {NodeFunction} A node function.
  32146. */
  32147. parseFunction( /*source*/ ) {
  32148. console.warn( 'Abstract function.' );
  32149. }
  32150. }
  32151. /**
  32152. * Base class for node functions. A derived module must be implemented
  32153. * for each supported native shader language. Similar to other `Node*` modules,
  32154. * this class is only relevant during the building process and not used
  32155. * in user-level code.
  32156. */
  32157. class NodeFunction {
  32158. /**
  32159. * Constructs a new node function.
  32160. *
  32161. * @param {String} type - The node type. This type is the return type of the node function.
  32162. * @param {Array<NodeFunctionInput>} inputs - The function's inputs.
  32163. * @param {String} [name=''] - The function's name.
  32164. * @param {String} [precision=''] - The precision qualifier.
  32165. */
  32166. constructor( type, inputs, name = '', precision = '' ) {
  32167. /**
  32168. * The node type. This type is the return type of the node function.
  32169. *
  32170. * @type {String}
  32171. */
  32172. this.type = type;
  32173. /**
  32174. * The function's inputs.
  32175. *
  32176. * @type {Array<NodeFunctionInput>}
  32177. */
  32178. this.inputs = inputs;
  32179. /**
  32180. * The name of the uniform.
  32181. *
  32182. * @type {String}
  32183. * @default ''
  32184. */
  32185. this.name = name;
  32186. /**
  32187. * The precision qualifier.
  32188. *
  32189. * @type {String}
  32190. * @default ''
  32191. */
  32192. this.precision = precision;
  32193. }
  32194. /**
  32195. * This method returns the native code of the node function.
  32196. *
  32197. * @abstract
  32198. * @param {String} name - The function's name.
  32199. * @return {String} A shader code.
  32200. */
  32201. getCode( /*name = this.name*/ ) {
  32202. console.warn( 'Abstract function.' );
  32203. }
  32204. }
  32205. NodeFunction.isNodeFunction = true;
  32206. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  32207. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  32208. const pragmaMain = '#pragma main';
  32209. const parse$1 = ( source ) => {
  32210. source = source.trim();
  32211. const pragmaMainIndex = source.indexOf( pragmaMain );
  32212. const mainCode = pragmaMainIndex !== -1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  32213. const declaration = mainCode.match( declarationRegexp$1 );
  32214. if ( declaration !== null && declaration.length === 5 ) {
  32215. // tokenizer
  32216. const inputsCode = declaration[ 4 ];
  32217. const propsMatches = [];
  32218. let nameMatch = null;
  32219. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  32220. propsMatches.push( nameMatch );
  32221. }
  32222. // parser
  32223. const inputs = [];
  32224. let i = 0;
  32225. while ( i < propsMatches.length ) {
  32226. const isConst = propsMatches[ i ][ 0 ] === 'const';
  32227. if ( isConst === true ) {
  32228. i ++;
  32229. }
  32230. let qualifier = propsMatches[ i ][ 0 ];
  32231. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  32232. i ++;
  32233. } else {
  32234. qualifier = '';
  32235. }
  32236. const type = propsMatches[ i ++ ][ 0 ];
  32237. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  32238. if ( Number.isNaN( count ) === false ) i ++;
  32239. else count = null;
  32240. const name = propsMatches[ i ++ ][ 0 ];
  32241. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  32242. }
  32243. //
  32244. const blockCode = mainCode.substring( declaration[ 0 ].length );
  32245. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  32246. const type = declaration[ 2 ];
  32247. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  32248. const headerCode = pragmaMainIndex !== -1 ? source.slice( 0, pragmaMainIndex ) : '';
  32249. return {
  32250. type,
  32251. inputs,
  32252. name,
  32253. precision,
  32254. inputsCode,
  32255. blockCode,
  32256. headerCode
  32257. };
  32258. } else {
  32259. throw new Error( 'FunctionNode: Function is not a GLSL code.' );
  32260. }
  32261. };
  32262. /**
  32263. * This class represents a GLSL node function.
  32264. *
  32265. * @augments NodeFunction
  32266. */
  32267. class GLSLNodeFunction extends NodeFunction {
  32268. /**
  32269. * Constructs a new GLSL node function.
  32270. *
  32271. * @param {String} source - The GLSL source.
  32272. */
  32273. constructor( source ) {
  32274. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  32275. super( type, inputs, name, precision );
  32276. this.inputsCode = inputsCode;
  32277. this.blockCode = blockCode;
  32278. this.headerCode = headerCode;
  32279. }
  32280. /**
  32281. * This method returns the GLSL code of the node function.
  32282. *
  32283. * @param {String} [name=this.name] - The function's name.
  32284. * @return {String} The shader code.
  32285. */
  32286. getCode( name = this.name ) {
  32287. let code;
  32288. const blockCode = this.blockCode;
  32289. if ( blockCode !== '' ) {
  32290. const { type, inputsCode, headerCode, precision } = this;
  32291. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  32292. if ( precision !== '' ) {
  32293. declarationCode = `${ precision } ${ declarationCode }`;
  32294. }
  32295. code = headerCode + declarationCode + blockCode;
  32296. } else {
  32297. // interface function
  32298. code = '';
  32299. }
  32300. return code;
  32301. }
  32302. }
  32303. /**
  32304. * A GLSL node parser.
  32305. *
  32306. * @augments NodeParser
  32307. */
  32308. class GLSLNodeParser extends NodeParser {
  32309. /**
  32310. * The method parses the given GLSL code an returns a node function.
  32311. *
  32312. * @param {String} source - The GLSL code.
  32313. * @return {GLSLNodeFunction} A node function.
  32314. */
  32315. parseFunction( source ) {
  32316. return new GLSLNodeFunction( source );
  32317. }
  32318. }
  32319. const _outputNodeMap = new WeakMap();
  32320. const _chainKeys$2 = [];
  32321. const _cacheKeyValues = [];
  32322. /**
  32323. * This renderer module manages node-related objects and is the
  32324. * primary interface between the renderer and the node system.
  32325. *
  32326. * @private
  32327. * @augments DataMap
  32328. */
  32329. class Nodes extends DataMap {
  32330. /**
  32331. * Constructs a new nodes management component.
  32332. *
  32333. * @param {Renderer} renderer - The renderer.
  32334. * @param {Backend} backend - The renderer's backend.
  32335. */
  32336. constructor( renderer, backend ) {
  32337. super();
  32338. /**
  32339. * The renderer.
  32340. *
  32341. * @type {Renderer}
  32342. */
  32343. this.renderer = renderer;
  32344. /**
  32345. * The renderer's backend.
  32346. *
  32347. * @type {Backend}
  32348. */
  32349. this.backend = backend;
  32350. /**
  32351. * The node frame.
  32352. *
  32353. * @type {Renderer}
  32354. */
  32355. this.nodeFrame = new NodeFrame();
  32356. /**
  32357. * A cache for managing node builder states.
  32358. *
  32359. * @type {Map<Number,NodeBuilderState>}
  32360. */
  32361. this.nodeBuilderCache = new Map();
  32362. /**
  32363. * A cache for managing data cache key data.
  32364. *
  32365. * @type {ChainMap}
  32366. */
  32367. this.callHashCache = new ChainMap();
  32368. /**
  32369. * A cache for managing node uniforms group data.
  32370. *
  32371. * @type {ChainMap}
  32372. */
  32373. this.groupsData = new ChainMap();
  32374. /**
  32375. * A cache for managing node objects of
  32376. * scene properties like fog or environments.
  32377. *
  32378. * @type {Object<String,WeakMap>}
  32379. */
  32380. this.cacheLib = {};
  32381. }
  32382. /**
  32383. * Returns `true` if the given node uniforms group must be updated or not.
  32384. *
  32385. * @param {NodeUniformsGroup} nodeUniformsGroup - The node uniforms group.
  32386. * @return {Boolean} Whether the node uniforms group requires an update or not.
  32387. */
  32388. updateGroup( nodeUniformsGroup ) {
  32389. const groupNode = nodeUniformsGroup.groupNode;
  32390. const name = groupNode.name;
  32391. // objectGroup is always updated
  32392. if ( name === objectGroup.name ) return true;
  32393. // renderGroup is updated once per render/compute call
  32394. if ( name === renderGroup.name ) {
  32395. const uniformsGroupData = this.get( nodeUniformsGroup );
  32396. const renderId = this.nodeFrame.renderId;
  32397. if ( uniformsGroupData.renderId !== renderId ) {
  32398. uniformsGroupData.renderId = renderId;
  32399. return true;
  32400. }
  32401. return false;
  32402. }
  32403. // frameGroup is updated once per frame
  32404. if ( name === frameGroup.name ) {
  32405. const uniformsGroupData = this.get( nodeUniformsGroup );
  32406. const frameId = this.nodeFrame.frameId;
  32407. if ( uniformsGroupData.frameId !== frameId ) {
  32408. uniformsGroupData.frameId = frameId;
  32409. return true;
  32410. }
  32411. return false;
  32412. }
  32413. // other groups are updated just when groupNode.needsUpdate is true
  32414. _chainKeys$2[ 0 ] = groupNode;
  32415. _chainKeys$2[ 1 ] = nodeUniformsGroup;
  32416. let groupData = this.groupsData.get( _chainKeys$2 );
  32417. if ( groupData === undefined ) this.groupsData.set( _chainKeys$2, groupData = {} );
  32418. _chainKeys$2.length = 0;
  32419. if ( groupData.version !== groupNode.version ) {
  32420. groupData.version = groupNode.version;
  32421. return true;
  32422. }
  32423. return false;
  32424. }
  32425. /**
  32426. * Returns the cache key for the given render object.
  32427. *
  32428. * @param {RenderObject} renderObject - The render object.
  32429. * @return {Number} The cache key.
  32430. */
  32431. getForRenderCacheKey( renderObject ) {
  32432. return renderObject.initialCacheKey;
  32433. }
  32434. /**
  32435. * Returns a node builder state for the given render object.
  32436. *
  32437. * @param {RenderObject} renderObject - The render object.
  32438. * @return {NodeBuilderState} The node builder state.
  32439. */
  32440. getForRender( renderObject ) {
  32441. const renderObjectData = this.get( renderObject );
  32442. let nodeBuilderState = renderObjectData.nodeBuilderState;
  32443. if ( nodeBuilderState === undefined ) {
  32444. const { nodeBuilderCache } = this;
  32445. const cacheKey = this.getForRenderCacheKey( renderObject );
  32446. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  32447. if ( nodeBuilderState === undefined ) {
  32448. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  32449. nodeBuilder.scene = renderObject.scene;
  32450. nodeBuilder.material = renderObject.material;
  32451. nodeBuilder.camera = renderObject.camera;
  32452. nodeBuilder.context.material = renderObject.material;
  32453. nodeBuilder.lightsNode = renderObject.lightsNode;
  32454. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  32455. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  32456. nodeBuilder.clippingContext = renderObject.clippingContext;
  32457. nodeBuilder.build();
  32458. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  32459. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  32460. }
  32461. nodeBuilderState.usedTimes ++;
  32462. renderObjectData.nodeBuilderState = nodeBuilderState;
  32463. }
  32464. return nodeBuilderState;
  32465. }
  32466. /**
  32467. * Deletes the given object from the internal data map
  32468. *
  32469. * @param {Any} object - The object to delete.
  32470. * @return {Object?} The deleted dictionary.
  32471. */
  32472. delete( object ) {
  32473. if ( object.isRenderObject ) {
  32474. const nodeBuilderState = this.get( object ).nodeBuilderState;
  32475. nodeBuilderState.usedTimes --;
  32476. if ( nodeBuilderState.usedTimes === 0 ) {
  32477. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  32478. }
  32479. }
  32480. return super.delete( object );
  32481. }
  32482. /**
  32483. * Returns a node builder state for the given compute node.
  32484. *
  32485. * @param {Node} computeNode - The compute node.
  32486. * @return {NodeBuilderState} The node builder state.
  32487. */
  32488. getForCompute( computeNode ) {
  32489. const computeData = this.get( computeNode );
  32490. let nodeBuilderState = computeData.nodeBuilderState;
  32491. if ( nodeBuilderState === undefined ) {
  32492. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  32493. nodeBuilder.build();
  32494. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  32495. computeData.nodeBuilderState = nodeBuilderState;
  32496. }
  32497. return nodeBuilderState;
  32498. }
  32499. /**
  32500. * Creates a node builder state for the given node builder.
  32501. *
  32502. * @private
  32503. * @param {NodeBuilder} nodeBuilder - The node builder.
  32504. * @return {NodeBuilderState} The node builder state.
  32505. */
  32506. _createNodeBuilderState( nodeBuilder ) {
  32507. return new NodeBuilderState(
  32508. nodeBuilder.vertexShader,
  32509. nodeBuilder.fragmentShader,
  32510. nodeBuilder.computeShader,
  32511. nodeBuilder.getAttributesArray(),
  32512. nodeBuilder.getBindings(),
  32513. nodeBuilder.updateNodes,
  32514. nodeBuilder.updateBeforeNodes,
  32515. nodeBuilder.updateAfterNodes,
  32516. nodeBuilder.observer,
  32517. nodeBuilder.transforms
  32518. );
  32519. }
  32520. /**
  32521. * Returns an environment node for the current configured
  32522. * scene environment.
  32523. *
  32524. * @param {Scene} scene - The scene.
  32525. * @return {Node} A node representing the current scene environment.
  32526. */
  32527. getEnvironmentNode( scene ) {
  32528. this.updateEnvironment( scene );
  32529. let environmentNode = null;
  32530. if ( scene.environmentNode && scene.environmentNode.isNode ) {
  32531. environmentNode = scene.environmentNode;
  32532. } else {
  32533. const sceneData = this.get( scene );
  32534. if ( sceneData.environmentNode ) {
  32535. environmentNode = sceneData.environmentNode;
  32536. }
  32537. }
  32538. return environmentNode;
  32539. }
  32540. /**
  32541. * Returns a background node for the current configured
  32542. * scene background.
  32543. *
  32544. * @param {Scene} scene - The scene.
  32545. * @return {Node} A node representing the current scene background.
  32546. */
  32547. getBackgroundNode( scene ) {
  32548. this.updateBackground( scene );
  32549. let backgroundNode = null;
  32550. if ( scene.backgroundNode && scene.backgroundNode.isNode ) {
  32551. backgroundNode = scene.backgroundNode;
  32552. } else {
  32553. const sceneData = this.get( scene );
  32554. if ( sceneData.backgroundNode ) {
  32555. backgroundNode = sceneData.backgroundNode;
  32556. }
  32557. }
  32558. return backgroundNode;
  32559. }
  32560. /**
  32561. * Returns a fog node for the current configured scene fog.
  32562. *
  32563. * @param {Scene} scene - The scene.
  32564. * @return {Node} A node representing the current scene fog.
  32565. */
  32566. getFogNode( scene ) {
  32567. this.updateFog( scene );
  32568. return scene.fogNode || this.get( scene ).fogNode || null;
  32569. }
  32570. /**
  32571. * Returns a cache key for the given scene and lights node.
  32572. * This key is used by `RenderObject` as a part of the dynamic
  32573. * cache key (a key that must be checked every time the render
  32574. * objects is drawn).
  32575. *
  32576. * @param {Scene} scene - The scene.
  32577. * @param {LightsNode} lightsNode - The lights node.
  32578. * @return {Number} The cache key.
  32579. */
  32580. getCacheKey( scene, lightsNode ) {
  32581. _chainKeys$2[ 0 ] = scene;
  32582. _chainKeys$2[ 1 ] = lightsNode;
  32583. const callId = this.renderer.info.calls;
  32584. const cacheKeyData = this.callHashCache.get( _chainKeys$2 ) || {};
  32585. if ( cacheKeyData.callId !== callId ) {
  32586. const environmentNode = this.getEnvironmentNode( scene );
  32587. const fogNode = this.getFogNode( scene );
  32588. if ( lightsNode ) _cacheKeyValues.push( lightsNode.getCacheKey( true ) );
  32589. if ( environmentNode ) _cacheKeyValues.push( environmentNode.getCacheKey() );
  32590. if ( fogNode ) _cacheKeyValues.push( fogNode.getCacheKey() );
  32591. _cacheKeyValues.push( this.renderer.shadowMap.enabled ? 1 : 0 );
  32592. cacheKeyData.callId = callId;
  32593. cacheKeyData.cacheKey = hashArray( _cacheKeyValues );
  32594. this.callHashCache.set( _chainKeys$2, cacheKeyData );
  32595. _cacheKeyValues.length = 0;
  32596. }
  32597. _chainKeys$2.length = 0;
  32598. return cacheKeyData.cacheKey;
  32599. }
  32600. /**
  32601. * A boolean that indicates whether tone mapping should be enabled
  32602. * or not.
  32603. *
  32604. * @type {Boolean}
  32605. */
  32606. get isToneMappingState() {
  32607. return this.renderer.getRenderTarget() ? false : true;
  32608. }
  32609. /**
  32610. * If a scene background is configured, this method makes sure to
  32611. * represent the background with a corresponding node-based implementation.
  32612. *
  32613. * @param {Scene} scene - The scene.
  32614. */
  32615. updateBackground( scene ) {
  32616. const sceneData = this.get( scene );
  32617. const background = scene.background;
  32618. if ( background ) {
  32619. const forceUpdate = ( scene.backgroundBlurriness === 0 && sceneData.backgroundBlurriness > 0 ) || ( scene.backgroundBlurriness > 0 && sceneData.backgroundBlurriness === 0 );
  32620. if ( sceneData.background !== background || forceUpdate ) {
  32621. const backgroundNode = this.getCacheNode( 'background', background, () => {
  32622. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping || background.mapping === CubeUVReflectionMapping ) ) {
  32623. if ( scene.backgroundBlurriness > 0 || background.mapping === CubeUVReflectionMapping ) {
  32624. return pmremTexture( background );
  32625. } else {
  32626. let envMap;
  32627. if ( background.isCubeTexture === true ) {
  32628. envMap = cubeTexture( background );
  32629. } else {
  32630. envMap = texture( background );
  32631. }
  32632. return cubeMapNode( envMap );
  32633. }
  32634. } else if ( background.isTexture === true ) {
  32635. return texture( background, screenUV.flipY() ).setUpdateMatrix( true );
  32636. } else if ( background.isColor !== true ) {
  32637. console.error( 'WebGPUNodes: Unsupported background configuration.', background );
  32638. }
  32639. }, forceUpdate );
  32640. sceneData.backgroundNode = backgroundNode;
  32641. sceneData.background = background;
  32642. sceneData.backgroundBlurriness = scene.backgroundBlurriness;
  32643. }
  32644. } else if ( sceneData.backgroundNode ) {
  32645. delete sceneData.backgroundNode;
  32646. delete sceneData.background;
  32647. }
  32648. }
  32649. /**
  32650. * This method is part of the caching of nodes which are used to represents the
  32651. * scene's background, fog or environment.
  32652. *
  32653. * @param {String} type - The type of object to cache.
  32654. * @param {Object} object - The object.
  32655. * @param {Function} callback - A callback that produces a node representation for the given object.
  32656. * @param {Boolean} [forceUpdate=false] - Whether an update should be enforced or not.
  32657. * @return {Node} The node representation.
  32658. */
  32659. getCacheNode( type, object, callback, forceUpdate = false ) {
  32660. const nodeCache = this.cacheLib[ type ] || ( this.cacheLib[ type ] = new WeakMap() );
  32661. let node = nodeCache.get( object );
  32662. if ( node === undefined || forceUpdate ) {
  32663. node = callback();
  32664. nodeCache.set( object, node );
  32665. }
  32666. return node;
  32667. }
  32668. /**
  32669. * If a scene fog is configured, this method makes sure to
  32670. * represent the fog with a corresponding node-based implementation.
  32671. *
  32672. * @param {Scene} scene - The scene.
  32673. */
  32674. updateFog( scene ) {
  32675. const sceneData = this.get( scene );
  32676. const sceneFog = scene.fog;
  32677. if ( sceneFog ) {
  32678. if ( sceneData.fog !== sceneFog ) {
  32679. const fogNode = this.getCacheNode( 'fog', sceneFog, () => {
  32680. if ( sceneFog.isFogExp2 ) {
  32681. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  32682. const density = reference( 'density', 'float', sceneFog ).setGroup( renderGroup );
  32683. return fog( color, densityFogFactor( density ) );
  32684. } else if ( sceneFog.isFog ) {
  32685. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  32686. const near = reference( 'near', 'float', sceneFog ).setGroup( renderGroup );
  32687. const far = reference( 'far', 'float', sceneFog ).setGroup( renderGroup );
  32688. return fog( color, rangeFogFactor( near, far ) );
  32689. } else {
  32690. console.error( 'THREE.Renderer: Unsupported fog configuration.', sceneFog );
  32691. }
  32692. } );
  32693. sceneData.fogNode = fogNode;
  32694. sceneData.fog = sceneFog;
  32695. }
  32696. } else {
  32697. delete sceneData.fogNode;
  32698. delete sceneData.fog;
  32699. }
  32700. }
  32701. /**
  32702. * If a scene environment is configured, this method makes sure to
  32703. * represent the environment with a corresponding node-based implementation.
  32704. *
  32705. * @param {Scene} scene - The scene.
  32706. */
  32707. updateEnvironment( scene ) {
  32708. const sceneData = this.get( scene );
  32709. const environment = scene.environment;
  32710. if ( environment ) {
  32711. if ( sceneData.environment !== environment ) {
  32712. const environmentNode = this.getCacheNode( 'environment', environment, () => {
  32713. if ( environment.isCubeTexture === true ) {
  32714. return cubeTexture( environment );
  32715. } else if ( environment.isTexture === true ) {
  32716. return texture( environment );
  32717. } else {
  32718. console.error( 'Nodes: Unsupported environment configuration.', environment );
  32719. }
  32720. } );
  32721. sceneData.environmentNode = environmentNode;
  32722. sceneData.environment = environment;
  32723. }
  32724. } else if ( sceneData.environmentNode ) {
  32725. delete sceneData.environmentNode;
  32726. delete sceneData.environment;
  32727. }
  32728. }
  32729. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  32730. const nodeFrame = this.nodeFrame;
  32731. nodeFrame.renderer = renderer;
  32732. nodeFrame.scene = scene;
  32733. nodeFrame.object = object;
  32734. nodeFrame.camera = camera;
  32735. nodeFrame.material = material;
  32736. return nodeFrame;
  32737. }
  32738. getNodeFrameForRender( renderObject ) {
  32739. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  32740. }
  32741. /**
  32742. * Returns the current output cache key.
  32743. *
  32744. * @return {String} The output cache key.
  32745. */
  32746. getOutputCacheKey() {
  32747. const renderer = this.renderer;
  32748. return renderer.toneMapping + ',' + renderer.currentColorSpace;
  32749. }
  32750. /**
  32751. * Checks if the output configuration (tone mapping and color space) for
  32752. * the given target has changed.
  32753. *
  32754. * @param {Texture} outputTarget - The output target.
  32755. * @return {Boolean} Whether the output configuration has changed or not.
  32756. */
  32757. hasOutputChange( outputTarget ) {
  32758. const cacheKey = _outputNodeMap.get( outputTarget );
  32759. return cacheKey !== this.getOutputCacheKey();
  32760. }
  32761. /**
  32762. * Returns a node that represents the output configuration (tone mapping and
  32763. * color space) for the current target.
  32764. *
  32765. * @param {Texture} outputTarget - The output target.
  32766. * @return {Node} The output node.
  32767. */
  32768. getOutputNode( outputTarget ) {
  32769. const renderer = this.renderer;
  32770. const cacheKey = this.getOutputCacheKey();
  32771. const output = texture( outputTarget, screenUV ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  32772. _outputNodeMap.set( outputTarget, cacheKey );
  32773. return output;
  32774. }
  32775. /**
  32776. * Triggers the call of `updateBefore()` methods
  32777. * for all nodes of the given render object.
  32778. *
  32779. * @param {RenderObject} renderObject - The render object.
  32780. */
  32781. updateBefore( renderObject ) {
  32782. const nodeBuilder = renderObject.getNodeBuilderState();
  32783. for ( const node of nodeBuilder.updateBeforeNodes ) {
  32784. // update frame state for each node
  32785. this.getNodeFrameForRender( renderObject ).updateBeforeNode( node );
  32786. }
  32787. }
  32788. /**
  32789. * Triggers the call of `updateAfter()` methods
  32790. * for all nodes of the given render object.
  32791. *
  32792. * @param {RenderObject} renderObject - The render object.
  32793. */
  32794. updateAfter( renderObject ) {
  32795. const nodeBuilder = renderObject.getNodeBuilderState();
  32796. for ( const node of nodeBuilder.updateAfterNodes ) {
  32797. // update frame state for each node
  32798. this.getNodeFrameForRender( renderObject ).updateAfterNode( node );
  32799. }
  32800. }
  32801. /**
  32802. * Triggers the call of `update()` methods
  32803. * for all nodes of the given compute node.
  32804. *
  32805. * @param {Node} computeNode - The compute node.
  32806. */
  32807. updateForCompute( computeNode ) {
  32808. const nodeFrame = this.getNodeFrame();
  32809. const nodeBuilder = this.getForCompute( computeNode );
  32810. for ( const node of nodeBuilder.updateNodes ) {
  32811. nodeFrame.updateNode( node );
  32812. }
  32813. }
  32814. /**
  32815. * Triggers the call of `update()` methods
  32816. * for all nodes of the given compute node.
  32817. *
  32818. * @param {RenderObject} renderObject - The render object.
  32819. */
  32820. updateForRender( renderObject ) {
  32821. const nodeFrame = this.getNodeFrameForRender( renderObject );
  32822. const nodeBuilder = renderObject.getNodeBuilderState();
  32823. for ( const node of nodeBuilder.updateNodes ) {
  32824. nodeFrame.updateNode( node );
  32825. }
  32826. }
  32827. /**
  32828. * Returns `true` if the given render object requires a refresh.
  32829. *
  32830. * @param {RenderObject} renderObject - The render object.
  32831. * @return {Boolean} Whether the given render object requires a refresh or not.
  32832. */
  32833. needsRefresh( renderObject ) {
  32834. const nodeFrame = this.getNodeFrameForRender( renderObject );
  32835. const monitor = renderObject.getMonitor();
  32836. return monitor.needsRefresh( renderObject, nodeFrame );
  32837. }
  32838. /**
  32839. * Frees the internal resources.
  32840. */
  32841. dispose() {
  32842. super.dispose();
  32843. this.nodeFrame = new NodeFrame();
  32844. this.nodeBuilderCache = new Map();
  32845. this.cacheLib = {};
  32846. }
  32847. }
  32848. const _plane = /*@__PURE__*/ new Plane();
  32849. /**
  32850. * Represents the state that is used to perform clipping via clipping planes.
  32851. * There is a default clipping context for each render context. When the
  32852. * scene holds instances of `ClippingGroup`, there will be a context for each
  32853. * group.
  32854. *
  32855. * @private
  32856. */
  32857. class ClippingContext {
  32858. /**
  32859. * Constructs a new clipping context.
  32860. *
  32861. * @param {ClippingContext?} [parentContext=null] - A reference to the parent clipping context.
  32862. */
  32863. constructor( parentContext = null ) {
  32864. /**
  32865. * The clipping context's version.
  32866. *
  32867. * @type {Number}
  32868. * @readonly
  32869. */
  32870. this.version = 0;
  32871. /**
  32872. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  32873. *
  32874. * @type {Boolean?}
  32875. * @default null
  32876. */
  32877. this.clipIntersection = null;
  32878. /**
  32879. * The clipping context's cache key.
  32880. *
  32881. * @type {String}
  32882. */
  32883. this.cacheKey = '';
  32884. /**
  32885. * Whether the shadow pass is active or not.
  32886. *
  32887. * @type {Boolean}
  32888. * @default false
  32889. */
  32890. this.shadowPass = false;
  32891. /**
  32892. * The view normal matrix.
  32893. *
  32894. * @type {Matrix3}
  32895. */
  32896. this.viewNormalMatrix = new Matrix3();
  32897. /**
  32898. * Internal cache for maintaining clipping contexts.
  32899. *
  32900. * @type {WeakMap<ClippingGroup,ClippingContext>}
  32901. */
  32902. this.clippingGroupContexts = new WeakMap();
  32903. /**
  32904. * The intersection planes.
  32905. *
  32906. * @type {Array<Vector4>}
  32907. */
  32908. this.intersectionPlanes = [];
  32909. /**
  32910. * The intersection planes.
  32911. *
  32912. * @type {Array<Vector4>}
  32913. */
  32914. this.unionPlanes = [];
  32915. /**
  32916. * The version of the clipping context's parent context.
  32917. *
  32918. * @type {Number?}
  32919. * @readonly
  32920. */
  32921. this.parentVersion = null;
  32922. if ( parentContext !== null ) {
  32923. this.viewNormalMatrix = parentContext.viewNormalMatrix;
  32924. this.clippingGroupContexts = parentContext.clippingGroupContexts;
  32925. this.shadowPass = parentContext.shadowPass;
  32926. this.viewMatrix = parentContext.viewMatrix;
  32927. }
  32928. }
  32929. /**
  32930. * Projects the given source clipping planes and writes the result into the
  32931. * destination array.
  32932. *
  32933. * @param {Array<Plane>} source - The source clipping planes.
  32934. * @param {Array<Vector4>} destination - The destination.
  32935. * @param {Number} offset - The offset.
  32936. */
  32937. projectPlanes( source, destination, offset ) {
  32938. const l = source.length;
  32939. for ( let i = 0; i < l; i ++ ) {
  32940. _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, this.viewNormalMatrix );
  32941. const v = destination[ offset + i ];
  32942. const normal = _plane.normal;
  32943. v.x = - normal.x;
  32944. v.y = - normal.y;
  32945. v.z = - normal.z;
  32946. v.w = _plane.constant;
  32947. }
  32948. }
  32949. /**
  32950. * Updates the root clipping context of a scene.
  32951. *
  32952. * @param {Scene} scene - The scene.
  32953. * @param {Camera} camera - The camera that is used to render the scene.
  32954. */
  32955. updateGlobal( scene, camera ) {
  32956. this.shadowPass = ( scene.overrideMaterial !== null && scene.overrideMaterial.isShadowPassMaterial );
  32957. this.viewMatrix = camera.matrixWorldInverse;
  32958. this.viewNormalMatrix.getNormalMatrix( this.viewMatrix );
  32959. }
  32960. /**
  32961. * Updates the clipping context.
  32962. *
  32963. * @param {ClippingContext} parentContext - The parent context.
  32964. * @param {ClippingGroup} clippingGroup - The clipping group this context belongs to.
  32965. */
  32966. update( parentContext, clippingGroup ) {
  32967. let update = false;
  32968. if ( parentContext.version !== this.parentVersion ) {
  32969. this.intersectionPlanes = Array.from( parentContext.intersectionPlanes );
  32970. this.unionPlanes = Array.from( parentContext.unionPlanes );
  32971. this.parentVersion = parentContext.version;
  32972. }
  32973. if ( this.clipIntersection !== clippingGroup.clipIntersection ) {
  32974. this.clipIntersection = clippingGroup.clipIntersection;
  32975. if ( this.clipIntersection ) {
  32976. this.unionPlanes.length = parentContext.unionPlanes.length;
  32977. } else {
  32978. this.intersectionPlanes.length = parentContext.intersectionPlanes.length;
  32979. }
  32980. }
  32981. const srcClippingPlanes = clippingGroup.clippingPlanes;
  32982. const l = srcClippingPlanes.length;
  32983. let dstClippingPlanes;
  32984. let offset;
  32985. if ( this.clipIntersection ) {
  32986. dstClippingPlanes = this.intersectionPlanes;
  32987. offset = parentContext.intersectionPlanes.length;
  32988. } else {
  32989. dstClippingPlanes = this.unionPlanes;
  32990. offset = parentContext.unionPlanes.length;
  32991. }
  32992. if ( dstClippingPlanes.length !== offset + l ) {
  32993. dstClippingPlanes.length = offset + l;
  32994. for ( let i = 0; i < l; i ++ ) {
  32995. dstClippingPlanes[ offset + i ] = new Vector4();
  32996. }
  32997. update = true;
  32998. }
  32999. this.projectPlanes( srcClippingPlanes, dstClippingPlanes, offset );
  33000. if ( update ) {
  33001. this.version ++;
  33002. this.cacheKey = `${ this.intersectionPlanes.length }:${ this.unionPlanes.length }`;
  33003. }
  33004. }
  33005. /**
  33006. * Returns a clipping context for the given clipping group.
  33007. *
  33008. * @param {ClippingGroup} clippingGroup - The clipping group.
  33009. * @return {ClippingContext} The clipping context.
  33010. */
  33011. getGroupContext( clippingGroup ) {
  33012. if ( this.shadowPass && ! clippingGroup.clipShadows ) return this;
  33013. let context = this.clippingGroupContexts.get( clippingGroup );
  33014. if ( context === undefined ) {
  33015. context = new ClippingContext( this );
  33016. this.clippingGroupContexts.set( clippingGroup, context );
  33017. }
  33018. context.update( this, clippingGroup );
  33019. return context;
  33020. }
  33021. /**
  33022. * The count of union clipping planes.
  33023. *
  33024. * @type {Number}
  33025. * @readonly
  33026. */
  33027. get unionClippingCount() {
  33028. return this.unionPlanes.length;
  33029. }
  33030. }
  33031. /**
  33032. * This module is used to represent render bundles inside the renderer
  33033. * for further processing.
  33034. *
  33035. * @private
  33036. */
  33037. class RenderBundle {
  33038. /**
  33039. * Constructs a new bundle group.
  33040. *
  33041. * @param {BundleGroup} bundleGroup - The bundle group.
  33042. * @param {Camera} camera - The camera the bundle group is rendered with.
  33043. */
  33044. constructor( bundleGroup, camera ) {
  33045. this.bundleGroup = bundleGroup;
  33046. this.camera = camera;
  33047. }
  33048. }
  33049. const _chainKeys$1 = [];
  33050. /**
  33051. * This renderer module manages render bundles.
  33052. *
  33053. * @private
  33054. */
  33055. class RenderBundles {
  33056. /**
  33057. * Constructs a new render bundle management component.
  33058. */
  33059. constructor() {
  33060. /**
  33061. * A chain map for maintaining the render bundles.
  33062. *
  33063. * @type {ChainMap}
  33064. */
  33065. this.bundles = new ChainMap();
  33066. }
  33067. /**
  33068. * Returns a render bundle for the given bundle group and camera.
  33069. *
  33070. * @param {BundleGroup} bundleGroup - The bundle group.
  33071. * @param {Camera} camera - The camera the bundle group is rendered with.
  33072. * @return {RenderBundle} The render bundle.
  33073. */
  33074. get( bundleGroup, camera ) {
  33075. const bundles = this.bundles;
  33076. _chainKeys$1[ 0 ] = bundleGroup;
  33077. _chainKeys$1[ 1 ] = camera;
  33078. let bundle = bundles.get( _chainKeys$1 );
  33079. if ( bundle === undefined ) {
  33080. bundle = new RenderBundle( bundleGroup, camera );
  33081. bundles.set( _chainKeys$1, bundle );
  33082. }
  33083. _chainKeys$1.length = 0;
  33084. return bundle;
  33085. }
  33086. /**
  33087. * Frees all internal resources.
  33088. */
  33089. dispose() {
  33090. this.bundles = new ChainMap();
  33091. }
  33092. }
  33093. /**
  33094. * The purpose of a node library is to assign node implementations
  33095. * to existing library features. In `WebGPURenderer` lights, materials
  33096. * which are not based on `NodeMaterial` as well as tone mapping techniques
  33097. * are implemented with node-based modules.
  33098. *
  33099. * @private
  33100. */
  33101. class NodeLibrary {
  33102. /**
  33103. * Constructs a new node library.
  33104. */
  33105. constructor() {
  33106. /**
  33107. * A weak map that maps lights to light nodes.
  33108. *
  33109. * @type {WeakMap<Light.constructor,AnalyticLightNode.constructor>}
  33110. */
  33111. this.lightNodes = new WeakMap();
  33112. /**
  33113. * A map that maps materials to node materials.
  33114. *
  33115. * @type {Map<String,NodeMaterial.constructor>}
  33116. */
  33117. this.materialNodes = new Map();
  33118. /**
  33119. * A map that maps tone mapping techniques (constants)
  33120. * to tone mapping node functions.
  33121. *
  33122. * @type {Map<Number,Function>}
  33123. */
  33124. this.toneMappingNodes = new Map();
  33125. }
  33126. /**
  33127. * Returns a matching node material instance for the given material object.
  33128. *
  33129. * This method also assigns/copies the properties of the given material object
  33130. * to the node material. This is done to make sure the current material
  33131. * configuration carries over to the node version.
  33132. *
  33133. * @param {Material} material - A material.
  33134. * @return {NodeMaterial} The corresponding node material.
  33135. */
  33136. fromMaterial( material ) {
  33137. if ( material.isNodeMaterial ) return material;
  33138. let nodeMaterial = null;
  33139. const nodeMaterialClass = this.getMaterialNodeClass( material.type );
  33140. if ( nodeMaterialClass !== null ) {
  33141. nodeMaterial = new nodeMaterialClass();
  33142. for ( const key in material ) {
  33143. nodeMaterial[ key ] = material[ key ];
  33144. }
  33145. }
  33146. return nodeMaterial;
  33147. }
  33148. /**
  33149. * Adds a tone mapping node function for a tone mapping technique (constant).
  33150. *
  33151. * @param {Function} toneMappingNode - The tone mapping node function.
  33152. * @param {Number} toneMapping - The tone mapping.
  33153. */
  33154. addToneMapping( toneMappingNode, toneMapping ) {
  33155. this.addType( toneMappingNode, toneMapping, this.toneMappingNodes );
  33156. }
  33157. /**
  33158. * Returns a tone mapping node function for a tone mapping technique (constant).
  33159. *
  33160. * @param {Number} toneMapping - The tone mapping.
  33161. * @return {Function?} The tone mapping node function. Returns `null` if no node function is found.
  33162. */
  33163. getToneMappingFunction( toneMapping ) {
  33164. return this.toneMappingNodes.get( toneMapping ) || null;
  33165. }
  33166. /**
  33167. * Returns a node material class definition for a material type.
  33168. *
  33169. * @param {String} materialType - The material type.
  33170. * @return {NodeMaterial.constructor?} The node material class definition. Returns `null` if no node material is found.
  33171. */
  33172. getMaterialNodeClass( materialType ) {
  33173. return this.materialNodes.get( materialType ) || null;
  33174. }
  33175. /**
  33176. * Adds a node material class definition for a given material type.
  33177. *
  33178. * @param {NodeMaterial.constructor} materialNodeClass - The node material class definition.
  33179. * @param {String} materialClassType - The material type.
  33180. */
  33181. addMaterial( materialNodeClass, materialClassType ) {
  33182. this.addType( materialNodeClass, materialClassType, this.materialNodes );
  33183. }
  33184. /**
  33185. * Returns a light node class definition for a light class definition.
  33186. *
  33187. * @param {Light.constructor} light - The light class definition.
  33188. * @return {AnalyticLightNode.constructor?} The light node class definition. Returns `null` if no light node is found.
  33189. */
  33190. getLightNodeClass( light ) {
  33191. return this.lightNodes.get( light ) || null;
  33192. }
  33193. /**
  33194. * Adds a light node class definition for a given light class definition.
  33195. *
  33196. * @param {AnalyticLightNode.constructor} lightNodeClass - The light node class definition.
  33197. * @param {Light.constructor} lightClass - The light class definition.
  33198. */
  33199. addLight( lightNodeClass, lightClass ) {
  33200. this.addClass( lightNodeClass, lightClass, this.lightNodes );
  33201. }
  33202. /**
  33203. * Adds a node class definition for the given type to the provided type library.
  33204. *
  33205. * @param {Any} nodeClass - The node class definition.
  33206. * @param {Number|String} type - The object type.
  33207. * @param {Map} library - The type library.
  33208. */
  33209. addType( nodeClass, type, library ) {
  33210. if ( library.has( type ) ) {
  33211. console.warn( `Redefinition of node ${ type }` );
  33212. return;
  33213. }
  33214. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  33215. if ( typeof type === 'function' || typeof type === 'object' ) throw new Error( `Base class ${ type } is not a class.` );
  33216. library.set( type, nodeClass );
  33217. }
  33218. /**
  33219. * Adds a node class definition for the given class definition to the provided type library.
  33220. *
  33221. * @param {Any} nodeClass - The node class definition.
  33222. * @param {Any} baseClass - The class definition.
  33223. * @param {WeakMap} library - The type library.
  33224. */
  33225. addClass( nodeClass, baseClass, library ) {
  33226. if ( library.has( baseClass ) ) {
  33227. console.warn( `Redefinition of node ${ baseClass.name }` );
  33228. return;
  33229. }
  33230. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  33231. if ( typeof baseClass !== 'function' ) throw new Error( `Base class ${ baseClass.name } is not a class.` );
  33232. library.set( baseClass, nodeClass );
  33233. }
  33234. }
  33235. const _defaultLights = /*@__PURE__*/ new LightsNode();
  33236. const _chainKeys = [];
  33237. /**
  33238. * This renderer module manages the lights nodes which are unique
  33239. * per scene and camera combination.
  33240. *
  33241. * The lights node itself is later configured in the render list
  33242. * with the actual lights from the scene.
  33243. *
  33244. * @private
  33245. * @augments ChainMap
  33246. */
  33247. class Lighting extends ChainMap {
  33248. /**
  33249. * Constructs a lighting management component.
  33250. */
  33251. constructor() {
  33252. super();
  33253. }
  33254. /**
  33255. * Creates a new lights node for the given array of lights.
  33256. *
  33257. * @param {Array<Light>} lights - The render object.
  33258. * @return {LightsNode} The lights node.
  33259. */
  33260. createNode( lights = [] ) {
  33261. return new LightsNode().setLights( lights );
  33262. }
  33263. /**
  33264. * Returns a lights node for the given scene and camera.
  33265. *
  33266. * @param {Scene} scene - The scene.
  33267. * @param {Camera} camera - The camera.
  33268. * @return {LightsNode} The lights node.
  33269. */
  33270. getNode( scene, camera ) {
  33271. // ignore post-processing
  33272. if ( scene.isQuadMesh ) return _defaultLights;
  33273. _chainKeys[ 0 ] = scene;
  33274. _chainKeys[ 1 ] = camera;
  33275. let node = this.get( _chainKeys );
  33276. if ( node === undefined ) {
  33277. node = this.createNode();
  33278. this.set( _chainKeys, node );
  33279. }
  33280. _chainKeys.length = 0;
  33281. return node;
  33282. }
  33283. }
  33284. /**
  33285. * A special type of render target that is used when rendering
  33286. * with the WebXR Device API.
  33287. *
  33288. * @private
  33289. * @augments RenderTarget
  33290. */
  33291. class XRRenderTarget extends RenderTarget {
  33292. /**
  33293. * Constructs a new XR render target.
  33294. *
  33295. * @param {Number} [width=1] - The width of the render target.
  33296. * @param {Number} [height=1] - The height of the render target.
  33297. * @param {Object} [options={}] - The configuration options.
  33298. */
  33299. constructor( width = 1, height = 1, options = {} ) {
  33300. super( width, height, options );
  33301. /**
  33302. * This flag can be used for type testing.
  33303. *
  33304. * @type {Boolean}
  33305. * @readonly
  33306. * @default true
  33307. */
  33308. this.isXRRenderTarget = true;
  33309. /**
  33310. * Whether the attachments of the render target
  33311. * are defined by external textures. This flag is
  33312. * set to `true` when using the WebXR Layers API.
  33313. *
  33314. * @type {Boolean}
  33315. * @default false
  33316. */
  33317. this.hasExternalTextures = false;
  33318. /**
  33319. * Whether a depth buffer should automatically be allocated
  33320. * for this XR render target or not.
  33321. *
  33322. * Allocating a depth buffer is the default behavior of XR render
  33323. * targets. However, when using the WebXR Layers API, this flag
  33324. * must be set to `false` when the `ignoreDepthValues` property of
  33325. * the projection layers evaluates to `true`.
  33326. *
  33327. * Reference: {@link https://www.w3.org/TR/webxrlayers-1/#dom-xrprojectionlayer-ignoredepthvalues}.
  33328. *
  33329. * @type {Boolean}
  33330. * @default true
  33331. */
  33332. this.autoAllocateDepthBuffer = true;
  33333. }
  33334. copy( source ) {
  33335. super.copy( source );
  33336. this.hasExternalTextures = source.hasExternalTextures;
  33337. this.autoAllocateDepthBuffer = source.autoAllocateDepthBuffer;
  33338. return this;
  33339. }
  33340. }
  33341. const _cameraLPos = /*@__PURE__*/ new Vector3();
  33342. const _cameraRPos = /*@__PURE__*/ new Vector3();
  33343. /**
  33344. * The XR manager is built on top of the WebXR Device API to
  33345. * manage XR sessions with `WebGPURenderer`.
  33346. *
  33347. * XR is currently only supported with a WebGL 2 backend.
  33348. *
  33349. * @augments EventDispatcher
  33350. */
  33351. class XRManager extends EventDispatcher {
  33352. /**
  33353. * Constructs a new XR manager.
  33354. *
  33355. * @param {Renderer} renderer - The renderer.
  33356. */
  33357. constructor( renderer ) {
  33358. super();
  33359. /**
  33360. * This flag globally enables XR rendering.
  33361. *
  33362. * @type {Boolean}
  33363. * @default false
  33364. */
  33365. this.enabled = false;
  33366. /**
  33367. * Whether the XR device is currently presenting or not.
  33368. *
  33369. * @type {Boolean}
  33370. * @default false
  33371. * @readonly
  33372. */
  33373. this.isPresenting = false;
  33374. /**
  33375. * Whether the XR camera should automatically be updated or not.
  33376. *
  33377. * @type {Boolean}
  33378. * @default true
  33379. */
  33380. this.cameraAutoUpdate = true;
  33381. /**
  33382. * The renderer.
  33383. *
  33384. * @private
  33385. * @type {Renderer}
  33386. */
  33387. this._renderer = renderer;
  33388. // camera
  33389. /**
  33390. * Represents the camera for the left eye.
  33391. *
  33392. * @private
  33393. * @type {PerspectiveCamera}
  33394. */
  33395. this._cameraL = new PerspectiveCamera();
  33396. this._cameraL.viewport = new Vector4();
  33397. /**
  33398. * Represents the camera for the right eye.
  33399. *
  33400. * @private
  33401. * @type {PerspectiveCamera}
  33402. */
  33403. this._cameraR = new PerspectiveCamera();
  33404. this._cameraR.viewport = new Vector4();
  33405. /**
  33406. * A list of cameras used for rendering the XR views.
  33407. *
  33408. * @private
  33409. * @type {Array<Camera>}
  33410. */
  33411. this._cameras = [ this._cameraL, this._cameraR ];
  33412. /**
  33413. * The main XR camera.
  33414. *
  33415. * @private
  33416. * @type {ArrayCamera}
  33417. */
  33418. this._cameraXR = new ArrayCamera();
  33419. /**
  33420. * The current near value of the XR camera.
  33421. *
  33422. * @private
  33423. * @type {Number?}
  33424. * @default null
  33425. */
  33426. this._currentDepthNear = null;
  33427. /**
  33428. * The current far value of the XR camera.
  33429. *
  33430. * @private
  33431. * @type {Number?}
  33432. * @default null
  33433. */
  33434. this._currentDepthFar = null;
  33435. /**
  33436. * A list of WebXR controllers requested by the application.
  33437. *
  33438. * @private
  33439. * @type {Array<WebXRController>}
  33440. */
  33441. this._controllers = [];
  33442. /**
  33443. * A list of XR input source. Each input source belongs to
  33444. * an instance of WebXRController.
  33445. *
  33446. * @private
  33447. * @type {Array<XRInputSource?>}
  33448. */
  33449. this._controllerInputSources = [];
  33450. /**
  33451. * The current render target of the renderer.
  33452. *
  33453. * @private
  33454. * @type {RenderTarget?}
  33455. * @default null
  33456. */
  33457. this._currentRenderTarget = null;
  33458. /**
  33459. * The XR render target that represents the rendering destination
  33460. * during an active XR session.
  33461. *
  33462. * @private
  33463. * @type {RenderTarget?}
  33464. * @default null
  33465. */
  33466. this._xrRenderTarget = null;
  33467. /**
  33468. * The current animation context.
  33469. *
  33470. * @private
  33471. * @type {Window?}
  33472. * @default null
  33473. */
  33474. this._currentAnimationContext = null;
  33475. /**
  33476. * The current animation loop.
  33477. *
  33478. * @private
  33479. * @type {Function?}
  33480. * @default null
  33481. */
  33482. this._currentAnimationLoop = null;
  33483. /**
  33484. * The current pixel ratio.
  33485. *
  33486. * @private
  33487. * @type {Number?}
  33488. * @default null
  33489. */
  33490. this._currentPixelRatio = null;
  33491. /**
  33492. * The current size of the renderer's canvas
  33493. * in logical pixel unit.
  33494. *
  33495. * @private
  33496. * @type {Vector2}
  33497. */
  33498. this._currentSize = new Vector2();
  33499. /**
  33500. * The default event listener for handling events inside a XR session.
  33501. *
  33502. * @private
  33503. * @type {Function}
  33504. */
  33505. this._onSessionEvent = onSessionEvent.bind( this );
  33506. /**
  33507. * The event listener for handling the end of a XR session.
  33508. *
  33509. * @private
  33510. * @type {Function}
  33511. */
  33512. this._onSessionEnd = onSessionEnd.bind( this );
  33513. /**
  33514. * The event listener for handling the `inputsourceschange` event.
  33515. *
  33516. * @private
  33517. * @type {Function}
  33518. */
  33519. this._onInputSourcesChange = onInputSourcesChange.bind( this );
  33520. /**
  33521. * The animation loop which is used as a replacement for the default
  33522. * animation loop of the applicatio. It is only used when a XR session
  33523. * is active.
  33524. *
  33525. * @private
  33526. * @type {Function}
  33527. */
  33528. this._onAnimationFrame = onAnimationFrame.bind( this );
  33529. /**
  33530. * The current XR reference space.
  33531. *
  33532. * @private
  33533. * @type {XRReferenceSpace?}
  33534. * @default null
  33535. */
  33536. this._referenceSpace = null;
  33537. /**
  33538. * The current XR reference space type.
  33539. *
  33540. * @private
  33541. * @type {String}
  33542. * @default 'local-floor'
  33543. */
  33544. this._referenceSpaceType = 'local-floor';
  33545. /**
  33546. * A custom reference space defined by the application.
  33547. *
  33548. * @private
  33549. * @type {XRReferenceSpace?}
  33550. * @default null
  33551. */
  33552. this._customReferenceSpace = null;
  33553. /**
  33554. * The framebuffer scale factor.
  33555. *
  33556. * @private
  33557. * @type {Number}
  33558. * @default 1
  33559. */
  33560. this._framebufferScaleFactor = 1;
  33561. /**
  33562. * The foveation factor.
  33563. *
  33564. * @private
  33565. * @type {Number}
  33566. * @default 1
  33567. */
  33568. this._foveation = 1.0;
  33569. /**
  33570. * A reference to the current XR session.
  33571. *
  33572. * @private
  33573. * @type {XRSession?}
  33574. * @default null
  33575. */
  33576. this._session = null;
  33577. /**
  33578. * A reference to the current XR base layer.
  33579. *
  33580. * @private
  33581. * @type {XRWebGLLayer?}
  33582. * @default null
  33583. */
  33584. this._glBaseLayer = null;
  33585. /**
  33586. * A reference to the current XR binding.
  33587. *
  33588. * @private
  33589. * @type {XRWebGLBinding?}
  33590. * @default null
  33591. */
  33592. this._glBinding = null;
  33593. /**
  33594. * A reference to the current XR projection layer.
  33595. *
  33596. * @private
  33597. * @type {XRProjectionLayer?}
  33598. * @default null
  33599. */
  33600. this._glProjLayer = null;
  33601. /**
  33602. * A reference to the current XR frame.
  33603. *
  33604. * @private
  33605. * @type {XRFrame?}
  33606. * @default null
  33607. */
  33608. this._xrFrame = null;
  33609. /**
  33610. * Whether to use the WebXR Layers API or not.
  33611. *
  33612. * @private
  33613. * @type {Boolean}
  33614. * @readonly
  33615. */
  33616. this._useLayers = ( typeof XRWebGLBinding !== 'undefined' && 'createProjectionLayer' in XRWebGLBinding.prototype ); // eslint-disable-line compat/compat
  33617. }
  33618. /**
  33619. * Returns an instance of `THREE.Group` that represents the transformation
  33620. * of a XR controller in target ray space. The requested controller is defined
  33621. * by the given index.
  33622. *
  33623. * @param {Number} index - The index of the XR controller.
  33624. * @return {Group} A group that represents the controller's transformation.
  33625. */
  33626. getController( index ) {
  33627. const controller = this._getController( index );
  33628. return controller.getTargetRaySpace();
  33629. }
  33630. /**
  33631. * Returns an instance of `THREE.Group` that represents the transformation
  33632. * of a XR controller in grip space. The requested controller is defined
  33633. * by the given index.
  33634. *
  33635. * @param {Number} index - The index of the XR controller.
  33636. * @return {Group} A group that represents the controller's transformation.
  33637. */
  33638. getControllerGrip( index ) {
  33639. const controller = this._getController( index );
  33640. return controller.getGripSpace();
  33641. }
  33642. /**
  33643. * Returns an instance of `THREE.Group` that represents the transformation
  33644. * of a XR controller in hand space. The requested controller is defined
  33645. * by the given index.
  33646. *
  33647. * @param {Number} index - The index of the XR controller.
  33648. * @return {Group} A group that represents the controller's transformation.
  33649. */
  33650. getHand( index ) {
  33651. const controller = this._getController( index );
  33652. return controller.getHandSpace();
  33653. }
  33654. /**
  33655. * Returns the foveation value.
  33656. *
  33657. * @return {Number|undefined} The foveation value. Returns `undefined` if no base or projection layer is defined.
  33658. */
  33659. getFoveation() {
  33660. if ( this._glProjLayer === null && this._glBaseLayer === null ) {
  33661. return undefined;
  33662. }
  33663. return this._foveation;
  33664. }
  33665. /**
  33666. * Sets the foveation value.
  33667. *
  33668. * @param {Number} foveation - A number in the range `[0,1]` where `0` means no foveation (full resolution)
  33669. * and `1` means maximum foveation (the edges render at lower resolution).
  33670. */
  33671. setFoveation( foveation ) {
  33672. this._foveation = foveation;
  33673. if ( this._glProjLayer !== null ) {
  33674. this._glProjLayer.fixedFoveation = foveation;
  33675. }
  33676. if ( this._glBaseLayer !== null && this._glBaseLayer.fixedFoveation !== undefined ) {
  33677. this._glBaseLayer.fixedFoveation = foveation;
  33678. }
  33679. }
  33680. /**
  33681. * Returns the framebuffer scale factor.
  33682. *
  33683. * @return {Number} The framebuffer scale factor.
  33684. */
  33685. getFramebufferScaleFactor() {
  33686. return this._framebufferScaleFactor;
  33687. }
  33688. /**
  33689. * Sets the framebuffer scale factor.
  33690. *
  33691. * This method can not be used during a XR session.
  33692. *
  33693. * @param {Number} factor - The framebuffer scale factor.
  33694. */
  33695. setFramebufferScaleFactor( factor ) {
  33696. this._framebufferScaleFactor = factor;
  33697. if ( this.isPresenting === true ) {
  33698. console.warn( 'THREE.XRManager: Cannot change framebuffer scale while presenting.' );
  33699. }
  33700. }
  33701. /**
  33702. * Returns the reference space type.
  33703. *
  33704. * @return {String} The reference space type.
  33705. */
  33706. getReferenceSpaceType() {
  33707. return this._referenceSpaceType;
  33708. }
  33709. /**
  33710. * Sets the reference space type.
  33711. *
  33712. * This method can not be used during a XR session.
  33713. *
  33714. * @param {String} type - The reference space type.
  33715. */
  33716. setReferenceSpaceType( type ) {
  33717. this._referenceSpaceType = type;
  33718. if ( this.isPresenting === true ) {
  33719. console.warn( 'THREE.XRManager: Cannot change reference space type while presenting.' );
  33720. }
  33721. }
  33722. /**
  33723. * Returns the XR reference space.
  33724. *
  33725. * @return {XRReferenceSpace} The XR reference space.
  33726. */
  33727. getReferenceSpace() {
  33728. return this._customReferenceSpace || this._referenceSpace;
  33729. }
  33730. /**
  33731. * Sets a custom XR reference space.
  33732. *
  33733. * @param {XRReferenceSpace} space - The XR reference space.
  33734. */
  33735. setReferenceSpace( space ) {
  33736. this._customReferenceSpace = space;
  33737. }
  33738. /**
  33739. * Returns the XR camera.
  33740. *
  33741. * @return {ArrayCamera} The XR camera.
  33742. */
  33743. getCamera() {
  33744. return this._cameraXR;
  33745. }
  33746. /**
  33747. * Returns the environment blend mode from the current XR session.
  33748. *
  33749. * @return {('opaque'|'additive'|'alpha-blend')?} The environment blend mode. Returns `null` when used outside of a XR session.
  33750. */
  33751. getEnvironmentBlendMode() {
  33752. if ( this._session !== null ) {
  33753. return this._session.environmentBlendMode;
  33754. }
  33755. }
  33756. /**
  33757. * Returns the current XR frame.
  33758. *
  33759. * @return {XRFrame?} The XR frame. Returns `null` when used outside a XR session.
  33760. */
  33761. getFrame() {
  33762. return this._xrFrame;
  33763. }
  33764. /**
  33765. * Returns the current XR session.
  33766. *
  33767. * @return {XRSession?} The XR session. Returns `null` when used outside a XR session.
  33768. */
  33769. getSession() {
  33770. return this._session;
  33771. }
  33772. /**
  33773. * After a XR session has been requested usually with one of the `*Button` modules, it
  33774. * is injected into the renderer with this method. This method triggers the start of
  33775. * the actual XR rendering.
  33776. *
  33777. * @async
  33778. * @param {XRSession} session - The XR session to set.
  33779. * @return {Promise} A Promise that resolves when the session has been set.
  33780. */
  33781. async setSession( session ) {
  33782. const renderer = this._renderer;
  33783. const backend = renderer.backend;
  33784. const gl = renderer.getContext();
  33785. this._session = session;
  33786. if ( session !== null ) {
  33787. 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.' );
  33788. this._currentRenderTarget = renderer.getRenderTarget();
  33789. session.addEventListener( 'select', this._onSessionEvent );
  33790. session.addEventListener( 'selectstart', this._onSessionEvent );
  33791. session.addEventListener( 'selectend', this._onSessionEvent );
  33792. session.addEventListener( 'squeeze', this._onSessionEvent );
  33793. session.addEventListener( 'squeezestart', this._onSessionEvent );
  33794. session.addEventListener( 'squeezeend', this._onSessionEvent );
  33795. session.addEventListener( 'end', this._onSessionEnd );
  33796. session.addEventListener( 'inputsourceschange', this._onInputSourcesChange );
  33797. await backend.makeXRCompatible();
  33798. this._currentPixelRatio = renderer.getPixelRatio();
  33799. renderer.getSize( this._currentSize );
  33800. this._currentAnimationContext = renderer._animation.getContext();
  33801. this._currentAnimationLoop = renderer._animation.getAnimationLoop();
  33802. renderer._animation.stop();
  33803. //
  33804. const attributes = gl.getContextAttributes();
  33805. if ( this._useLayers === true ) {
  33806. // default path using XRWebGLBinding/XRProjectionLayer
  33807. let depthFormat = null;
  33808. let depthType = null;
  33809. let glDepthFormat = null;
  33810. if ( attributes.depth ) {
  33811. glDepthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  33812. depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat;
  33813. depthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType;
  33814. }
  33815. const projectionlayerInit = {
  33816. colorFormat: gl.RGBA8,
  33817. depthFormat: glDepthFormat,
  33818. scaleFactor: this._framebufferScaleFactor
  33819. };
  33820. const glBinding = new XRWebGLBinding( session, gl );
  33821. const glProjLayer = glBinding.createProjectionLayer( projectionlayerInit );
  33822. this._glBinding = glBinding;
  33823. this._glProjLayer = glProjLayer;
  33824. session.updateRenderState( { layers: [ glProjLayer ] } );
  33825. renderer.setPixelRatio( 1 );
  33826. renderer.setSize( glProjLayer.textureWidth, glProjLayer.textureHeight, false );
  33827. this._xrRenderTarget = new XRRenderTarget(
  33828. glProjLayer.textureWidth,
  33829. glProjLayer.textureHeight,
  33830. {
  33831. format: RGBAFormat,
  33832. type: UnsignedByteType,
  33833. colorSpace: renderer.outputColorSpace,
  33834. depthTexture: new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat ),
  33835. stencilBuffer: attributes.stencil,
  33836. samples: attributes.antialias ? 4 : 0
  33837. } );
  33838. this._xrRenderTarget.hasExternalTextures = true;
  33839. } else {
  33840. // fallback to XRWebGLLayer
  33841. const layerInit = {
  33842. antialias: attributes.antialias,
  33843. alpha: true,
  33844. depth: attributes.depth,
  33845. stencil: attributes.stencil,
  33846. framebufferScaleFactor: this.getFramebufferScaleFactor()
  33847. };
  33848. const glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  33849. this._glBaseLayer = glBaseLayer;
  33850. session.updateRenderState( { baseLayer: glBaseLayer } );
  33851. renderer.setPixelRatio( 1 );
  33852. renderer.setSize( glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight, false );
  33853. this._xrRenderTarget = new XRRenderTarget(
  33854. glBaseLayer.framebufferWidth,
  33855. glBaseLayer.framebufferHeight,
  33856. {
  33857. format: RGBAFormat,
  33858. type: UnsignedByteType,
  33859. colorSpace: renderer.outputColorSpace,
  33860. stencilBuffer: attributes.stencil
  33861. }
  33862. );
  33863. }
  33864. //
  33865. this.setFoveation( this.getFoveation() );
  33866. this._referenceSpace = await session.requestReferenceSpace( this.getReferenceSpaceType() );
  33867. renderer._animation.setAnimationLoop( this._onAnimationFrame );
  33868. renderer._animation.setContext( session );
  33869. renderer._animation.start();
  33870. this.isPresenting = true;
  33871. this.dispatchEvent( { type: 'sessionstart' } );
  33872. }
  33873. }
  33874. /**
  33875. * This method is called by the renderer per frame and updates the XR camera
  33876. * and it sub cameras based on the given camera. The given camera is the "user"
  33877. * camera created on application level and used for non-XR rendering.
  33878. *
  33879. * @param {PerspectiveCamera} camera - The camera.
  33880. */
  33881. updateCamera( camera ) {
  33882. const session = this._session;
  33883. if ( session === null ) return;
  33884. const depthNear = camera.near;
  33885. const depthFar = camera.far;
  33886. const cameraXR = this._cameraXR;
  33887. const cameraL = this._cameraL;
  33888. const cameraR = this._cameraR;
  33889. cameraXR.near = cameraR.near = cameraL.near = depthNear;
  33890. cameraXR.far = cameraR.far = cameraL.far = depthFar;
  33891. if ( this._currentDepthNear !== cameraXR.near || this._currentDepthFar !== cameraXR.far ) {
  33892. // Note that the new renderState won't apply until the next frame. See #18320
  33893. session.updateRenderState( {
  33894. depthNear: cameraXR.near,
  33895. depthFar: cameraXR.far
  33896. } );
  33897. this._currentDepthNear = cameraXR.near;
  33898. this._currentDepthFar = cameraXR.far;
  33899. }
  33900. cameraL.layers.mask = camera.layers.mask | 0b010;
  33901. cameraR.layers.mask = camera.layers.mask | 0b100;
  33902. cameraXR.layers.mask = cameraL.layers.mask | cameraR.layers.mask;
  33903. const parent = camera.parent;
  33904. const cameras = cameraXR.cameras;
  33905. updateCamera( cameraXR, parent );
  33906. for ( let i = 0; i < cameras.length; i ++ ) {
  33907. updateCamera( cameras[ i ], parent );
  33908. }
  33909. // update projection matrix for proper view frustum culling
  33910. if ( cameras.length === 2 ) {
  33911. setProjectionFromUnion( cameraXR, cameraL, cameraR );
  33912. } else {
  33913. // assume single camera setup (AR)
  33914. cameraXR.projectionMatrix.copy( cameraL.projectionMatrix );
  33915. }
  33916. // update user camera and its children
  33917. updateUserCamera( camera, cameraXR, parent );
  33918. }
  33919. /**
  33920. * Returns a WebXR controller for the given controller index.
  33921. *
  33922. * @private
  33923. * @param {Number} index - The controller index.
  33924. * @return {WebXRController} The XR controller.
  33925. */
  33926. _getController( index ) {
  33927. let controller = this._controllers[ index ];
  33928. if ( controller === undefined ) {
  33929. controller = new WebXRController();
  33930. this._controllers[ index ] = controller;
  33931. }
  33932. return controller;
  33933. }
  33934. }
  33935. /**
  33936. * Assumes 2 cameras that are parallel and share an X-axis, and that
  33937. * the cameras' projection and world matrices have already been set.
  33938. * And that near and far planes are identical for both cameras.
  33939. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  33940. *
  33941. * @param {ArrayCamera} camera - The camera to update.
  33942. * @param {PerspectiveCamera} cameraL - The left camera.
  33943. * @param {PerspectiveCamera} cameraR - The right camera.
  33944. */
  33945. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  33946. _cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  33947. _cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  33948. const ipd = _cameraLPos.distanceTo( _cameraRPos );
  33949. const projL = cameraL.projectionMatrix.elements;
  33950. const projR = cameraR.projectionMatrix.elements;
  33951. // VR systems will have identical far and near planes, and
  33952. // most likely identical top and bottom frustum extents.
  33953. // Use the left camera for these values.
  33954. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  33955. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  33956. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  33957. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  33958. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  33959. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  33960. const left = near * leftFov;
  33961. const right = near * rightFov;
  33962. // Calculate the new camera's position offset from the
  33963. // left camera. xOffset should be roughly half `ipd`.
  33964. const zOffset = ipd / ( - leftFov + rightFov );
  33965. const xOffset = zOffset * - leftFov;
  33966. // TODO: Better way to apply this offset?
  33967. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  33968. camera.translateX( xOffset );
  33969. camera.translateZ( zOffset );
  33970. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  33971. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  33972. // Check if the projection uses an infinite far plane.
  33973. if ( projL[ 10 ] === -1 ) {
  33974. // Use the projection matrix from the left eye.
  33975. // The camera offset is sufficient to include the view volumes
  33976. // of both eyes (assuming symmetric projections).
  33977. camera.projectionMatrix.copy( cameraL.projectionMatrix );
  33978. camera.projectionMatrixInverse.copy( cameraL.projectionMatrixInverse );
  33979. } else {
  33980. // Find the union of the frustum values of the cameras and scale
  33981. // the values so that the near plane's position does not change in world space,
  33982. // although must now be relative to the new union camera.
  33983. const near2 = near + zOffset;
  33984. const far2 = far + zOffset;
  33985. const left2 = left - xOffset;
  33986. const right2 = right + ( ipd - xOffset );
  33987. const top2 = topFov * far / far2 * near2;
  33988. const bottom2 = bottomFov * far / far2 * near2;
  33989. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  33990. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  33991. }
  33992. }
  33993. /**
  33994. * Updates the world matrices for the given camera based on the parent 3D object.
  33995. *
  33996. * @inner
  33997. * @param {Camera} camera - The camera to update.
  33998. * @param {Object3D} parent - The parent 3D object.
  33999. */
  34000. function updateCamera( camera, parent ) {
  34001. if ( parent === null ) {
  34002. camera.matrixWorld.copy( camera.matrix );
  34003. } else {
  34004. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  34005. }
  34006. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  34007. }
  34008. /**
  34009. * Updates the given camera with the transfomration of the XR camera and parent object.
  34010. *
  34011. * @inner
  34012. * @param {Camera} camera - The camera to update.
  34013. * @param {ArrayCamera} cameraXR - The XR camera.
  34014. * @param {Object3D} parent - The parent 3D object.
  34015. */
  34016. function updateUserCamera( camera, cameraXR, parent ) {
  34017. if ( parent === null ) {
  34018. camera.matrix.copy( cameraXR.matrixWorld );
  34019. } else {
  34020. camera.matrix.copy( parent.matrixWorld );
  34021. camera.matrix.invert();
  34022. camera.matrix.multiply( cameraXR.matrixWorld );
  34023. }
  34024. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  34025. camera.updateMatrixWorld( true );
  34026. camera.projectionMatrix.copy( cameraXR.projectionMatrix );
  34027. camera.projectionMatrixInverse.copy( cameraXR.projectionMatrixInverse );
  34028. if ( camera.isPerspectiveCamera ) {
  34029. camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );
  34030. camera.zoom = 1;
  34031. }
  34032. }
  34033. function onSessionEvent( event ) {
  34034. const controllerIndex = this._controllerInputSources.indexOf( event.inputSource );
  34035. if ( controllerIndex === -1 ) {
  34036. return;
  34037. }
  34038. const controller = this._controllers[ controllerIndex ];
  34039. if ( controller !== undefined ) {
  34040. const referenceSpace = this.getReferenceSpace();
  34041. controller.update( event.inputSource, event.frame, referenceSpace );
  34042. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  34043. }
  34044. }
  34045. function onSessionEnd() {
  34046. const session = this._session;
  34047. const renderer = this._renderer;
  34048. session.removeEventListener( 'select', this._onSessionEvent );
  34049. session.removeEventListener( 'selectstart', this._onSessionEvent );
  34050. session.removeEventListener( 'selectend', this._onSessionEvent );
  34051. session.removeEventListener( 'squeeze', this._onSessionEvent );
  34052. session.removeEventListener( 'squeezestart', this._onSessionEvent );
  34053. session.removeEventListener( 'squeezeend', this._onSessionEvent );
  34054. session.removeEventListener( 'end', this._onSessionEnd );
  34055. session.removeEventListener( 'inputsourceschange', this._onInputSourcesChange );
  34056. for ( let i = 0; i < this._controllers.length; i ++ ) {
  34057. const inputSource = this._controllerInputSources[ i ];
  34058. if ( inputSource === null ) continue;
  34059. this._controllerInputSources[ i ] = null;
  34060. this._controllers[ i ].disconnect( inputSource );
  34061. }
  34062. this._currentDepthNear = null;
  34063. this._currentDepthFar = null;
  34064. // restore framebuffer/rendering state
  34065. renderer.backend.setXRTarget( null );
  34066. renderer.setRenderTarget( this._currentRenderTarget );
  34067. this._session = null;
  34068. this._xrRenderTarget = null;
  34069. //
  34070. this.isPresenting = false;
  34071. renderer._animation.stop();
  34072. renderer._animation.setAnimationLoop( this._currentAnimationLoop );
  34073. renderer._animation.setContext( this._currentAnimationContext );
  34074. renderer._animation.start();
  34075. renderer.setPixelRatio( this._currentPixelRatio );
  34076. renderer.setSize( this._currentSize.width, this._currentSize.height, false );
  34077. this.dispatchEvent( { type: 'sessionend' } );
  34078. }
  34079. function onInputSourcesChange( event ) {
  34080. const controllers = this._controllers;
  34081. const controllerInputSources = this._controllerInputSources;
  34082. // Notify disconnected
  34083. for ( let i = 0; i < event.removed.length; i ++ ) {
  34084. const inputSource = event.removed[ i ];
  34085. const index = controllerInputSources.indexOf( inputSource );
  34086. if ( index >= 0 ) {
  34087. controllerInputSources[ index ] = null;
  34088. controllers[ index ].disconnect( inputSource );
  34089. }
  34090. }
  34091. // Notify connected
  34092. for ( let i = 0; i < event.added.length; i ++ ) {
  34093. const inputSource = event.added[ i ];
  34094. let controllerIndex = controllerInputSources.indexOf( inputSource );
  34095. if ( controllerIndex === -1 ) {
  34096. // Assign input source a controller that currently has no input source
  34097. for ( let i = 0; i < controllers.length; i ++ ) {
  34098. if ( i >= controllerInputSources.length ) {
  34099. controllerInputSources.push( inputSource );
  34100. controllerIndex = i;
  34101. break;
  34102. } else if ( controllerInputSources[ i ] === null ) {
  34103. controllerInputSources[ i ] = inputSource;
  34104. controllerIndex = i;
  34105. break;
  34106. }
  34107. }
  34108. // If all controllers do currently receive input we ignore new ones
  34109. if ( controllerIndex === -1 ) break;
  34110. }
  34111. const controller = controllers[ controllerIndex ];
  34112. if ( controller ) {
  34113. controller.connect( inputSource );
  34114. }
  34115. }
  34116. }
  34117. function onAnimationFrame( time, frame ) {
  34118. if ( frame === undefined ) return;
  34119. const cameraXR = this._cameraXR;
  34120. const renderer = this._renderer;
  34121. const backend = renderer.backend;
  34122. const glBaseLayer = this._glBaseLayer;
  34123. const referenceSpace = this.getReferenceSpace();
  34124. const pose = frame.getViewerPose( referenceSpace );
  34125. this._xrFrame = frame;
  34126. if ( pose !== null ) {
  34127. const views = pose.views;
  34128. if ( this._glBaseLayer !== null ) {
  34129. backend.setXRTarget( glBaseLayer.framebuffer );
  34130. }
  34131. let cameraXRNeedsUpdate = false;
  34132. // check if it's necessary to rebuild cameraXR's camera list
  34133. if ( views.length !== cameraXR.cameras.length ) {
  34134. cameraXR.cameras.length = 0;
  34135. cameraXRNeedsUpdate = true;
  34136. }
  34137. for ( let i = 0; i < views.length; i ++ ) {
  34138. const view = views[ i ];
  34139. let viewport;
  34140. if ( this._useLayers === true ) {
  34141. const glSubImage = this._glBinding.getViewSubImage( this._glProjLayer, view );
  34142. viewport = glSubImage.viewport;
  34143. // For side-by-side projection, we only produce a single texture for both eyes.
  34144. if ( i === 0 ) {
  34145. backend.setXRRenderTargetTextures(
  34146. this._xrRenderTarget,
  34147. glSubImage.colorTexture,
  34148. this._glProjLayer.ignoreDepthValues ? undefined : glSubImage.depthStencilTexture
  34149. );
  34150. }
  34151. } else {
  34152. viewport = glBaseLayer.getViewport( view );
  34153. }
  34154. let camera = this._cameras[ i ];
  34155. if ( camera === undefined ) {
  34156. camera = new PerspectiveCamera();
  34157. camera.layers.enable( i );
  34158. camera.viewport = new Vector4();
  34159. this._cameras[ i ] = camera;
  34160. }
  34161. camera.matrix.fromArray( view.transform.matrix );
  34162. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  34163. camera.projectionMatrix.fromArray( view.projectionMatrix );
  34164. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  34165. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  34166. if ( i === 0 ) {
  34167. cameraXR.matrix.copy( camera.matrix );
  34168. cameraXR.matrix.decompose( cameraXR.position, cameraXR.quaternion, cameraXR.scale );
  34169. }
  34170. if ( cameraXRNeedsUpdate === true ) {
  34171. cameraXR.cameras.push( camera );
  34172. }
  34173. }
  34174. renderer.setRenderTarget( this._xrRenderTarget );
  34175. }
  34176. //
  34177. for ( let i = 0; i < this._controllers.length; i ++ ) {
  34178. const inputSource = this._controllerInputSources[ i ];
  34179. const controller = this._controllers[ i ];
  34180. if ( inputSource !== null && controller !== undefined ) {
  34181. controller.update( inputSource, frame, referenceSpace );
  34182. }
  34183. }
  34184. if ( this._currentAnimationLoop ) this._currentAnimationLoop( time, frame );
  34185. if ( frame.detectedPlanes ) {
  34186. this.dispatchEvent( { type: 'planesdetected', data: frame } );
  34187. }
  34188. this._xrFrame = null;
  34189. }
  34190. /** @module Renderer **/
  34191. const _scene = /*@__PURE__*/ new Scene();
  34192. const _drawingBufferSize = /*@__PURE__*/ new Vector2();
  34193. const _screen = /*@__PURE__*/ new Vector4();
  34194. const _frustum = /*@__PURE__*/ new Frustum();
  34195. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  34196. const _vector4 = /*@__PURE__*/ new Vector4();
  34197. /**
  34198. * Base class for renderers.
  34199. */
  34200. class Renderer {
  34201. /**
  34202. * Constructs a new renderer.
  34203. *
  34204. * @param {Backend} backend - The backend the renderer is targeting (e.g. WebGPU or WebGL 2).
  34205. * @param {Object} parameters - The configuration parameter.
  34206. * @param {Boolean} [parameters.logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  34207. * @param {Boolean} [parameters.alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  34208. * @param {Boolean} [parameters.depth=true] - Whether the default framebuffer should have a depth buffer or not.
  34209. * @param {Boolean} [parameters.stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  34210. * @param {Boolean} [parameters.antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  34211. * @param {Number} [parameters.samples=0] - When `antialias` is `true`, `4` samples are used by default. This parameter can set to any other integer value than 0
  34212. * to overwrite the default.
  34213. * @param {Function?} [parameters.getFallback=null] - This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  34214. */
  34215. constructor( backend, parameters = {} ) {
  34216. /**
  34217. * This flag can be used for type testing.
  34218. *
  34219. * @type {Boolean}
  34220. * @readonly
  34221. * @default true
  34222. */
  34223. this.isRenderer = true;
  34224. //
  34225. const {
  34226. logarithmicDepthBuffer = false,
  34227. alpha = true,
  34228. depth = true,
  34229. stencil = false,
  34230. antialias = false,
  34231. samples = 0,
  34232. getFallback = null
  34233. } = parameters;
  34234. /**
  34235. * A reference to the canvas element the renderer is drawing to.
  34236. * This value of this property will automatically be created by
  34237. * the renderer.
  34238. *
  34239. * @type {HTMLCanvasElement|OffscreenCanvas}
  34240. */
  34241. this.domElement = backend.getDomElement();
  34242. /**
  34243. * A reference to the current backend.
  34244. *
  34245. * @type {Backend}
  34246. */
  34247. this.backend = backend;
  34248. /**
  34249. * The number of MSAA samples.
  34250. *
  34251. * @type {Number}
  34252. * @default 0
  34253. */
  34254. this.samples = samples || ( antialias === true ) ? 4 : 0;
  34255. /**
  34256. * Whether the renderer should automatically clear the current rendering target
  34257. * before execute a `render()` call. The target can be the canvas (default framebuffer)
  34258. * or the current bound render target (custom framebuffer).
  34259. *
  34260. * @type {Boolean}
  34261. * @default true
  34262. */
  34263. this.autoClear = true;
  34264. /**
  34265. * When `autoClear` is set to `true`, this property defines whether the renderer
  34266. * should clear the color buffer.
  34267. *
  34268. * @type {Boolean}
  34269. * @default true
  34270. */
  34271. this.autoClearColor = true;
  34272. /**
  34273. * When `autoClear` is set to `true`, this property defines whether the renderer
  34274. * should clear the depth buffer.
  34275. *
  34276. * @type {Boolean}
  34277. * @default true
  34278. */
  34279. this.autoClearDepth = true;
  34280. /**
  34281. * When `autoClear` is set to `true`, this property defines whether the renderer
  34282. * should clear the stencil buffer.
  34283. *
  34284. * @type {Boolean}
  34285. * @default true
  34286. */
  34287. this.autoClearStencil = true;
  34288. /**
  34289. * Whether the default framebuffer should be transparent or opaque.
  34290. *
  34291. * @type {Boolean}
  34292. * @default true
  34293. */
  34294. this.alpha = alpha;
  34295. /**
  34296. * Whether logarithmic depth buffer is enabled or not.
  34297. *
  34298. * @type {Boolean}
  34299. * @default false
  34300. */
  34301. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  34302. /**
  34303. * Defines the output color space of the renderer.
  34304. *
  34305. * @type {String}
  34306. * @default SRGBColorSpace
  34307. */
  34308. this.outputColorSpace = SRGBColorSpace;
  34309. /**
  34310. * Defines the tone mapping of the renderer.
  34311. *
  34312. * @type {Number}
  34313. * @default NoToneMapping
  34314. */
  34315. this.toneMapping = NoToneMapping;
  34316. /**
  34317. * Defines the tone mapping exposure.
  34318. *
  34319. * @type {Number}
  34320. * @default 1
  34321. */
  34322. this.toneMappingExposure = 1.0;
  34323. /**
  34324. * Whether the renderer should sort its render lists or not.
  34325. *
  34326. * Note: Sorting is used to attempt to properly render objects that have some degree of transparency.
  34327. * By definition, sorting objects may not work in all cases. Depending on the needs of application,
  34328. * it may be necessary to turn off sorting and use other methods to deal with transparency rendering
  34329. * e.g. manually determining each object's rendering order.
  34330. *
  34331. * @type {Boolean}
  34332. * @default true
  34333. */
  34334. this.sortObjects = true;
  34335. /**
  34336. * Whether the default framebuffer should have a depth buffer or not.
  34337. *
  34338. * @type {Boolean}
  34339. * @default true
  34340. */
  34341. this.depth = depth;
  34342. /**
  34343. * Whether the default framebuffer should have a stencil buffer or not.
  34344. *
  34345. * @type {Boolean}
  34346. * @default false
  34347. */
  34348. this.stencil = stencil;
  34349. /**
  34350. * Holds a series of statistical information about the GPU memory
  34351. * and the rendering process. Useful for debugging and monitoring.
  34352. *
  34353. * @type {Info}
  34354. */
  34355. this.info = new Info();
  34356. this.nodes = {
  34357. modelViewMatrix: null,
  34358. modelNormalViewMatrix: null
  34359. };
  34360. /**
  34361. * The node library defines how certain library objects like materials, lights
  34362. * or tone mapping functions are mapped to node types. This is required since
  34363. * although instances of classes like `MeshBasicMaterial` or `PointLight` can
  34364. * be part of the scene graph, they are internally represented as nodes for
  34365. * further processing.
  34366. *
  34367. * @type {NodeLibrary}
  34368. */
  34369. this.library = new NodeLibrary();
  34370. /**
  34371. * A map-like data structure for managing lights.
  34372. *
  34373. * @type {Lighting}
  34374. */
  34375. this.lighting = new Lighting();
  34376. // internals
  34377. /**
  34378. * This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  34379. *
  34380. * @private
  34381. * @type {Function}
  34382. */
  34383. this._getFallback = getFallback;
  34384. /**
  34385. * The renderer's pixel ration.
  34386. *
  34387. * @private
  34388. * @type {Number}
  34389. * @default 1
  34390. */
  34391. this._pixelRatio = 1;
  34392. /**
  34393. * The width of the renderer's default framebuffer in logical pixel unit.
  34394. *
  34395. * @private
  34396. * @type {Number}
  34397. */
  34398. this._width = this.domElement.width;
  34399. /**
  34400. * The height of the renderer's default framebuffer in logical pixel unit.
  34401. *
  34402. * @private
  34403. * @type {Number}
  34404. */
  34405. this._height = this.domElement.height;
  34406. /**
  34407. * The viewport of the renderer in logical pixel unit.
  34408. *
  34409. * @private
  34410. * @type {Vector4}
  34411. */
  34412. this._viewport = new Vector4( 0, 0, this._width, this._height );
  34413. /**
  34414. * The scissor rectangle of the renderer in logical pixel unit.
  34415. *
  34416. * @private
  34417. * @type {Vector4}
  34418. */
  34419. this._scissor = new Vector4( 0, 0, this._width, this._height );
  34420. /**
  34421. * Whether the scissor test should be enabled or not.
  34422. *
  34423. * @private
  34424. * @type {Boolean}
  34425. */
  34426. this._scissorTest = false;
  34427. /**
  34428. * A reference to a renderer module for managing shader attributes.
  34429. *
  34430. * @private
  34431. * @type {Attributes?}
  34432. * @default null
  34433. */
  34434. this._attributes = null;
  34435. /**
  34436. * A reference to a renderer module for managing geometries.
  34437. *
  34438. * @private
  34439. * @type {Geometries?}
  34440. * @default null
  34441. */
  34442. this._geometries = null;
  34443. /**
  34444. * A reference to a renderer module for managing node related logic.
  34445. *
  34446. * @private
  34447. * @type {Nodes?}
  34448. * @default null
  34449. */
  34450. this._nodes = null;
  34451. /**
  34452. * A reference to a renderer module for managing the internal animation loop.
  34453. *
  34454. * @private
  34455. * @type {Animation?}
  34456. * @default null
  34457. */
  34458. this._animation = null;
  34459. /**
  34460. * A reference to a renderer module for managing shader program bindings.
  34461. *
  34462. * @private
  34463. * @type {Bindings?}
  34464. * @default null
  34465. */
  34466. this._bindings = null;
  34467. /**
  34468. * A reference to a renderer module for managing render objects.
  34469. *
  34470. * @private
  34471. * @type {RenderObjects?}
  34472. * @default null
  34473. */
  34474. this._objects = null;
  34475. /**
  34476. * A reference to a renderer module for managing render and compute pipelines.
  34477. *
  34478. * @private
  34479. * @type {Pipelines?}
  34480. * @default null
  34481. */
  34482. this._pipelines = null;
  34483. /**
  34484. * A reference to a renderer module for managing render bundles.
  34485. *
  34486. * @private
  34487. * @type {RenderBundles?}
  34488. * @default null
  34489. */
  34490. this._bundles = null;
  34491. /**
  34492. * A reference to a renderer module for managing render lists.
  34493. *
  34494. * @private
  34495. * @type {RenderLists?}
  34496. * @default null
  34497. */
  34498. this._renderLists = null;
  34499. /**
  34500. * A reference to a renderer module for managing render contexts.
  34501. *
  34502. * @private
  34503. * @type {RenderContexts?}
  34504. * @default null
  34505. */
  34506. this._renderContexts = null;
  34507. /**
  34508. * A reference to a renderer module for managing textures.
  34509. *
  34510. * @private
  34511. * @type {Textures?}
  34512. * @default null
  34513. */
  34514. this._textures = null;
  34515. /**
  34516. * A reference to a renderer module for backgrounds.
  34517. *
  34518. * @private
  34519. * @type {Background?}
  34520. * @default null
  34521. */
  34522. this._background = null;
  34523. /**
  34524. * This fullscreen quad is used for internal render passes
  34525. * like the tone mapping and color space output pass.
  34526. *
  34527. * @private
  34528. * @type {QuadMesh}
  34529. */
  34530. this._quad = new QuadMesh( new NodeMaterial() );
  34531. this._quad.material.name = 'Renderer_output';
  34532. /**
  34533. * A reference to the current render context.
  34534. *
  34535. * @private
  34536. * @type {RenderContext?}
  34537. * @default null
  34538. */
  34539. this._currentRenderContext = null;
  34540. /**
  34541. * A custom sort function for the opaque render list.
  34542. *
  34543. * @private
  34544. * @type {Function?}
  34545. * @default null
  34546. */
  34547. this._opaqueSort = null;
  34548. /**
  34549. * A custom sort function for the transparent render list.
  34550. *
  34551. * @private
  34552. * @type {Function?}
  34553. * @default null
  34554. */
  34555. this._transparentSort = null;
  34556. /**
  34557. * The framebuffer target.
  34558. *
  34559. * @private
  34560. * @type {RenderTarget?}
  34561. * @default null
  34562. */
  34563. this._frameBufferTarget = null;
  34564. const alphaClear = this.alpha === true ? 0 : 1;
  34565. /**
  34566. * The clear color value.
  34567. *
  34568. * @private
  34569. * @type {Color4}
  34570. */
  34571. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  34572. /**
  34573. * The clear depth value.
  34574. *
  34575. * @private
  34576. * @type {Number}
  34577. * @default 1
  34578. */
  34579. this._clearDepth = 1;
  34580. /**
  34581. * The clear stencil value.
  34582. *
  34583. * @private
  34584. * @type {Number}
  34585. * @default 0
  34586. */
  34587. this._clearStencil = 0;
  34588. /**
  34589. * The current render target.
  34590. *
  34591. * @private
  34592. * @type {RenderTarget?}
  34593. * @default null
  34594. */
  34595. this._renderTarget = null;
  34596. /**
  34597. * The active cube face.
  34598. *
  34599. * @private
  34600. * @type {Number}
  34601. * @default 0
  34602. */
  34603. this._activeCubeFace = 0;
  34604. /**
  34605. * The active mipmap level.
  34606. *
  34607. * @private
  34608. * @type {Number}
  34609. * @default 0
  34610. */
  34611. this._activeMipmapLevel = 0;
  34612. /**
  34613. * The MRT setting.
  34614. *
  34615. * @private
  34616. * @type {MRTNode?}
  34617. * @default null
  34618. */
  34619. this._mrt = null;
  34620. /**
  34621. * This function defines how a render object is going
  34622. * to be rendered.
  34623. *
  34624. * @private
  34625. * @type {Function?}
  34626. * @default null
  34627. */
  34628. this._renderObjectFunction = null;
  34629. /**
  34630. * Used to keep track of the current render object function.
  34631. *
  34632. * @private
  34633. * @type {Function?}
  34634. * @default null
  34635. */
  34636. this._currentRenderObjectFunction = null;
  34637. /**
  34638. * Used to keep track of the current render bundle.
  34639. *
  34640. * @private
  34641. * @type {RenderBundle?}
  34642. * @default null
  34643. */
  34644. this._currentRenderBundle = null;
  34645. /**
  34646. * Next to `_renderObjectFunction()`, this function provides another hook
  34647. * for influencing the render process of a render object. It is meant for internal
  34648. * use and only relevant for `compileAsync()` right now. Instead of using
  34649. * the default logic of `_renderObjectDirect()` which actually draws the render object,
  34650. * a different function might be used which performs no draw but just the node
  34651. * and pipeline updates.
  34652. *
  34653. * @private
  34654. * @type {Function?}
  34655. * @default null
  34656. */
  34657. this._handleObjectFunction = this._renderObjectDirect;
  34658. /**
  34659. * Indicates whether the device has been lost or not. In WebGL terms, the device
  34660. * lost is considered as a context lost. When this is set to `true`, rendering
  34661. * isn't possible anymore.
  34662. *
  34663. * @private
  34664. * @type {Boolean}
  34665. * @default false
  34666. */
  34667. this._isDeviceLost = false;
  34668. /**
  34669. * A callback function that defines what should happen when a device/context lost occurs.
  34670. *
  34671. * @type {Function}
  34672. */
  34673. this.onDeviceLost = this._onDeviceLost;
  34674. /**
  34675. * Whether the renderer has been initialized or not.
  34676. *
  34677. * @private
  34678. * @type {Boolean}
  34679. * @default false
  34680. */
  34681. this._initialized = false;
  34682. /**
  34683. * A reference to the promise which initializes the renderer.
  34684. *
  34685. * @private
  34686. * @type {Promise?}
  34687. * @default null
  34688. */
  34689. this._initPromise = null;
  34690. /**
  34691. * An array of compilation promises which are used in `compileAsync()`.
  34692. *
  34693. * @private
  34694. * @type {Array<Promise>?}
  34695. * @default null
  34696. */
  34697. this._compilationPromises = null;
  34698. /**
  34699. * Whether the renderer should render transparent render objects or not.
  34700. *
  34701. * @type {Boolean}
  34702. * @default true
  34703. */
  34704. this.transparent = true;
  34705. /**
  34706. * Whether the renderer should render opaque render objects or not.
  34707. *
  34708. * @type {Boolean}
  34709. * @default true
  34710. */
  34711. this.opaque = true;
  34712. /**
  34713. * Shadow map configuration
  34714. * @typedef {Object} ShadowMapConfig
  34715. * @property {Boolean} enabled - Whether to globally enable shadows or not.
  34716. * @property {Number} type - The shadow map type.
  34717. */
  34718. /**
  34719. * The renderer's shadow configuration.
  34720. *
  34721. * @type {module:Renderer~ShadowMapConfig}
  34722. */
  34723. this.shadowMap = {
  34724. enabled: false,
  34725. type: PCFShadowMap
  34726. };
  34727. /**
  34728. * XR configuration.
  34729. * @typedef {Object} XRConfig
  34730. * @property {Boolean} enabled - Whether to globally enable XR or not.
  34731. */
  34732. /**
  34733. * The renderer's XR manager.
  34734. *
  34735. * @type {XRManager}
  34736. */
  34737. this.xr = new XRManager( this );
  34738. /**
  34739. * Debug configuration.
  34740. * @typedef {Object} DebugConfig
  34741. * @property {Boolean} checkShaderErrors - Whether shader errors should be checked or not.
  34742. * @property {Function} onShaderError - A callback function that is executed when a shader error happens. Only supported with WebGL 2 right now.
  34743. * @property {Function} getShaderAsync - Allows the get the raw shader code for the given scene, camera and 3D object.
  34744. */
  34745. /**
  34746. * The renderer's debug configuration.
  34747. *
  34748. * @type {module:Renderer~DebugConfig}
  34749. */
  34750. this.debug = {
  34751. checkShaderErrors: true,
  34752. onShaderError: null,
  34753. getShaderAsync: async ( scene, camera, object ) => {
  34754. await this.compileAsync( scene, camera );
  34755. const renderList = this._renderLists.get( scene, camera );
  34756. const renderContext = this._renderContexts.get( scene, camera, this._renderTarget );
  34757. const material = scene.overrideMaterial || object.material;
  34758. const renderObject = this._objects.get( object, material, scene, camera, renderList.lightsNode, renderContext, renderContext.clippingContext );
  34759. const { fragmentShader, vertexShader } = renderObject.getNodeBuilderState();
  34760. return { fragmentShader, vertexShader };
  34761. }
  34762. };
  34763. }
  34764. /**
  34765. * Initializes the renderer so it is ready for usage.
  34766. *
  34767. * @async
  34768. * @return {Promise} A Promise that resolves when the renderer has been initialized.
  34769. */
  34770. async init() {
  34771. if ( this._initialized ) {
  34772. throw new Error( 'Renderer: Backend has already been initialized.' );
  34773. }
  34774. if ( this._initPromise !== null ) {
  34775. return this._initPromise;
  34776. }
  34777. this._initPromise = new Promise( async ( resolve, reject ) => {
  34778. let backend = this.backend;
  34779. try {
  34780. await backend.init( this );
  34781. } catch ( error ) {
  34782. if ( this._getFallback !== null ) {
  34783. // try the fallback
  34784. try {
  34785. this.backend = backend = this._getFallback( error );
  34786. await backend.init( this );
  34787. } catch ( error ) {
  34788. reject( error );
  34789. return;
  34790. }
  34791. } else {
  34792. reject( error );
  34793. return;
  34794. }
  34795. }
  34796. this._nodes = new Nodes( this, backend );
  34797. this._animation = new Animation( this._nodes, this.info );
  34798. this._attributes = new Attributes( backend );
  34799. this._background = new Background( this, this._nodes );
  34800. this._geometries = new Geometries( this._attributes, this.info );
  34801. this._textures = new Textures( this, backend, this.info );
  34802. this._pipelines = new Pipelines( backend, this._nodes );
  34803. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  34804. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  34805. this._renderLists = new RenderLists( this.lighting );
  34806. this._bundles = new RenderBundles();
  34807. this._renderContexts = new RenderContexts();
  34808. //
  34809. this._animation.start();
  34810. this._initialized = true;
  34811. resolve();
  34812. } );
  34813. return this._initPromise;
  34814. }
  34815. /**
  34816. * The coordinate system of the renderer. The value of this property
  34817. * depends on the selected backend. Either `THREE.WebGLCoordinateSystem` or
  34818. * `THREE.WebGPUCoordinateSystem`.
  34819. *
  34820. * @readonly
  34821. * @type {Number}
  34822. */
  34823. get coordinateSystem() {
  34824. return this.backend.coordinateSystem;
  34825. }
  34826. /**
  34827. * Compiles all materials in the given scene. This can be useful to avoid a
  34828. * phenomenon which is called "shader compilation stutter", which occurs when
  34829. * rendering an object with a new shader for the first time.
  34830. *
  34831. * If you want to add a 3D object to an existing scene, use the third optional
  34832. * parameter for applying the target scene. Note that the (target) scene's lighting
  34833. * and environment must be configured before calling this method.
  34834. *
  34835. * @async
  34836. * @param {Object3D} scene - The scene or 3D object to precompile.
  34837. * @param {Camera} camera - The camera that is used to render the scene.
  34838. * @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.
  34839. * @return {Promise<Array>} A Promise that resolves when the compile has been finished.
  34840. */
  34841. async compileAsync( scene, camera, targetScene = null ) {
  34842. if ( this._isDeviceLost === true ) return;
  34843. if ( this._initialized === false ) await this.init();
  34844. // preserve render tree
  34845. const nodeFrame = this._nodes.nodeFrame;
  34846. const previousRenderId = nodeFrame.renderId;
  34847. const previousRenderContext = this._currentRenderContext;
  34848. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  34849. const previousCompilationPromises = this._compilationPromises;
  34850. //
  34851. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  34852. if ( targetScene === null ) targetScene = scene;
  34853. const renderTarget = this._renderTarget;
  34854. const renderContext = this._renderContexts.get( targetScene, camera, renderTarget );
  34855. const activeMipmapLevel = this._activeMipmapLevel;
  34856. const compilationPromises = [];
  34857. this._currentRenderContext = renderContext;
  34858. this._currentRenderObjectFunction = this.renderObject;
  34859. this._handleObjectFunction = this._createObjectPipeline;
  34860. this._compilationPromises = compilationPromises;
  34861. nodeFrame.renderId ++;
  34862. //
  34863. nodeFrame.update();
  34864. //
  34865. renderContext.depth = this.depth;
  34866. renderContext.stencil = this.stencil;
  34867. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  34868. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  34869. //
  34870. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  34871. //
  34872. const renderList = this._renderLists.get( scene, camera );
  34873. renderList.begin();
  34874. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  34875. // include lights from target scene
  34876. if ( targetScene !== scene ) {
  34877. targetScene.traverseVisible( function ( object ) {
  34878. if ( object.isLight && object.layers.test( camera.layers ) ) {
  34879. renderList.pushLight( object );
  34880. }
  34881. } );
  34882. }
  34883. renderList.finish();
  34884. //
  34885. if ( renderTarget !== null ) {
  34886. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  34887. const renderTargetData = this._textures.get( renderTarget );
  34888. renderContext.textures = renderTargetData.textures;
  34889. renderContext.depthTexture = renderTargetData.depthTexture;
  34890. } else {
  34891. renderContext.textures = null;
  34892. renderContext.depthTexture = null;
  34893. }
  34894. //
  34895. this._background.update( sceneRef, renderList, renderContext );
  34896. // process render lists
  34897. const opaqueObjects = renderList.opaque;
  34898. const transparentObjects = renderList.transparent;
  34899. const transparentDoublePassObjects = renderList.transparentDoublePass;
  34900. const lightsNode = renderList.lightsNode;
  34901. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  34902. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  34903. // restore render tree
  34904. nodeFrame.renderId = previousRenderId;
  34905. this._currentRenderContext = previousRenderContext;
  34906. this._currentRenderObjectFunction = previousRenderObjectFunction;
  34907. this._compilationPromises = previousCompilationPromises;
  34908. this._handleObjectFunction = this._renderObjectDirect;
  34909. // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete
  34910. await Promise.all( compilationPromises );
  34911. }
  34912. /**
  34913. * Renders the scene in an async fashion.
  34914. *
  34915. * @async
  34916. * @param {Object3D} scene - The scene or 3D object to render.
  34917. * @param {Camera} camera - The camera.
  34918. * @return {Promise} A Promise that resolves when the render has been finished.
  34919. */
  34920. async renderAsync( scene, camera ) {
  34921. if ( this._initialized === false ) await this.init();
  34922. this._renderScene( scene, camera );
  34923. }
  34924. /**
  34925. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  34926. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  34927. *
  34928. * @async
  34929. * @return {Promise} A Promise that resolves when synchronization has been finished.
  34930. */
  34931. async waitForGPU() {
  34932. await this.backend.waitForGPU();
  34933. }
  34934. /**
  34935. * Sets the given MRT configuration.
  34936. *
  34937. * @param {MRTNode} mrt - The MRT node to set.
  34938. * @return {Renderer} A reference to this renderer.
  34939. */
  34940. setMRT( mrt ) {
  34941. this._mrt = mrt;
  34942. return this;
  34943. }
  34944. /**
  34945. * Returns the MRT configuration.
  34946. *
  34947. * @return {MRTNode} The MRT configuration.
  34948. */
  34949. getMRT() {
  34950. return this._mrt;
  34951. }
  34952. /**
  34953. * Default implementation of the device lost callback.
  34954. *
  34955. * @private
  34956. * @param {Object} info - Information about the context lost.
  34957. */
  34958. _onDeviceLost( info ) {
  34959. let errorMessage = `THREE.WebGPURenderer: ${info.api} Device Lost:\n\nMessage: ${info.message}`;
  34960. if ( info.reason ) {
  34961. errorMessage += `\nReason: ${info.reason}`;
  34962. }
  34963. console.error( errorMessage );
  34964. this._isDeviceLost = true;
  34965. }
  34966. /**
  34967. * Renders the given render bundle.
  34968. *
  34969. * @private
  34970. * @param {Object} bundle - Render bundle data.
  34971. * @param {Scene} sceneRef - The scene the render bundle belongs to.
  34972. * @param {LightsNode} lightsNode - The current lights node.
  34973. */
  34974. _renderBundle( bundle, sceneRef, lightsNode ) {
  34975. const { bundleGroup, camera, renderList } = bundle;
  34976. const renderContext = this._currentRenderContext;
  34977. //
  34978. const renderBundle = this._bundles.get( bundleGroup, camera );
  34979. const renderBundleData = this.backend.get( renderBundle );
  34980. if ( renderBundleData.renderContexts === undefined ) renderBundleData.renderContexts = new Set();
  34981. //
  34982. const needsUpdate = bundleGroup.version !== renderBundleData.version;
  34983. const renderBundleNeedsUpdate = renderBundleData.renderContexts.has( renderContext ) === false || needsUpdate;
  34984. renderBundleData.renderContexts.add( renderContext );
  34985. if ( renderBundleNeedsUpdate ) {
  34986. this.backend.beginBundle( renderContext );
  34987. if ( renderBundleData.renderObjects === undefined || needsUpdate ) {
  34988. renderBundleData.renderObjects = [];
  34989. }
  34990. this._currentRenderBundle = renderBundle;
  34991. const opaqueObjects = renderList.opaque;
  34992. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  34993. this._currentRenderBundle = null;
  34994. //
  34995. this.backend.finishBundle( renderContext, renderBundle );
  34996. renderBundleData.version = bundleGroup.version;
  34997. } else {
  34998. const { renderObjects } = renderBundleData;
  34999. for ( let i = 0, l = renderObjects.length; i < l; i ++ ) {
  35000. const renderObject = renderObjects[ i ];
  35001. if ( this._nodes.needsRefresh( renderObject ) ) {
  35002. this._nodes.updateBefore( renderObject );
  35003. this._nodes.updateForRender( renderObject );
  35004. this._bindings.updateForRender( renderObject );
  35005. this._nodes.updateAfter( renderObject );
  35006. }
  35007. }
  35008. }
  35009. this.backend.addBundle( renderContext, renderBundle );
  35010. }
  35011. /**
  35012. * Renders the scene or 3D object with the given camera. This method can only be called
  35013. * if the renderer has been initialized.
  35014. *
  35015. * The target of the method is the default framebuffer (meaning the canvas)
  35016. * or alternatively a render target when specified via `setRenderTarget()`.
  35017. *
  35018. * @param {Object3D} scene - The scene or 3D object to render.
  35019. * @param {Camera} camera - The camera to render the scene with.
  35020. * @return {Promise?} A Promise that resolve when the scene has been rendered.
  35021. * Only returned when the renderer has not been initialized.
  35022. */
  35023. render( scene, camera ) {
  35024. if ( this._initialized === false ) {
  35025. console.warn( 'THREE.Renderer: .render() called before the backend is initialized. Try using .renderAsync() instead.' );
  35026. return this.renderAsync( scene, camera );
  35027. }
  35028. this._renderScene( scene, camera );
  35029. }
  35030. /**
  35031. * Returns an internal render target which is used when computing the output tone mapping
  35032. * and color space conversion. Unlike in `WebGLRenderer`, this is done in a separate render
  35033. * pass and not inline to achieve more correct results.
  35034. *
  35035. * @private
  35036. * @return {RenderTarget?} The render target. The method returns `null` if no output conversion should be applied.
  35037. */
  35038. _getFrameBufferTarget() {
  35039. const { currentToneMapping, currentColorSpace } = this;
  35040. const useToneMapping = currentToneMapping !== NoToneMapping;
  35041. const useColorSpace = currentColorSpace !== LinearSRGBColorSpace;
  35042. if ( useToneMapping === false && useColorSpace === false ) return null;
  35043. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  35044. const { depth, stencil } = this;
  35045. let frameBufferTarget = this._frameBufferTarget;
  35046. if ( frameBufferTarget === null ) {
  35047. frameBufferTarget = new RenderTarget( width, height, {
  35048. depthBuffer: depth,
  35049. stencilBuffer: stencil,
  35050. type: HalfFloatType, // FloatType
  35051. format: RGBAFormat,
  35052. colorSpace: LinearSRGBColorSpace,
  35053. generateMipmaps: false,
  35054. minFilter: LinearFilter,
  35055. magFilter: LinearFilter,
  35056. samples: this.samples
  35057. } );
  35058. frameBufferTarget.isPostProcessingRenderTarget = true;
  35059. this._frameBufferTarget = frameBufferTarget;
  35060. }
  35061. frameBufferTarget.depthBuffer = depth;
  35062. frameBufferTarget.stencilBuffer = stencil;
  35063. frameBufferTarget.setSize( width, height );
  35064. frameBufferTarget.viewport.copy( this._viewport );
  35065. frameBufferTarget.scissor.copy( this._scissor );
  35066. frameBufferTarget.viewport.multiplyScalar( this._pixelRatio );
  35067. frameBufferTarget.scissor.multiplyScalar( this._pixelRatio );
  35068. frameBufferTarget.scissorTest = this._scissorTest;
  35069. return frameBufferTarget;
  35070. }
  35071. /**
  35072. * Renders the scene or 3D object with the given camera.
  35073. *
  35074. * @private
  35075. * @param {Object3D} scene - The scene or 3D object to render.
  35076. * @param {Camera} camera - The camera to render the scene with.
  35077. * @param {Boolean} [useFrameBufferTarget=true] - Whether to use a framebuffer target or not.
  35078. * @return {RenderContext} The current render context.
  35079. */
  35080. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  35081. if ( this._isDeviceLost === true ) return;
  35082. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  35083. // preserve render tree
  35084. const nodeFrame = this._nodes.nodeFrame;
  35085. const previousRenderId = nodeFrame.renderId;
  35086. const previousRenderContext = this._currentRenderContext;
  35087. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  35088. //
  35089. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  35090. const outputRenderTarget = this._renderTarget;
  35091. const activeCubeFace = this._activeCubeFace;
  35092. const activeMipmapLevel = this._activeMipmapLevel;
  35093. //
  35094. let renderTarget;
  35095. if ( frameBufferTarget !== null ) {
  35096. renderTarget = frameBufferTarget;
  35097. this.setRenderTarget( renderTarget );
  35098. } else {
  35099. renderTarget = outputRenderTarget;
  35100. }
  35101. //
  35102. const renderContext = this._renderContexts.get( scene, camera, renderTarget );
  35103. this._currentRenderContext = renderContext;
  35104. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  35105. //
  35106. this.info.calls ++;
  35107. this.info.render.calls ++;
  35108. this.info.render.frameCalls ++;
  35109. nodeFrame.renderId = this.info.calls;
  35110. //
  35111. const coordinateSystem = this.coordinateSystem;
  35112. const xr = this.xr;
  35113. if ( camera.coordinateSystem !== coordinateSystem && xr.isPresenting === false ) {
  35114. camera.coordinateSystem = coordinateSystem;
  35115. camera.updateProjectionMatrix();
  35116. if ( camera.isArrayCamera ) {
  35117. for ( const subCamera of camera.cameras ) {
  35118. subCamera.coordinateSystem = coordinateSystem;
  35119. subCamera.updateProjectionMatrix();
  35120. }
  35121. }
  35122. }
  35123. //
  35124. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  35125. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  35126. if ( xr.enabled === true && xr.isPresenting === true ) {
  35127. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  35128. camera = xr.getCamera(); // use XR camera for rendering
  35129. }
  35130. //
  35131. let viewport = this._viewport;
  35132. let scissor = this._scissor;
  35133. let pixelRatio = this._pixelRatio;
  35134. if ( renderTarget !== null ) {
  35135. viewport = renderTarget.viewport;
  35136. scissor = renderTarget.scissor;
  35137. pixelRatio = 1;
  35138. }
  35139. this.getDrawingBufferSize( _drawingBufferSize );
  35140. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  35141. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  35142. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  35143. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  35144. renderContext.viewportValue.width >>= activeMipmapLevel;
  35145. renderContext.viewportValue.height >>= activeMipmapLevel;
  35146. renderContext.viewportValue.minDepth = minDepth;
  35147. renderContext.viewportValue.maxDepth = maxDepth;
  35148. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  35149. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  35150. renderContext.scissor = this._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  35151. renderContext.scissorValue.width >>= activeMipmapLevel;
  35152. renderContext.scissorValue.height >>= activeMipmapLevel;
  35153. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  35154. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  35155. //
  35156. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  35157. //
  35158. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  35159. _frustum.setFromProjectionMatrix( _projScreenMatrix, coordinateSystem );
  35160. const renderList = this._renderLists.get( scene, camera );
  35161. renderList.begin();
  35162. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  35163. renderList.finish();
  35164. if ( this.sortObjects === true ) {
  35165. renderList.sort( this._opaqueSort, this._transparentSort );
  35166. }
  35167. //
  35168. if ( renderTarget !== null ) {
  35169. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  35170. const renderTargetData = this._textures.get( renderTarget );
  35171. renderContext.textures = renderTargetData.textures;
  35172. renderContext.depthTexture = renderTargetData.depthTexture;
  35173. renderContext.width = renderTargetData.width;
  35174. renderContext.height = renderTargetData.height;
  35175. renderContext.renderTarget = renderTarget;
  35176. renderContext.depth = renderTarget.depthBuffer;
  35177. renderContext.stencil = renderTarget.stencilBuffer;
  35178. } else {
  35179. renderContext.textures = null;
  35180. renderContext.depthTexture = null;
  35181. renderContext.width = this.domElement.width;
  35182. renderContext.height = this.domElement.height;
  35183. renderContext.depth = this.depth;
  35184. renderContext.stencil = this.stencil;
  35185. }
  35186. renderContext.width >>= activeMipmapLevel;
  35187. renderContext.height >>= activeMipmapLevel;
  35188. renderContext.activeCubeFace = activeCubeFace;
  35189. renderContext.activeMipmapLevel = activeMipmapLevel;
  35190. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  35191. //
  35192. this._background.update( sceneRef, renderList, renderContext );
  35193. //
  35194. this.backend.beginRender( renderContext );
  35195. // process render lists
  35196. const {
  35197. bundles,
  35198. lightsNode,
  35199. transparentDoublePass: transparentDoublePassObjects,
  35200. transparent: transparentObjects,
  35201. opaque: opaqueObjects
  35202. } = renderList;
  35203. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  35204. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  35205. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  35206. // finish render pass
  35207. this.backend.finishRender( renderContext );
  35208. // restore render tree
  35209. nodeFrame.renderId = previousRenderId;
  35210. this._currentRenderContext = previousRenderContext;
  35211. this._currentRenderObjectFunction = previousRenderObjectFunction;
  35212. //
  35213. if ( frameBufferTarget !== null ) {
  35214. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  35215. const quad = this._quad;
  35216. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  35217. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  35218. quad.material.needsUpdate = true;
  35219. }
  35220. this._renderScene( quad, quad.camera, false );
  35221. }
  35222. //
  35223. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  35224. //
  35225. return renderContext;
  35226. }
  35227. /**
  35228. * Returns the maximum available anisotropy for texture filtering.
  35229. *
  35230. * @return {Number} The maximum available anisotropy.
  35231. */
  35232. getMaxAnisotropy() {
  35233. return this.backend.getMaxAnisotropy();
  35234. }
  35235. /**
  35236. * Returns the active cube face.
  35237. *
  35238. * @return {Number} The active cube face.
  35239. */
  35240. getActiveCubeFace() {
  35241. return this._activeCubeFace;
  35242. }
  35243. /**
  35244. * Returns the active mipmap level.
  35245. *
  35246. * @return {Number} The active mipmap level.
  35247. */
  35248. getActiveMipmapLevel() {
  35249. return this._activeMipmapLevel;
  35250. }
  35251. /**
  35252. * Applications are advised to always define the animation loop
  35253. * with this method and not manually with `requestAnimationFrame()`
  35254. * for best compatibility.
  35255. *
  35256. * @async
  35257. * @param {Function} callback - The application's animation loop.
  35258. * @return {Promise} A Promise that resolves when the set has been executed.
  35259. */
  35260. async setAnimationLoop( callback ) {
  35261. if ( this._initialized === false ) await this.init();
  35262. this._animation.setAnimationLoop( callback );
  35263. }
  35264. /**
  35265. * Can be used to transfer buffer data from a storage buffer attribute
  35266. * from the GPU to the CPU in context of compute shaders.
  35267. *
  35268. * @async
  35269. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  35270. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  35271. */
  35272. async getArrayBufferAsync( attribute ) {
  35273. return await this.backend.getArrayBufferAsync( attribute );
  35274. }
  35275. /**
  35276. * Returns the rendering context.
  35277. *
  35278. * @return {GPUCanvasContext|WebGL2RenderingContext} The rendering context.
  35279. */
  35280. getContext() {
  35281. return this.backend.getContext();
  35282. }
  35283. /**
  35284. * Returns the pixel ratio.
  35285. *
  35286. * @return {Number} The pixel ratio.
  35287. */
  35288. getPixelRatio() {
  35289. return this._pixelRatio;
  35290. }
  35291. /**
  35292. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  35293. *
  35294. * @param {Vector2} target - The method writes the result in this target object.
  35295. * @return {Vector2} The drawing buffer size.
  35296. */
  35297. getDrawingBufferSize( target ) {
  35298. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  35299. }
  35300. /**
  35301. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  35302. *
  35303. * @param {Vector2} target - The method writes the result in this target object.
  35304. * @return {Vector2} The drawing buffer size.
  35305. */
  35306. getSize( target ) {
  35307. return target.set( this._width, this._height );
  35308. }
  35309. /**
  35310. * Sets the given pixel ration and resizes the canvas if necessary.
  35311. *
  35312. * @param {Number} [value=1] - The pixel ratio.
  35313. */
  35314. setPixelRatio( value = 1 ) {
  35315. if ( this._pixelRatio === value ) return;
  35316. this._pixelRatio = value;
  35317. this.setSize( this._width, this._height, false );
  35318. }
  35319. /**
  35320. * This method allows to define the drawing buffer size by specifying
  35321. * width, height and pixel ratio all at once. The size of the drawing
  35322. * buffer is computed with this formula:
  35323. * ````
  35324. * size.x = width * pixelRatio;
  35325. * size.y = height * pixelRatio;
  35326. *```
  35327. *
  35328. * @param {Number} width - The width in logical pixels.
  35329. * @param {Number} height - The height in logical pixels.
  35330. * @param {Number} pixelRatio - The pixel ratio.
  35331. */
  35332. setDrawingBufferSize( width, height, pixelRatio ) {
  35333. this._width = width;
  35334. this._height = height;
  35335. this._pixelRatio = pixelRatio;
  35336. this.domElement.width = Math.floor( width * pixelRatio );
  35337. this.domElement.height = Math.floor( height * pixelRatio );
  35338. this.setViewport( 0, 0, width, height );
  35339. if ( this._initialized ) this.backend.updateSize();
  35340. }
  35341. /**
  35342. * Sets the size of the renderer.
  35343. *
  35344. * @param {Number} width - The width in logical pixels.
  35345. * @param {Number} height - The height in logical pixels.
  35346. * @param {Boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  35347. */
  35348. setSize( width, height, updateStyle = true ) {
  35349. this._width = width;
  35350. this._height = height;
  35351. this.domElement.width = Math.floor( width * this._pixelRatio );
  35352. this.domElement.height = Math.floor( height * this._pixelRatio );
  35353. if ( updateStyle === true ) {
  35354. this.domElement.style.width = width + 'px';
  35355. this.domElement.style.height = height + 'px';
  35356. }
  35357. this.setViewport( 0, 0, width, height );
  35358. if ( this._initialized ) this.backend.updateSize();
  35359. }
  35360. /**
  35361. * Defines a manual sort function for the opaque render list.
  35362. * Pass `null` to use the default sort.
  35363. *
  35364. * @param {Function} method - The sort function.
  35365. */
  35366. setOpaqueSort( method ) {
  35367. this._opaqueSort = method;
  35368. }
  35369. /**
  35370. * Defines a manual sort function for the transparent render list.
  35371. * Pass `null` to use the default sort.
  35372. *
  35373. * @param {Function} method - The sort function.
  35374. */
  35375. setTransparentSort( method ) {
  35376. this._transparentSort = method;
  35377. }
  35378. /**
  35379. * Returns the scissor rectangle.
  35380. *
  35381. * @param {Vector4} target - The method writes the result in this target object.
  35382. * @return {Vector4} The scissor rectangle.
  35383. */
  35384. getScissor( target ) {
  35385. const scissor = this._scissor;
  35386. target.x = scissor.x;
  35387. target.y = scissor.y;
  35388. target.width = scissor.width;
  35389. target.height = scissor.height;
  35390. return target;
  35391. }
  35392. /**
  35393. * Defines the scissor rectangle.
  35394. *
  35395. * @param {Number | Vector4} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  35396. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  35397. * @param {Number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  35398. * @param {Number} width - The width of the scissor box in logical pixel unit.
  35399. * @param {Number} height - The height of the scissor box in logical pixel unit.
  35400. */
  35401. setScissor( x, y, width, height ) {
  35402. const scissor = this._scissor;
  35403. if ( x.isVector4 ) {
  35404. scissor.copy( x );
  35405. } else {
  35406. scissor.set( x, y, width, height );
  35407. }
  35408. }
  35409. /**
  35410. * Returns the scissor test value.
  35411. *
  35412. * @return {Boolean} Whether the scissor test should be enabled or not.
  35413. */
  35414. getScissorTest() {
  35415. return this._scissorTest;
  35416. }
  35417. /**
  35418. * Defines the scissor test.
  35419. *
  35420. * @param {Boolean} boolean - Whether the scissor test should be enabled or not.
  35421. */
  35422. setScissorTest( boolean ) {
  35423. this._scissorTest = boolean;
  35424. this.backend.setScissorTest( boolean );
  35425. }
  35426. /**
  35427. * Returns the viewport definition.
  35428. *
  35429. * @param {Vector4} target - The method writes the result in this target object.
  35430. * @return {Vector4} The viewport definition.
  35431. */
  35432. getViewport( target ) {
  35433. return target.copy( this._viewport );
  35434. }
  35435. /**
  35436. * Defines the viewport.
  35437. *
  35438. * @param {Number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  35439. * @param {Number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  35440. * @param {Number} width - The width of the viewport in logical pixel unit.
  35441. * @param {Number} height - The height of the viewport in logical pixel unit.
  35442. * @param {Number} minDepth - The minimum depth value of the viewport. WebGPU only.
  35443. * @param {Number} maxDepth - The maximum depth value of the viewport. WebGPU only.
  35444. */
  35445. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  35446. const viewport = this._viewport;
  35447. if ( x.isVector4 ) {
  35448. viewport.copy( x );
  35449. } else {
  35450. viewport.set( x, y, width, height );
  35451. }
  35452. viewport.minDepth = minDepth;
  35453. viewport.maxDepth = maxDepth;
  35454. }
  35455. /**
  35456. * Returns the clear color.
  35457. *
  35458. * @param {Color} target - The method writes the result in this target object.
  35459. * @return {Color} The clear color.
  35460. */
  35461. getClearColor( target ) {
  35462. return target.copy( this._clearColor );
  35463. }
  35464. /**
  35465. * Defines the clear color and optionally the clear alpha.
  35466. *
  35467. * @param {Color} color - The clear color.
  35468. * @param {Number} [alpha=1] - The clear alpha.
  35469. */
  35470. setClearColor( color, alpha = 1 ) {
  35471. this._clearColor.set( color );
  35472. this._clearColor.a = alpha;
  35473. }
  35474. /**
  35475. * Returns the clear alpha.
  35476. *
  35477. * @return {Number} The clear alpha.
  35478. */
  35479. getClearAlpha() {
  35480. return this._clearColor.a;
  35481. }
  35482. /**
  35483. * Defines the clear alpha.
  35484. *
  35485. * @param {Number} alpha - The clear alpha.
  35486. */
  35487. setClearAlpha( alpha ) {
  35488. this._clearColor.a = alpha;
  35489. }
  35490. /**
  35491. * Returns the clear depth.
  35492. *
  35493. * @return {Number} The clear depth.
  35494. */
  35495. getClearDepth() {
  35496. return this._clearDepth;
  35497. }
  35498. /**
  35499. * Defines the clear depth.
  35500. *
  35501. * @param {Number} depth - The clear depth.
  35502. */
  35503. setClearDepth( depth ) {
  35504. this._clearDepth = depth;
  35505. }
  35506. /**
  35507. * Returns the clear stencil.
  35508. *
  35509. * @return {Number} The clear stencil.
  35510. */
  35511. getClearStencil() {
  35512. return this._clearStencil;
  35513. }
  35514. /**
  35515. * Defines the clear stencil.
  35516. *
  35517. * @param {Number} stencil - The clear stencil.
  35518. */
  35519. setClearStencil( stencil ) {
  35520. this._clearStencil = stencil;
  35521. }
  35522. /**
  35523. * This method performs an occlusion query for the given 3D object.
  35524. * It returns `true` if the given 3D object is fully occluded by other
  35525. * 3D objects in the scene.
  35526. *
  35527. * @param {Object3D} object - The 3D object to test.
  35528. * @return {Boolean} Whether the 3D object is fully occluded or not.
  35529. */
  35530. isOccluded( object ) {
  35531. const renderContext = this._currentRenderContext;
  35532. return renderContext && this.backend.isOccluded( renderContext, object );
  35533. }
  35534. /**
  35535. * Performs a manual clear operation. This method ignores `autoClear` properties.
  35536. *
  35537. * @param {Boolean} [color=true] - Whether the color buffer should be cleared or not.
  35538. * @param {Boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  35539. * @param {Boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  35540. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  35541. * Only returned when the renderer has not been initialized.
  35542. */
  35543. clear( color = true, depth = true, stencil = true ) {
  35544. if ( this._initialized === false ) {
  35545. console.warn( 'THREE.Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead.' );
  35546. return this.clearAsync( color, depth, stencil );
  35547. }
  35548. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  35549. let renderContext = null;
  35550. if ( renderTarget !== null ) {
  35551. this._textures.updateRenderTarget( renderTarget );
  35552. const renderTargetData = this._textures.get( renderTarget );
  35553. renderContext = this._renderContexts.getForClear( renderTarget );
  35554. renderContext.textures = renderTargetData.textures;
  35555. renderContext.depthTexture = renderTargetData.depthTexture;
  35556. renderContext.width = renderTargetData.width;
  35557. renderContext.height = renderTargetData.height;
  35558. renderContext.renderTarget = renderTarget;
  35559. renderContext.depth = renderTarget.depthBuffer;
  35560. renderContext.stencil = renderTarget.stencilBuffer;
  35561. }
  35562. // #30329
  35563. renderContext.clearColorValue = this._clearColor;
  35564. this.backend.clear( color, depth, stencil, renderContext );
  35565. if ( renderTarget !== null && this._renderTarget === null ) {
  35566. // If a color space transform or tone mapping is required,
  35567. // the clear operation clears the intermediate renderTarget texture, but does not update the screen canvas.
  35568. const quad = this._quad;
  35569. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  35570. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  35571. quad.material.needsUpdate = true;
  35572. }
  35573. this._renderScene( quad, quad.camera, false );
  35574. }
  35575. }
  35576. /**
  35577. * Performs a manual clear operation of the color buffer. This method ignores `autoClear` properties.
  35578. *
  35579. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  35580. * Only returned when the renderer has not been initialized.
  35581. */
  35582. clearColor() {
  35583. return this.clear( true, false, false );
  35584. }
  35585. /**
  35586. * Performs a manual clear operation of the depth buffer. This method ignores `autoClear` properties.
  35587. *
  35588. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  35589. * Only returned when the renderer has not been initialized.
  35590. */
  35591. clearDepth() {
  35592. return this.clear( false, true, false );
  35593. }
  35594. /**
  35595. * Performs a manual clear operation of the stencil buffer. This method ignores `autoClear` properties.
  35596. *
  35597. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  35598. * Only returned when the renderer has not been initialized.
  35599. */
  35600. clearStencil() {
  35601. return this.clear( false, false, true );
  35602. }
  35603. /**
  35604. * Async version of {@link module:Renderer~Renderer#clear}.
  35605. *
  35606. * @async
  35607. * @param {Boolean} [color=true] - Whether the color buffer should be cleared or not.
  35608. * @param {Boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  35609. * @param {Boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  35610. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  35611. */
  35612. async clearAsync( color = true, depth = true, stencil = true ) {
  35613. if ( this._initialized === false ) await this.init();
  35614. this.clear( color, depth, stencil );
  35615. }
  35616. /**
  35617. * Async version of {@link module:Renderer~Renderer#clearColor}.
  35618. *
  35619. * @async
  35620. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  35621. */
  35622. async clearColorAsync() {
  35623. this.clearAsync( true, false, false );
  35624. }
  35625. /**
  35626. * Async version of {@link module:Renderer~Renderer#clearDepth}.
  35627. *
  35628. * @async
  35629. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  35630. */
  35631. async clearDepthAsync() {
  35632. this.clearAsync( false, true, false );
  35633. }
  35634. /**
  35635. * Async version of {@link module:Renderer~Renderer#clearStencil}.
  35636. *
  35637. * @async
  35638. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  35639. */
  35640. async clearStencilAsync() {
  35641. this.clearAsync( false, false, true );
  35642. }
  35643. /**
  35644. * The current output tone mapping of the renderer. When a render target is set,
  35645. * the output tone mapping is always `NoToneMapping`.
  35646. *
  35647. * @type {Number}
  35648. */
  35649. get currentToneMapping() {
  35650. return this._renderTarget !== null ? NoToneMapping : this.toneMapping;
  35651. }
  35652. /**
  35653. * The current output color space of the renderer. When a render target is set,
  35654. * the output color space is always `LinearSRGBColorSpace`.
  35655. *
  35656. * @type {String}
  35657. */
  35658. get currentColorSpace() {
  35659. return this._renderTarget !== null ? LinearSRGBColorSpace : this.outputColorSpace;
  35660. }
  35661. /**
  35662. * Frees all internal resources of the renderer. Call this method if the renderer
  35663. * is no longer in use by your app.
  35664. */
  35665. dispose() {
  35666. this.info.dispose();
  35667. this.backend.dispose();
  35668. this._animation.dispose();
  35669. this._objects.dispose();
  35670. this._pipelines.dispose();
  35671. this._nodes.dispose();
  35672. this._bindings.dispose();
  35673. this._renderLists.dispose();
  35674. this._renderContexts.dispose();
  35675. this._textures.dispose();
  35676. Object.values( this.backend.timestampQueryPool ).forEach( queryPool => {
  35677. if ( queryPool !== null ) queryPool.dispose();
  35678. } );
  35679. this.setRenderTarget( null );
  35680. this.setAnimationLoop( null );
  35681. }
  35682. /**
  35683. * Sets the given render target. Calling this method means the renderer does not
  35684. * target the default framebuffer (meaning the canvas) anymore but a custom framebuffer.
  35685. * Use `null` as the first argument to reset the state.
  35686. *
  35687. * @param {RenderTarget?} renderTarget - The render target to set.
  35688. * @param {Number} [activeCubeFace=0] - The active cube face.
  35689. * @param {Number} [activeMipmapLevel=0] - The active mipmap level.
  35690. */
  35691. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  35692. this._renderTarget = renderTarget;
  35693. this._activeCubeFace = activeCubeFace;
  35694. this._activeMipmapLevel = activeMipmapLevel;
  35695. }
  35696. /**
  35697. * Returns the current render target.
  35698. *
  35699. * @return {RenderTarget?} The render target. Returns `null` if no render target is set.
  35700. */
  35701. getRenderTarget() {
  35702. return this._renderTarget;
  35703. }
  35704. /**
  35705. * Callback for {@link module:Renderer~Renderer#setRenderObjectFunction}.
  35706. *
  35707. * @callback renderObjectFunction
  35708. * @param {Object3D} object - The 3D object.
  35709. * @param {Scene} scene - The scene the 3D object belongs to.
  35710. * @param {Camera} camera - The camera the object should be rendered with.
  35711. * @param {BufferGeometry} geometry - The object's geometry.
  35712. * @param {Material} material - The object's material.
  35713. * @param {Object?} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  35714. * @param {LightsNode} lightsNode - The current lights node.
  35715. * @param {ClippingContext} clippingContext - The clipping context.
  35716. * @param {String?} [passId=null] - An optional ID for identifying the pass.
  35717. */
  35718. /**
  35719. * Sets the given render object function. Calling this method overwrites the default implementation
  35720. * which is {@link module:Renderer~Renderer#renderObject}. Defining a custom function can be useful
  35721. * if you want to modify the way objects are rendered. For example you can define things like "every
  35722. * object that has material of a certain type should perform a pre-pass with a special overwrite material".
  35723. * The custom function must always call `renderObject()` in its implementation.
  35724. *
  35725. * Use `null` as the first argument to reset the state.
  35726. *
  35727. * @param {module:Renderer~renderObjectFunction?} renderObjectFunction - The render object function.
  35728. */
  35729. setRenderObjectFunction( renderObjectFunction ) {
  35730. this._renderObjectFunction = renderObjectFunction;
  35731. }
  35732. /**
  35733. * Returns the current render object function.
  35734. *
  35735. * @return {Function?} The current render object function. Returns `null` if no function is set.
  35736. */
  35737. getRenderObjectFunction() {
  35738. return this._renderObjectFunction;
  35739. }
  35740. /**
  35741. * Execute a single or an array of compute nodes. This method can only be called
  35742. * if the renderer has been initialized.
  35743. *
  35744. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  35745. * @return {Promise?} A Promise that resolve when the compute has finished. Only returned when the renderer has not been initialized.
  35746. */
  35747. compute( computeNodes ) {
  35748. if ( this._isDeviceLost === true ) return;
  35749. if ( this._initialized === false ) {
  35750. console.warn( 'THREE.Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead.' );
  35751. return this.computeAsync( computeNodes );
  35752. }
  35753. //
  35754. const nodeFrame = this._nodes.nodeFrame;
  35755. const previousRenderId = nodeFrame.renderId;
  35756. //
  35757. this.info.calls ++;
  35758. this.info.compute.calls ++;
  35759. this.info.compute.frameCalls ++;
  35760. nodeFrame.renderId = this.info.calls;
  35761. //
  35762. const backend = this.backend;
  35763. const pipelines = this._pipelines;
  35764. const bindings = this._bindings;
  35765. const nodes = this._nodes;
  35766. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  35767. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  35768. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  35769. }
  35770. backend.beginCompute( computeNodes );
  35771. for ( const computeNode of computeList ) {
  35772. // onInit
  35773. if ( pipelines.has( computeNode ) === false ) {
  35774. const dispose = () => {
  35775. computeNode.removeEventListener( 'dispose', dispose );
  35776. pipelines.delete( computeNode );
  35777. bindings.delete( computeNode );
  35778. nodes.delete( computeNode );
  35779. };
  35780. computeNode.addEventListener( 'dispose', dispose );
  35781. //
  35782. const onInitFn = computeNode.onInitFunction;
  35783. if ( onInitFn !== null ) {
  35784. onInitFn.call( computeNode, { renderer: this } );
  35785. }
  35786. }
  35787. nodes.updateForCompute( computeNode );
  35788. bindings.updateForCompute( computeNode );
  35789. const computeBindings = bindings.getForCompute( computeNode );
  35790. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  35791. backend.compute( computeNodes, computeNode, computeBindings, computePipeline );
  35792. }
  35793. backend.finishCompute( computeNodes );
  35794. //
  35795. nodeFrame.renderId = previousRenderId;
  35796. }
  35797. /**
  35798. * Execute a single or an array of compute nodes.
  35799. *
  35800. * @async
  35801. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  35802. * @return {Promise} A Promise that resolve when the compute has finished.
  35803. */
  35804. async computeAsync( computeNodes ) {
  35805. if ( this._initialized === false ) await this.init();
  35806. this.compute( computeNodes );
  35807. }
  35808. /**
  35809. * Checks if the given feature is supported by the selected backend.
  35810. *
  35811. * @async
  35812. * @param {String} name - The feature's name.
  35813. * @return {Promise<Boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  35814. */
  35815. async hasFeatureAsync( name ) {
  35816. if ( this._initialized === false ) await this.init();
  35817. return this.backend.hasFeature( name );
  35818. }
  35819. async resolveTimestampsAsync( type = 'render' ) {
  35820. if ( this._initialized === false ) await this.init();
  35821. return this.backend.resolveTimestampsAsync( type );
  35822. }
  35823. /**
  35824. * Checks if the given feature is supported by the selected backend. If the
  35825. * renderer has not been initialized, this method always returns `false`.
  35826. *
  35827. * @param {String} name - The feature's name.
  35828. * @return {Boolean} Whether the feature is supported or not.
  35829. */
  35830. hasFeature( name ) {
  35831. if ( this._initialized === false ) {
  35832. console.warn( 'THREE.Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead.' );
  35833. return false;
  35834. }
  35835. return this.backend.hasFeature( name );
  35836. }
  35837. /**
  35838. * Returns `true` when the renderer has been initialized.
  35839. *
  35840. * @return {Boolean} Whether the renderer has been initialized or not.
  35841. */
  35842. hasInitialized() {
  35843. return this._initialized;
  35844. }
  35845. /**
  35846. * Initializes the given textures. Useful for preloading a texture rather than waiting until first render
  35847. * (which can cause noticeable lags due to decode and GPU upload overhead).
  35848. *
  35849. * @async
  35850. * @param {Texture} texture - The texture.
  35851. * @return {Promise} A Promise that resolves when the texture has been initialized.
  35852. */
  35853. async initTextureAsync( texture ) {
  35854. if ( this._initialized === false ) await this.init();
  35855. this._textures.updateTexture( texture );
  35856. }
  35857. /**
  35858. * Initializes the given textures. Useful for preloading a texture rather than waiting until first render
  35859. * (which can cause noticeable lags due to decode and GPU upload overhead).
  35860. *
  35861. * This method can only be used if the renderer has been initialized.
  35862. *
  35863. * @param {Texture} texture - The texture.
  35864. */
  35865. initTexture( texture ) {
  35866. if ( this._initialized === false ) {
  35867. console.warn( 'THREE.Renderer: .initTexture() called before the backend is initialized. Try using .initTextureAsync() instead.' );
  35868. }
  35869. this._textures.updateTexture( texture );
  35870. }
  35871. /**
  35872. * Copies the current bound framebuffer into the given texture.
  35873. *
  35874. * @param {FramebufferTexture} framebufferTexture - The texture.
  35875. * @param {Vector2|Vector4} rectangle - A two or four dimensional vector that defines the rectangular portion of the framebuffer that should be copied.
  35876. */
  35877. copyFramebufferToTexture( framebufferTexture, rectangle = null ) {
  35878. if ( rectangle !== null ) {
  35879. if ( rectangle.isVector2 ) {
  35880. rectangle = _vector4.set( rectangle.x, rectangle.y, framebufferTexture.image.width, framebufferTexture.image.height ).floor();
  35881. } else if ( rectangle.isVector4 ) {
  35882. rectangle = _vector4.copy( rectangle ).floor();
  35883. } else {
  35884. console.error( 'THREE.Renderer.copyFramebufferToTexture: Invalid rectangle.' );
  35885. return;
  35886. }
  35887. } else {
  35888. rectangle = _vector4.set( 0, 0, framebufferTexture.image.width, framebufferTexture.image.height );
  35889. }
  35890. //
  35891. let renderContext = this._currentRenderContext;
  35892. let renderTarget;
  35893. if ( renderContext !== null ) {
  35894. renderTarget = renderContext.renderTarget;
  35895. } else {
  35896. renderTarget = this._renderTarget || this._getFrameBufferTarget();
  35897. if ( renderTarget !== null ) {
  35898. this._textures.updateRenderTarget( renderTarget );
  35899. renderContext = this._textures.get( renderTarget );
  35900. }
  35901. }
  35902. //
  35903. this._textures.updateTexture( framebufferTexture, { renderTarget } );
  35904. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext, rectangle );
  35905. }
  35906. /**
  35907. * Copies data of source texture into a destination texture.
  35908. *
  35909. * @param {Texture} srcTexture - The source texture.
  35910. * @param {Texture} dstTexture - The destination texture.
  35911. * @param {Box2|Box3} [srcRegion=null] - A bounding box which describes the source region. Can be two or three-dimensional.
  35912. * @param {Vector2|Vector3} [dstPosition=null] - A vector that represents the origin of the destination region. Can be two or three-dimensional.
  35913. * @param {Number} level - The mipmap level to copy.
  35914. */
  35915. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  35916. this._textures.updateTexture( srcTexture );
  35917. this._textures.updateTexture( dstTexture );
  35918. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  35919. }
  35920. /**
  35921. * Reads pixel data from the given render target.
  35922. *
  35923. * @async
  35924. * @param {RenderTarget} renderTarget - The render target to read from.
  35925. * @param {Number} x - The `x` coordinate of the copy region's origin.
  35926. * @param {Number} y - The `y` coordinate of the copy region's origin.
  35927. * @param {Number} width - The width of the copy region.
  35928. * @param {Number} height - The height of the copy region.
  35929. * @param {Number} [textureIndex=0] - The texture index of a MRT render target.
  35930. * @param {Number} [faceIndex=0] - The active cube face index.
  35931. * @return {Promise<TypedArray>} A Promise that resolves when the read has been finished. The resolve provides the read data as a typed array.
  35932. */
  35933. async readRenderTargetPixelsAsync( renderTarget, x, y, width, height, textureIndex = 0, faceIndex = 0 ) {
  35934. return this.backend.copyTextureToBuffer( renderTarget.textures[ textureIndex ], x, y, width, height, faceIndex );
  35935. }
  35936. /**
  35937. * Analyzes the given 3D object's hierarchy and builds render lists from the
  35938. * processed hierarchy.
  35939. *
  35940. * @param {Object3D} object - The 3D object to process (usually a scene).
  35941. * @param {Camera} camera - The camera the object is rendered with.
  35942. * @param {Number} groupOrder - The group order is derived from the `renderOrder` of groups and is used to group 3D objects within groups.
  35943. * @param {RenderList} renderList - The current render list.
  35944. * @param {ClippingContext} clippingContext - The current clipping context.
  35945. */
  35946. _projectObject( object, camera, groupOrder, renderList, clippingContext ) {
  35947. if ( object.visible === false ) return;
  35948. const visible = object.layers.test( camera.layers );
  35949. if ( visible ) {
  35950. if ( object.isGroup ) {
  35951. groupOrder = object.renderOrder;
  35952. if ( object.isClippingGroup && object.enabled ) clippingContext = clippingContext.getGroupContext( object );
  35953. } else if ( object.isLOD ) {
  35954. if ( object.autoUpdate === true ) object.update( camera );
  35955. } else if ( object.isLight ) {
  35956. renderList.pushLight( object );
  35957. } else if ( object.isSprite ) {
  35958. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  35959. if ( this.sortObjects === true ) {
  35960. _vector4.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  35961. }
  35962. const { geometry, material } = object;
  35963. if ( material.visible ) {
  35964. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  35965. }
  35966. }
  35967. } else if ( object.isLineLoop ) {
  35968. console.error( 'THREE.Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  35969. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  35970. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  35971. const { geometry, material } = object;
  35972. if ( this.sortObjects === true ) {
  35973. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  35974. _vector4
  35975. .copy( geometry.boundingSphere.center )
  35976. .applyMatrix4( object.matrixWorld )
  35977. .applyMatrix4( _projScreenMatrix );
  35978. }
  35979. if ( Array.isArray( material ) ) {
  35980. const groups = geometry.groups;
  35981. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  35982. const group = groups[ i ];
  35983. const groupMaterial = material[ group.materialIndex ];
  35984. if ( groupMaterial && groupMaterial.visible ) {
  35985. renderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group, clippingContext );
  35986. }
  35987. }
  35988. } else if ( material.visible ) {
  35989. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  35990. }
  35991. }
  35992. }
  35993. }
  35994. if ( object.isBundleGroup === true && this.backend.beginBundle !== undefined ) {
  35995. const baseRenderList = renderList;
  35996. // replace render list
  35997. renderList = this._renderLists.get( object, camera );
  35998. renderList.begin();
  35999. baseRenderList.pushBundle( {
  36000. bundleGroup: object,
  36001. camera,
  36002. renderList,
  36003. } );
  36004. renderList.finish();
  36005. }
  36006. const children = object.children;
  36007. for ( let i = 0, l = children.length; i < l; i ++ ) {
  36008. this._projectObject( children[ i ], camera, groupOrder, renderList, clippingContext );
  36009. }
  36010. }
  36011. /**
  36012. * Renders the given render bundles.
  36013. *
  36014. * @private
  36015. * @param {Array<Object>} bundles - Array with render bundle data.
  36016. * @param {Scene} sceneRef - The scene the render bundles belong to.
  36017. * @param {LightsNode} lightsNode - The current lights node.
  36018. */
  36019. _renderBundles( bundles, sceneRef, lightsNode ) {
  36020. for ( const bundle of bundles ) {
  36021. this._renderBundle( bundle, sceneRef, lightsNode );
  36022. }
  36023. }
  36024. /**
  36025. * Renders the transparent objects from the given render lists.
  36026. *
  36027. * @private
  36028. * @param {Array<Object>} renderList - The transparent render list.
  36029. * @param {Array<Object>} doublePassList - The list of transparent objects which require a double pass (e.g. because of transmission).
  36030. * @param {Camera} camera - The camera the render list should be rendered with.
  36031. * @param {Scene} scene - The scene the render list belongs to.
  36032. * @param {LightsNode} lightsNode - The current lights node.
  36033. */
  36034. _renderTransparents( renderList, doublePassList, camera, scene, lightsNode ) {
  36035. if ( doublePassList.length > 0 ) {
  36036. // render back side
  36037. for ( const { material } of doublePassList ) {
  36038. material.side = BackSide;
  36039. }
  36040. this._renderObjects( doublePassList, camera, scene, lightsNode, 'backSide' );
  36041. // render front side
  36042. for ( const { material } of doublePassList ) {
  36043. material.side = FrontSide;
  36044. }
  36045. this._renderObjects( renderList, camera, scene, lightsNode );
  36046. // restore
  36047. for ( const { material } of doublePassList ) {
  36048. material.side = DoubleSide;
  36049. }
  36050. } else {
  36051. this._renderObjects( renderList, camera, scene, lightsNode );
  36052. }
  36053. }
  36054. /**
  36055. * Renders the objects from the given render list.
  36056. *
  36057. * @private
  36058. * @param {Array<Object>} renderList - The render list.
  36059. * @param {Camera} camera - The camera the render list should be rendered with.
  36060. * @param {Scene} scene - The scene the render list belongs to.
  36061. * @param {LightsNode} lightsNode - The current lights node.
  36062. * @param {String?} [passId=null] - An optional ID for identifying the pass.
  36063. */
  36064. _renderObjects( renderList, camera, scene, lightsNode, passId = null ) {
  36065. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  36066. const { object, geometry, material, group, clippingContext } = renderList[ i ];
  36067. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode, clippingContext, passId );
  36068. }
  36069. }
  36070. /**
  36071. * This method represents the default render object function that manages the render lifecycle
  36072. * of the object.
  36073. *
  36074. * @param {Object3D} object - The 3D object.
  36075. * @param {Scene} scene - The scene the 3D object belongs to.
  36076. * @param {Camera} camera - The camera the object should be rendered with.
  36077. * @param {BufferGeometry} geometry - The object's geometry.
  36078. * @param {Material} material - The object's material.
  36079. * @param {Object?} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  36080. * @param {LightsNode} lightsNode - The current lights node.
  36081. * @param {ClippingContext} clippingContext - The clipping context.
  36082. * @param {String?} [passId=null] - An optional ID for identifying the pass.
  36083. */
  36084. renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext = null, passId = null ) {
  36085. let overridePositionNode;
  36086. let overrideColorNode;
  36087. let overrideDepthNode;
  36088. //
  36089. object.onBeforeRender( this, scene, camera, geometry, material, group );
  36090. //
  36091. if ( scene.overrideMaterial !== null ) {
  36092. const overrideMaterial = scene.overrideMaterial;
  36093. if ( material.positionNode && material.positionNode.isNode ) {
  36094. overridePositionNode = overrideMaterial.positionNode;
  36095. overrideMaterial.positionNode = material.positionNode;
  36096. }
  36097. overrideMaterial.alphaTest = material.alphaTest;
  36098. overrideMaterial.alphaMap = material.alphaMap;
  36099. overrideMaterial.transparent = material.transparent || material.transmission > 0;
  36100. if ( overrideMaterial.isShadowPassMaterial ) {
  36101. overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide;
  36102. if ( material.depthNode && material.depthNode.isNode ) {
  36103. overrideDepthNode = overrideMaterial.depthNode;
  36104. overrideMaterial.depthNode = material.depthNode;
  36105. }
  36106. if ( material.castShadowNode && material.castShadowNode.isNode ) {
  36107. overrideColorNode = overrideMaterial.colorNode;
  36108. overrideMaterial.colorNode = material.castShadowNode;
  36109. }
  36110. }
  36111. material = overrideMaterial;
  36112. }
  36113. //
  36114. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  36115. material.side = BackSide;
  36116. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, 'backSide' ); // create backSide pass id
  36117. material.side = FrontSide;
  36118. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId ); // use default pass id
  36119. material.side = DoubleSide;
  36120. } else {
  36121. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId );
  36122. }
  36123. //
  36124. if ( overridePositionNode !== undefined ) {
  36125. scene.overrideMaterial.positionNode = overridePositionNode;
  36126. }
  36127. if ( overrideDepthNode !== undefined ) {
  36128. scene.overrideMaterial.depthNode = overrideDepthNode;
  36129. }
  36130. if ( overrideColorNode !== undefined ) {
  36131. scene.overrideMaterial.colorNode = overrideColorNode;
  36132. }
  36133. //
  36134. object.onAfterRender( this, scene, camera, geometry, material, group );
  36135. }
  36136. /**
  36137. * This method represents the default `_handleObjectFunction` implementation which creates
  36138. * a render object from the given data and performs the draw command with the selected backend.
  36139. *
  36140. * @private
  36141. * @param {Object3D} object - The 3D object.
  36142. * @param {Material} material - The object's material.
  36143. * @param {Scene} scene - The scene the 3D object belongs to.
  36144. * @param {Camera} camera - The camera the object should be rendered with.
  36145. * @param {LightsNode} lightsNode - The current lights node.
  36146. * @param {{start: Number, count: Number}?} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  36147. * @param {ClippingContext} clippingContext - The clipping context.
  36148. * @param {String?} [passId=null] - An optional ID for identifying the pass.
  36149. */
  36150. _renderObjectDirect( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  36151. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  36152. renderObject.drawRange = object.geometry.drawRange;
  36153. renderObject.group = group;
  36154. //
  36155. const needsRefresh = this._nodes.needsRefresh( renderObject );
  36156. if ( needsRefresh ) {
  36157. this._nodes.updateBefore( renderObject );
  36158. this._geometries.updateForRender( renderObject );
  36159. this._nodes.updateForRender( renderObject );
  36160. this._bindings.updateForRender( renderObject );
  36161. }
  36162. this._pipelines.updateForRender( renderObject );
  36163. //
  36164. if ( this._currentRenderBundle !== null ) {
  36165. const renderBundleData = this.backend.get( this._currentRenderBundle );
  36166. renderBundleData.renderObjects.push( renderObject );
  36167. renderObject.bundle = this._currentRenderBundle.bundleGroup;
  36168. }
  36169. this.backend.draw( renderObject, this.info );
  36170. if ( needsRefresh ) this._nodes.updateAfter( renderObject );
  36171. }
  36172. /**
  36173. * A different implementation for `_handleObjectFunction` which only makes sure the object is ready for rendering.
  36174. * Used in `compileAsync()`.
  36175. *
  36176. * @private
  36177. * @param {Object3D} object - The 3D object.
  36178. * @param {Material} material - The object's material.
  36179. * @param {Scene} scene - The scene the 3D object belongs to.
  36180. * @param {Camera} camera - The camera the object should be rendered with.
  36181. * @param {LightsNode} lightsNode - The current lights node.
  36182. * @param {{start: Number, count: Number}?} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  36183. * @param {ClippingContext} clippingContext - The clipping context.
  36184. * @param {String?} [passId=null] - An optional ID for identifying the pass.
  36185. */
  36186. _createObjectPipeline( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  36187. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  36188. renderObject.drawRange = object.geometry.drawRange;
  36189. renderObject.group = group;
  36190. //
  36191. this._nodes.updateBefore( renderObject );
  36192. this._geometries.updateForRender( renderObject );
  36193. this._nodes.updateForRender( renderObject );
  36194. this._bindings.updateForRender( renderObject );
  36195. this._pipelines.getForRender( renderObject, this._compilationPromises );
  36196. this._nodes.updateAfter( renderObject );
  36197. }
  36198. /**
  36199. * Alias for `compileAsync()`.
  36200. *
  36201. * @method
  36202. * @param {Object3D} scene - The scene or 3D object to precompile.
  36203. * @param {Camera} camera - The camera that is used to render the scene.
  36204. * @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.
  36205. * @return {Promise} A Promise that resolves when the compile has been finished.
  36206. */
  36207. get compile() {
  36208. return this.compileAsync;
  36209. }
  36210. }
  36211. /**
  36212. * A binding represents the connection between a resource (like a texture, sampler
  36213. * or uniform buffer) and the resource definition in a shader stage.
  36214. *
  36215. * This module is an abstract base class for all concrete bindings types.
  36216. *
  36217. * @abstract
  36218. * @private
  36219. */
  36220. class Binding {
  36221. /**
  36222. * Constructs a new binding.
  36223. *
  36224. * @param {String} [name=''] - The binding's name.
  36225. */
  36226. constructor( name = '' ) {
  36227. /**
  36228. * The binding's name.
  36229. *
  36230. * @type {String}
  36231. */
  36232. this.name = name;
  36233. /**
  36234. * A bitmask that defines in what shader stages the
  36235. * binding's resource is accessible.
  36236. *
  36237. * @type {Number}
  36238. */
  36239. this.visibility = 0;
  36240. }
  36241. /**
  36242. * Makes sure binding's resource is visible for the given shader stage.
  36243. *
  36244. * @param {Number} visibility - The shader stage.
  36245. */
  36246. setVisibility( visibility ) {
  36247. this.visibility |= visibility;
  36248. }
  36249. /**
  36250. * Clones the binding.
  36251. *
  36252. * @return {Binding} The cloned binding.
  36253. */
  36254. clone() {
  36255. return Object.assign( new this.constructor(), this );
  36256. }
  36257. }
  36258. /** @module BufferUtils **/
  36259. /**
  36260. * This function is usually called with the length in bytes of an array buffer.
  36261. * It returns an padded value which ensure chunk size alignment according to STD140 layout.
  36262. *
  36263. * @function
  36264. * @param {Number} floatLength - The buffer length.
  36265. * @return {Number} The padded length.
  36266. */
  36267. function getFloatLength( floatLength ) {
  36268. // ensure chunk size alignment (STD140 layout)
  36269. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  36270. }
  36271. /**
  36272. * Represents a buffer binding type.
  36273. *
  36274. * @private
  36275. * @abstract
  36276. * @augments Binding
  36277. */
  36278. class Buffer extends Binding {
  36279. /**
  36280. * Constructs a new buffer.
  36281. *
  36282. * @param {String} name - The buffer's name.
  36283. * @param {TypedArray} [buffer=null] - The buffer.
  36284. */
  36285. constructor( name, buffer = null ) {
  36286. super( name );
  36287. /**
  36288. * This flag can be used for type testing.
  36289. *
  36290. * @type {Boolean}
  36291. * @readonly
  36292. * @default true
  36293. */
  36294. this.isBuffer = true;
  36295. /**
  36296. * The bytes per element.
  36297. *
  36298. * @type {Number}
  36299. */
  36300. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  36301. /**
  36302. * A reference to the internal buffer.
  36303. *
  36304. * @private
  36305. * @type {TypedArray}
  36306. */
  36307. this._buffer = buffer;
  36308. }
  36309. /**
  36310. * The buffer's byte length.
  36311. *
  36312. * @type {Number}
  36313. * @readonly
  36314. */
  36315. get byteLength() {
  36316. return getFloatLength( this._buffer.byteLength );
  36317. }
  36318. /**
  36319. * A reference to the internal buffer.
  36320. *
  36321. * @type {Float32Array}
  36322. * @readonly
  36323. */
  36324. get buffer() {
  36325. return this._buffer;
  36326. }
  36327. /**
  36328. * Updates the binding.
  36329. *
  36330. * @return {Boolean} Whether the buffer has been updated and must be
  36331. * uploaded to the GPU.
  36332. */
  36333. update() {
  36334. return true;
  36335. }
  36336. }
  36337. /**
  36338. * Represents a uniform buffer binding type.
  36339. *
  36340. * @private
  36341. * @augments Buffer
  36342. */
  36343. class UniformBuffer extends Buffer {
  36344. /**
  36345. * Constructs a new uniform buffer.
  36346. *
  36347. * @param {String} name - The buffer's name.
  36348. * @param {TypedArray} [buffer=null] - The buffer.
  36349. */
  36350. constructor( name, buffer = null ) {
  36351. super( name, buffer );
  36352. /**
  36353. * This flag can be used for type testing.
  36354. *
  36355. * @type {Boolean}
  36356. * @readonly
  36357. * @default true
  36358. */
  36359. this.isUniformBuffer = true;
  36360. }
  36361. }
  36362. let _id$4 = 0;
  36363. /**
  36364. * A special form of uniform buffer binding type.
  36365. * It's buffer value is managed by a node object.
  36366. *
  36367. * @private
  36368. * @augments UniformBuffer
  36369. */
  36370. class NodeUniformBuffer extends UniformBuffer {
  36371. /**
  36372. * Constructs a new node-based uniform buffer.
  36373. *
  36374. * @param {BufferNode} nodeUniform - The uniform buffer node.
  36375. * @param {UniformGroupNode} groupNode - The uniform group node.
  36376. */
  36377. constructor( nodeUniform, groupNode ) {
  36378. super( 'UniformBuffer_' + _id$4 ++, nodeUniform ? nodeUniform.value : null );
  36379. /**
  36380. * The uniform buffer node.
  36381. *
  36382. * @type {BufferNode}
  36383. */
  36384. this.nodeUniform = nodeUniform;
  36385. /**
  36386. * The uniform group node.
  36387. *
  36388. * @type {UniformGroupNode}
  36389. */
  36390. this.groupNode = groupNode;
  36391. }
  36392. /**
  36393. * The uniform buffer.
  36394. *
  36395. * @type {Float32Array}
  36396. */
  36397. get buffer() {
  36398. return this.nodeUniform.value;
  36399. }
  36400. }
  36401. /**
  36402. * This class represents a uniform buffer binding but with
  36403. * an API that allows to maintain individual uniform objects.
  36404. *
  36405. * @private
  36406. * @augments UniformBuffer
  36407. */
  36408. class UniformsGroup extends UniformBuffer {
  36409. /**
  36410. * Constructs a new uniforms group.
  36411. *
  36412. * @param {String} name - The group's name.
  36413. */
  36414. constructor( name ) {
  36415. super( name );
  36416. /**
  36417. * This flag can be used for type testing.
  36418. *
  36419. * @type {Boolean}
  36420. * @readonly
  36421. * @default true
  36422. */
  36423. this.isUniformsGroup = true;
  36424. /**
  36425. * An array with the raw uniform values.
  36426. *
  36427. * @private
  36428. * @type {Array<Number>?}
  36429. * @default null
  36430. */
  36431. this._values = null;
  36432. /**
  36433. * An array of uniform objects.
  36434. *
  36435. * The order of uniforms in this array must match the order of uniforms in the shader.
  36436. *
  36437. * @type {Array<Uniform>}
  36438. */
  36439. this.uniforms = [];
  36440. }
  36441. /**
  36442. * Adds a uniform to this group.
  36443. *
  36444. * @param {Uniform} uniform - The uniform to add.
  36445. * @return {UniformsGroup} A reference to this group.
  36446. */
  36447. addUniform( uniform ) {
  36448. this.uniforms.push( uniform );
  36449. return this;
  36450. }
  36451. /**
  36452. * Removes a uniform from this group.
  36453. *
  36454. * @param {Uniform} uniform - The uniform to remove.
  36455. * @return {UniformsGroup} A reference to this group.
  36456. */
  36457. removeUniform( uniform ) {
  36458. const index = this.uniforms.indexOf( uniform );
  36459. if ( index !== -1 ) {
  36460. this.uniforms.splice( index, 1 );
  36461. }
  36462. return this;
  36463. }
  36464. /**
  36465. * An array with the raw uniform values.
  36466. *
  36467. * @type {Array<Number>}
  36468. */
  36469. get values() {
  36470. if ( this._values === null ) {
  36471. this._values = Array.from( this.buffer );
  36472. }
  36473. return this._values;
  36474. }
  36475. /**
  36476. * A Float32 array buffer with the uniform values.
  36477. *
  36478. * @type {Float32Array}
  36479. */
  36480. get buffer() {
  36481. let buffer = this._buffer;
  36482. if ( buffer === null ) {
  36483. const byteLength = this.byteLength;
  36484. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  36485. this._buffer = buffer;
  36486. }
  36487. return buffer;
  36488. }
  36489. /**
  36490. * The byte length of the buffer with correct buffer alignment.
  36491. *
  36492. * @type {Number}
  36493. */
  36494. get byteLength() {
  36495. let offset = 0; // global buffer offset in bytes
  36496. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  36497. const uniform = this.uniforms[ i ];
  36498. const { boundary, itemSize } = uniform;
  36499. // offset within a single chunk in bytes
  36500. const chunkOffset = offset % GPU_CHUNK_BYTES;
  36501. const remainingSizeInChunk = GPU_CHUNK_BYTES - chunkOffset;
  36502. // conformance tests
  36503. if ( chunkOffset !== 0 && ( remainingSizeInChunk - boundary ) < 0 ) {
  36504. // check for chunk overflow
  36505. offset += ( GPU_CHUNK_BYTES - chunkOffset );
  36506. } else if ( chunkOffset % boundary !== 0 ) {
  36507. // check for correct alignment
  36508. offset += ( chunkOffset % boundary );
  36509. }
  36510. uniform.offset = ( offset / this.bytesPerElement );
  36511. offset += ( itemSize * this.bytesPerElement );
  36512. }
  36513. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  36514. }
  36515. /**
  36516. * Updates this group by updating each uniform object of
  36517. * the internal uniform list. The uniform objects check if their
  36518. * values has actually changed so this method only returns
  36519. * `true` if there is a real value change.
  36520. *
  36521. * @return {Boolean} Whether the uniforms have been updated and
  36522. * must be uploaded to the GPU.
  36523. */
  36524. update() {
  36525. let updated = false;
  36526. for ( const uniform of this.uniforms ) {
  36527. if ( this.updateByType( uniform ) === true ) {
  36528. updated = true;
  36529. }
  36530. }
  36531. return updated;
  36532. }
  36533. /**
  36534. * Updates a given uniform by calling an update method matching
  36535. * the uniforms type.
  36536. *
  36537. * @param {Uniform} uniform - The uniform to update.
  36538. * @return {Boolean} Whether the uniform has been updated or not.
  36539. */
  36540. updateByType( uniform ) {
  36541. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  36542. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  36543. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  36544. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  36545. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  36546. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  36547. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  36548. console.error( 'THREE.WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  36549. }
  36550. /**
  36551. * Updates a given Number uniform.
  36552. *
  36553. * @param {NumberUniform} uniform - The Number uniform.
  36554. * @return {Boolean} Whether the uniform has been updated or not.
  36555. */
  36556. updateNumber( uniform ) {
  36557. let updated = false;
  36558. const a = this.values;
  36559. const v = uniform.getValue();
  36560. const offset = uniform.offset;
  36561. const type = uniform.getType();
  36562. if ( a[ offset ] !== v ) {
  36563. const b = this._getBufferForType( type );
  36564. b[ offset ] = a[ offset ] = v;
  36565. updated = true;
  36566. }
  36567. return updated;
  36568. }
  36569. /**
  36570. * Updates a given Vector2 uniform.
  36571. *
  36572. * @param {Vector2Uniform} uniform - The Vector2 uniform.
  36573. * @return {Boolean} Whether the uniform has been updated or not.
  36574. */
  36575. updateVector2( uniform ) {
  36576. let updated = false;
  36577. const a = this.values;
  36578. const v = uniform.getValue();
  36579. const offset = uniform.offset;
  36580. const type = uniform.getType();
  36581. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  36582. const b = this._getBufferForType( type );
  36583. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  36584. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  36585. updated = true;
  36586. }
  36587. return updated;
  36588. }
  36589. /**
  36590. * Updates a given Vector3 uniform.
  36591. *
  36592. * @param {Vector3Uniform} uniform - The Vector3 uniform.
  36593. * @return {Boolean} Whether the uniform has been updated or not.
  36594. */
  36595. updateVector3( uniform ) {
  36596. let updated = false;
  36597. const a = this.values;
  36598. const v = uniform.getValue();
  36599. const offset = uniform.offset;
  36600. const type = uniform.getType();
  36601. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  36602. const b = this._getBufferForType( type );
  36603. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  36604. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  36605. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  36606. updated = true;
  36607. }
  36608. return updated;
  36609. }
  36610. /**
  36611. * Updates a given Vector4 uniform.
  36612. *
  36613. * @param {Vector4Uniform} uniform - The Vector4 uniform.
  36614. * @return {Boolean} Whether the uniform has been updated or not.
  36615. */
  36616. updateVector4( uniform ) {
  36617. let updated = false;
  36618. const a = this.values;
  36619. const v = uniform.getValue();
  36620. const offset = uniform.offset;
  36621. const type = uniform.getType();
  36622. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 4 ] !== v.w ) {
  36623. const b = this._getBufferForType( type );
  36624. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  36625. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  36626. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  36627. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  36628. updated = true;
  36629. }
  36630. return updated;
  36631. }
  36632. /**
  36633. * Updates a given Color uniform.
  36634. *
  36635. * @param {ColorUniform} uniform - The Color uniform.
  36636. * @return {Boolean} Whether the uniform has been updated or not.
  36637. */
  36638. updateColor( uniform ) {
  36639. let updated = false;
  36640. const a = this.values;
  36641. const c = uniform.getValue();
  36642. const offset = uniform.offset;
  36643. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  36644. const b = this.buffer;
  36645. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  36646. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  36647. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  36648. updated = true;
  36649. }
  36650. return updated;
  36651. }
  36652. /**
  36653. * Updates a given Matrix3 uniform.
  36654. *
  36655. * @param {Matrix3Uniform} uniform - The Matrix3 uniform.
  36656. * @return {Boolean} Whether the uniform has been updated or not.
  36657. */
  36658. updateMatrix3( uniform ) {
  36659. let updated = false;
  36660. const a = this.values;
  36661. const e = uniform.getValue().elements;
  36662. const offset = uniform.offset;
  36663. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  36664. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  36665. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  36666. const b = this.buffer;
  36667. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  36668. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  36669. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  36670. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  36671. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  36672. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  36673. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  36674. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  36675. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  36676. updated = true;
  36677. }
  36678. return updated;
  36679. }
  36680. /**
  36681. * Updates a given Matrix4 uniform.
  36682. *
  36683. * @param {Matrix4Uniform} uniform - The Matrix4 uniform.
  36684. * @return {Boolean} Whether the uniform has been updated or not.
  36685. */
  36686. updateMatrix4( uniform ) {
  36687. let updated = false;
  36688. const a = this.values;
  36689. const e = uniform.getValue().elements;
  36690. const offset = uniform.offset;
  36691. if ( arraysEqual( a, e, offset ) === false ) {
  36692. const b = this.buffer;
  36693. b.set( e, offset );
  36694. setArray( a, e, offset );
  36695. updated = true;
  36696. }
  36697. return updated;
  36698. }
  36699. /**
  36700. * Returns a typed array that matches the given data type.
  36701. *
  36702. * @param {String} type - The data type.
  36703. * @return {TypedArray} The typed array.
  36704. */
  36705. _getBufferForType( type ) {
  36706. if ( type === 'int' || type === 'ivec2' || type === 'ivec3' || type === 'ivec4' ) return new Int32Array( this.buffer.buffer );
  36707. if ( type === 'uint' || type === 'uvec2' || type === 'uvec3' || type === 'uvec4' ) return new Uint32Array( this.buffer.buffer );
  36708. return this.buffer;
  36709. }
  36710. }
  36711. /**
  36712. * Sets the values of the second array to the first array.
  36713. *
  36714. * @private
  36715. * @param {TypedArray} a - The first array.
  36716. * @param {TypedArray} b - The second array.
  36717. * @param {Number} offset - An index offset for the first array.
  36718. */
  36719. function setArray( a, b, offset ) {
  36720. for ( let i = 0, l = b.length; i < l; i ++ ) {
  36721. a[ offset + i ] = b[ i ];
  36722. }
  36723. }
  36724. /**
  36725. * Returns `true` if the given arrays are equal.
  36726. *
  36727. * @private
  36728. * @param {TypedArray} a - The first array.
  36729. * @param {TypedArray} b - The second array.
  36730. * @param {Number} offset - An index offset for the first array.
  36731. * @return {Boolean} Whether the given arrays are equal or not.
  36732. */
  36733. function arraysEqual( a, b, offset ) {
  36734. for ( let i = 0, l = b.length; i < l; i ++ ) {
  36735. if ( a[ offset + i ] !== b[ i ] ) return false;
  36736. }
  36737. return true;
  36738. }
  36739. let _id$3 = 0;
  36740. /**
  36741. * A special form of uniforms group that represents
  36742. * the individual uniforms as node-based uniforms.
  36743. *
  36744. * @private
  36745. * @augments UniformsGroup
  36746. */
  36747. class NodeUniformsGroup extends UniformsGroup {
  36748. /**
  36749. * Constructs a new node-based uniforms group.
  36750. *
  36751. * @param {String} name - The group's name.
  36752. * @param {UniformGroupNode} groupNode - The uniform group node.
  36753. */
  36754. constructor( name, groupNode ) {
  36755. super( name );
  36756. /**
  36757. * The group's ID.
  36758. *
  36759. * @type {Number}
  36760. */
  36761. this.id = _id$3 ++;
  36762. /**
  36763. * The uniform group node.
  36764. *
  36765. * @type {UniformGroupNode}
  36766. */
  36767. this.groupNode = groupNode;
  36768. /**
  36769. * This flag can be used for type testing.
  36770. *
  36771. * @type {Boolean}
  36772. * @readonly
  36773. * @default true
  36774. */
  36775. this.isNodeUniformsGroup = true;
  36776. }
  36777. }
  36778. let _id$2 = 0;
  36779. /**
  36780. * Represents a sampled texture binding type.
  36781. *
  36782. * @private
  36783. * @augments Binding
  36784. */
  36785. class SampledTexture extends Binding {
  36786. /**
  36787. * Constructs a new sampled texture.
  36788. *
  36789. * @param {String} name - The sampled texture's name.
  36790. * @param {Texture?} texture - The texture this binding is referring to.
  36791. */
  36792. constructor( name, texture ) {
  36793. super( name );
  36794. /**
  36795. * This identifier.
  36796. *
  36797. * @type {Number}
  36798. */
  36799. this.id = _id$2 ++;
  36800. /**
  36801. * The texture this binding is referring to.
  36802. *
  36803. * @type {Texture?}
  36804. */
  36805. this.texture = texture;
  36806. /**
  36807. * The binding's version.
  36808. *
  36809. * @type {Number}
  36810. */
  36811. this.version = texture ? texture.version : 0;
  36812. /**
  36813. * Whether the texture is a storage texture or not.
  36814. *
  36815. * @type {Boolean}
  36816. * @default false
  36817. */
  36818. this.store = false;
  36819. /**
  36820. * The binding's generation which is an additional version
  36821. * qualifier.
  36822. *
  36823. * @type {Number?}
  36824. * @default null
  36825. */
  36826. this.generation = null;
  36827. /**
  36828. * This flag can be used for type testing.
  36829. *
  36830. * @type {Boolean}
  36831. * @readonly
  36832. * @default true
  36833. */
  36834. this.isSampledTexture = true;
  36835. }
  36836. /**
  36837. * Returns `true` whether this binding requires an update for the
  36838. * given generation.
  36839. *
  36840. * @param {Number} generation - The generation.
  36841. * @return {Boolean} Whether an update is required or not.
  36842. */
  36843. needsBindingsUpdate( generation ) {
  36844. const { texture } = this;
  36845. if ( generation !== this.generation ) {
  36846. this.generation = generation;
  36847. return true;
  36848. }
  36849. return texture.isVideoTexture;
  36850. }
  36851. /**
  36852. * Updates the binding.
  36853. *
  36854. * @return {Boolean} Whether the texture has been updated and must be
  36855. * uploaded to the GPU.
  36856. */
  36857. update() {
  36858. const { texture, version } = this;
  36859. if ( version !== texture.version ) {
  36860. this.version = texture.version;
  36861. return true;
  36862. }
  36863. return false;
  36864. }
  36865. }
  36866. /**
  36867. * A special form of sampled texture binding type.
  36868. * It's texture value is managed by a node object.
  36869. *
  36870. * @private
  36871. * @augments SampledTexture
  36872. */
  36873. class NodeSampledTexture extends SampledTexture {
  36874. /**
  36875. * Constructs a new node-based sampled texture.
  36876. *
  36877. * @param {String} name - The textures's name.
  36878. * @param {TextureNode} textureNode - The texture node.
  36879. * @param {UniformGroupNode} groupNode - The uniform group node.
  36880. * @param {String?} [access=null] - The access type.
  36881. */
  36882. constructor( name, textureNode, groupNode, access = null ) {
  36883. super( name, textureNode ? textureNode.value : null );
  36884. /**
  36885. * The texture node.
  36886. *
  36887. * @type {TextureNode}
  36888. */
  36889. this.textureNode = textureNode;
  36890. /**
  36891. * The uniform group node.
  36892. *
  36893. * @type {UniformGroupNode}
  36894. */
  36895. this.groupNode = groupNode;
  36896. /**
  36897. * The access type.
  36898. *
  36899. * @type {String?}
  36900. * @default null
  36901. */
  36902. this.access = access;
  36903. }
  36904. /**
  36905. * Overwrites the default to additionally check if the node value has changed.
  36906. *
  36907. * @param {Number} generation - The generation.
  36908. * @return {Boolean} Whether an update is required or not.
  36909. */
  36910. needsBindingsUpdate( generation ) {
  36911. return this.textureNode.value !== this.texture || super.needsBindingsUpdate( generation );
  36912. }
  36913. /**
  36914. * Updates the binding.
  36915. *
  36916. * @return {Boolean} Whether the texture has been updated and must be
  36917. * uploaded to the GPU.
  36918. */
  36919. update() {
  36920. const { textureNode } = this;
  36921. if ( this.texture !== textureNode.value ) {
  36922. this.texture = textureNode.value;
  36923. return true;
  36924. }
  36925. return super.update();
  36926. }
  36927. }
  36928. /**
  36929. * A special form of sampled cube texture binding type.
  36930. * It's texture value is managed by a node object.
  36931. *
  36932. * @private
  36933. * @augments NodeSampledTexture
  36934. */
  36935. class NodeSampledCubeTexture extends NodeSampledTexture {
  36936. /**
  36937. * Constructs a new node-based sampled cube texture.
  36938. *
  36939. * @param {String} name - The textures's name.
  36940. * @param {TextureNode} textureNode - The texture node.
  36941. * @param {UniformGroupNode} groupNode - The uniform group node.
  36942. * @param {String?} [access=null] - The access type.
  36943. */
  36944. constructor( name, textureNode, groupNode, access = null ) {
  36945. super( name, textureNode, groupNode, access );
  36946. /**
  36947. * This flag can be used for type testing.
  36948. *
  36949. * @type {Boolean}
  36950. * @readonly
  36951. * @default true
  36952. */
  36953. this.isSampledCubeTexture = true;
  36954. }
  36955. }
  36956. /**
  36957. * A special form of sampled 3D texture binding type.
  36958. * It's texture value is managed by a node object.
  36959. *
  36960. * @private
  36961. * @augments NodeSampledTexture
  36962. */
  36963. class NodeSampledTexture3D extends NodeSampledTexture {
  36964. /**
  36965. * Constructs a new node-based sampled 3D texture.
  36966. *
  36967. * @param {String} name - The textures's name.
  36968. * @param {TextureNode} textureNode - The texture node.
  36969. * @param {UniformGroupNode} groupNode - The uniform group node.
  36970. * @param {String?} [access=null] - The access type.
  36971. */
  36972. constructor( name, textureNode, groupNode, access = null ) {
  36973. super( name, textureNode, groupNode, access );
  36974. /**
  36975. * This flag can be used for type testing.
  36976. *
  36977. * @type {Boolean}
  36978. * @readonly
  36979. * @default true
  36980. */
  36981. this.isSampledTexture3D = true;
  36982. }
  36983. }
  36984. const glslMethods = {
  36985. textureDimensions: 'textureSize',
  36986. equals: 'equal'
  36987. };
  36988. const precisionLib = {
  36989. low: 'lowp',
  36990. medium: 'mediump',
  36991. high: 'highp'
  36992. };
  36993. const supports$1 = {
  36994. swizzleAssign: true,
  36995. storageBuffer: false
  36996. };
  36997. const defaultPrecisions = `
  36998. precision highp float;
  36999. precision highp int;
  37000. precision highp sampler2D;
  37001. precision highp sampler3D;
  37002. precision highp samplerCube;
  37003. precision highp sampler2DArray;
  37004. precision highp usampler2D;
  37005. precision highp usampler3D;
  37006. precision highp usamplerCube;
  37007. precision highp usampler2DArray;
  37008. precision highp isampler2D;
  37009. precision highp isampler3D;
  37010. precision highp isamplerCube;
  37011. precision highp isampler2DArray;
  37012. precision lowp sampler2DShadow;
  37013. `;
  37014. /**
  37015. * A node builder targeting GLSL.
  37016. *
  37017. * This module generates GLSL shader code from node materials and also
  37018. * generates the respective bindings and vertex buffer definitions. These
  37019. * data are later used by the renderer to create render and compute pipelines
  37020. * for render objects.
  37021. *
  37022. * @augments NodeBuilder
  37023. */
  37024. class GLSLNodeBuilder extends NodeBuilder {
  37025. /**
  37026. * Constructs a new GLSL node builder renderer.
  37027. *
  37028. * @param {Object3D} object - The 3D object.
  37029. * @param {Renderer} renderer - The renderer.
  37030. */
  37031. constructor( object, renderer ) {
  37032. super( object, renderer, new GLSLNodeParser() );
  37033. /**
  37034. * A dictionary holds for each shader stage ('vertex', 'fragment', 'compute')
  37035. * another dictionary which manages UBOs per group ('render','frame','object').
  37036. *
  37037. * @type {Object<String,Object<String,NodeUniformsGroup>>}
  37038. */
  37039. this.uniformGroups = {};
  37040. /**
  37041. * An array that holds objects defining the varying and attribute data in
  37042. * context of Transform Feedback.
  37043. *
  37044. * @type {Object<String,Map<String,Object>>}
  37045. */
  37046. this.transforms = [];
  37047. /**
  37048. * A dictionary that holds for each shader stage a Map of used extensions.
  37049. *
  37050. * @type {Object<String,Map<String,Object>>}
  37051. */
  37052. this.extensions = {};
  37053. /**
  37054. * A dictionary that holds for each shader stage an Array of used builtins.
  37055. *
  37056. * @type {Object<String,Array<String>>}
  37057. */
  37058. this.builtins = { vertex: [], fragment: [], compute: [] };
  37059. /**
  37060. * Whether comparison in shader code are generated with methods or not.
  37061. *
  37062. * @type {Boolean}
  37063. * @default true
  37064. */
  37065. this.useComparisonMethod = true;
  37066. }
  37067. /**
  37068. * Checks if the given texture requires a manual conversion to the working color space.
  37069. *
  37070. * @param {Texture} texture - The texture to check.
  37071. * @return {Boolean} Whether the given texture requires a conversion to working color space or not.
  37072. */
  37073. needsToWorkingColorSpace( texture ) {
  37074. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  37075. }
  37076. /**
  37077. * Returns the native shader method name for a given generic name.
  37078. *
  37079. * @param {String} method - The method name to resolve.
  37080. * @return {String} The resolved GLSL method name.
  37081. */
  37082. getMethod( method ) {
  37083. return glslMethods[ method ] || method;
  37084. }
  37085. /**
  37086. * Returns the output struct name. Not relevant for GLSL.
  37087. *
  37088. * @return {String}
  37089. */
  37090. getOutputStructName() {
  37091. return '';
  37092. }
  37093. /**
  37094. * Builds the given shader node.
  37095. *
  37096. * @param {ShaderNodeInternal} shaderNode - The shader node.
  37097. * @return {String} The GLSL function code.
  37098. */
  37099. buildFunctionCode( shaderNode ) {
  37100. const layout = shaderNode.layout;
  37101. const flowData = this.flowShaderNode( shaderNode );
  37102. const parameters = [];
  37103. for ( const input of layout.inputs ) {
  37104. parameters.push( this.getType( input.type ) + ' ' + input.name );
  37105. }
  37106. //
  37107. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  37108. ${ flowData.vars }
  37109. ${ flowData.code }
  37110. return ${ flowData.result };
  37111. }`;
  37112. //
  37113. return code;
  37114. }
  37115. /**
  37116. * Setups the Pixel Buffer Object (PBO) for the given storage
  37117. * buffer node.
  37118. *
  37119. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  37120. */
  37121. setupPBO( storageBufferNode ) {
  37122. const attribute = storageBufferNode.value;
  37123. if ( attribute.pbo === undefined ) {
  37124. const originalArray = attribute.array;
  37125. const numElements = attribute.count * attribute.itemSize;
  37126. const { itemSize } = attribute;
  37127. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  37128. let format = isInteger ? RedIntegerFormat : RedFormat;
  37129. if ( itemSize === 2 ) {
  37130. format = isInteger ? RGIntegerFormat : RGFormat;
  37131. } else if ( itemSize === 3 ) {
  37132. format = isInteger ? RGBIntegerFormat : RGBFormat;
  37133. } else if ( itemSize === 4 ) {
  37134. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  37135. }
  37136. const typeMap = {
  37137. Float32Array: FloatType,
  37138. Uint8Array: UnsignedByteType,
  37139. Uint16Array: UnsignedShortType,
  37140. Uint32Array: UnsignedIntType,
  37141. Int8Array: ByteType,
  37142. Int16Array: ShortType,
  37143. Int32Array: IntType,
  37144. Uint8ClampedArray: UnsignedByteType,
  37145. };
  37146. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  37147. let height = Math.ceil( ( numElements / itemSize ) / width );
  37148. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  37149. const newSize = width * height * itemSize;
  37150. const newArray = new originalArray.constructor( newSize );
  37151. newArray.set( originalArray, 0 );
  37152. attribute.array = newArray;
  37153. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  37154. pboTexture.needsUpdate = true;
  37155. pboTexture.isPBOTexture = true;
  37156. const pbo = new TextureNode( pboTexture, null, null );
  37157. pbo.setPrecision( 'high' );
  37158. attribute.pboNode = pbo;
  37159. attribute.pbo = pbo.value;
  37160. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  37161. }
  37162. }
  37163. /**
  37164. * Returns a GLSL snippet that represents the property name of the given node.
  37165. *
  37166. * @param {Node} node - The node.
  37167. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  37168. * @return {String} The property name.
  37169. */
  37170. getPropertyName( node, shaderStage = this.shaderStage ) {
  37171. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  37172. return shaderStage.charAt( 0 ) + '_' + node.name;
  37173. }
  37174. return super.getPropertyName( node, shaderStage );
  37175. }
  37176. /**
  37177. * Setups the Pixel Buffer Object (PBO) for the given storage
  37178. * buffer node.
  37179. *
  37180. * @param {StorageArrayElementNode} storageArrayElementNode - The storage array element node.
  37181. * @return {String} The property name.
  37182. */
  37183. generatePBO( storageArrayElementNode ) {
  37184. const { node, indexNode } = storageArrayElementNode;
  37185. const attribute = node.value;
  37186. if ( this.renderer.backend.has( attribute ) ) {
  37187. const attributeData = this.renderer.backend.get( attribute );
  37188. attributeData.pbo = attribute.pbo;
  37189. }
  37190. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  37191. const textureName = this.getPropertyName( nodeUniform );
  37192. this.increaseUsage( indexNode ); // force cache generate to be used as index in x,y
  37193. const indexSnippet = indexNode.build( this, 'uint' );
  37194. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  37195. let propertyName = elementNodeData.propertyName;
  37196. if ( propertyName === undefined ) {
  37197. // property element
  37198. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  37199. propertyName = this.getPropertyName( nodeVar );
  37200. // property size
  37201. const bufferNodeData = this.getDataFromNode( node );
  37202. let propertySizeName = bufferNodeData.propertySizeName;
  37203. if ( propertySizeName === undefined ) {
  37204. propertySizeName = propertyName + 'Size';
  37205. this.getVarFromNode( node, propertySizeName, 'uint' );
  37206. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )`, storageArrayElementNode );
  37207. bufferNodeData.propertySizeName = propertySizeName;
  37208. }
  37209. //
  37210. const { itemSize } = attribute;
  37211. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  37212. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  37213. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, null, '0' );
  37214. //
  37215. let prefix = 'vec4';
  37216. if ( attribute.pbo.type === UnsignedIntType ) {
  37217. prefix = 'uvec4';
  37218. } else if ( attribute.pbo.type === IntType ) {
  37219. prefix = 'ivec4';
  37220. }
  37221. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}`, storageArrayElementNode );
  37222. elementNodeData.propertyName = propertyName;
  37223. }
  37224. return propertyName;
  37225. }
  37226. /**
  37227. * Generates the GLSL snippet that reads a single texel from a texture without sampling or filtering.
  37228. *
  37229. * @param {Texture} texture - The texture.
  37230. * @param {String} textureProperty - The name of the texture uniform in the shader.
  37231. * @param {String} uvIndexSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  37232. * @param {String?} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  37233. * @param {String} [levelSnippet='0u'] - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  37234. * @return {String} The GLSL snippet.
  37235. */
  37236. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0' ) {
  37237. if ( depthSnippet ) {
  37238. return `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  37239. } else {
  37240. return `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  37241. }
  37242. }
  37243. /**
  37244. * Generates the GLSL snippet for sampling/loading the given texture.
  37245. *
  37246. * @param {Texture} texture - The texture.
  37247. * @param {String} textureProperty - The name of the texture uniform in the shader.
  37248. * @param {String} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  37249. * @param {String?} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  37250. * @return {String} The GLSL snippet.
  37251. */
  37252. generateTexture( texture, textureProperty, uvSnippet, depthSnippet ) {
  37253. if ( texture.isDepthTexture ) {
  37254. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  37255. } else {
  37256. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  37257. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  37258. }
  37259. }
  37260. /**
  37261. * Generates the GLSL snippet when sampling textures with explicit mip level.
  37262. *
  37263. * @param {Texture} texture - The texture.
  37264. * @param {String} textureProperty - The name of the texture uniform in the shader.
  37265. * @param {String} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  37266. * @param {String} levelSnippet - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  37267. * @return {String} The GLSL snippet.
  37268. */
  37269. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet ) {
  37270. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  37271. }
  37272. /**
  37273. * Generates the GLSL snippet when sampling textures with a bias to the mip level.
  37274. *
  37275. * @param {Texture} texture - The texture.
  37276. * @param {String} textureProperty - The name of the texture uniform in the shader.
  37277. * @param {String} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  37278. * @param {String} biasSnippet - A GLSL snippet that represents the bias to apply to the mip level before sampling.
  37279. * @return {String} The GLSL snippet.
  37280. */
  37281. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet ) {
  37282. return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
  37283. }
  37284. /**
  37285. * Generates the GLSL snippet for sampling/loading the given texture using explicit gradients.
  37286. *
  37287. * @param {Texture} texture - The texture.
  37288. * @param {String} textureProperty - The name of the texture uniform in the shader.
  37289. * @param {String} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  37290. * @param {Array<String>} gradSnippet - An array holding both gradient GLSL snippets.
  37291. * @return {String} The GLSL snippet.
  37292. */
  37293. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet ) {
  37294. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  37295. }
  37296. /**
  37297. * Generates the GLSL snippet for sampling a depth texture and comparing the sampled depth values
  37298. * against a reference value.
  37299. *
  37300. * @param {Texture} texture - The texture.
  37301. * @param {String} textureProperty - The name of the texture uniform in the shader.
  37302. * @param {String} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  37303. * @param {String} compareSnippet - A GLSL snippet that represents the reference value.
  37304. * @param {String?} depthSnippet - A GLSL snippet that represents 0-based texture array index to sample.
  37305. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  37306. * @return {String} The GLSL snippet.
  37307. */
  37308. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  37309. if ( shaderStage === 'fragment' ) {
  37310. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  37311. } else {
  37312. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  37313. }
  37314. }
  37315. /**
  37316. * Returns the variables of the given shader stage as a GLSL string.
  37317. *
  37318. * @param {String} shaderStage - The shader stage.
  37319. * @return {String} The GLSL snippet that defines the variables.
  37320. */
  37321. getVars( shaderStage ) {
  37322. const snippets = [];
  37323. const vars = this.vars[ shaderStage ];
  37324. if ( vars !== undefined ) {
  37325. for ( const variable of vars ) {
  37326. snippets.push( `${ this.getVar( variable.type, variable.name, variable.count ) };` );
  37327. }
  37328. }
  37329. return snippets.join( '\n\t' );
  37330. }
  37331. /**
  37332. * Returns the uniforms of the given shader stage as a GLSL string.
  37333. *
  37334. * @param {String} shaderStage - The shader stage.
  37335. * @return {String} The GLSL snippet that defines the uniforms.
  37336. */
  37337. getUniforms( shaderStage ) {
  37338. const uniforms = this.uniforms[ shaderStage ];
  37339. const bindingSnippets = [];
  37340. const uniformGroups = {};
  37341. for ( const uniform of uniforms ) {
  37342. let snippet = null;
  37343. let group = false;
  37344. if ( uniform.type === 'texture' ) {
  37345. const texture = uniform.node.value;
  37346. let typePrefix = '';
  37347. if ( texture.isDataTexture === true ) {
  37348. if ( texture.type === UnsignedIntType ) {
  37349. typePrefix = 'u';
  37350. } else if ( texture.type === IntType ) {
  37351. typePrefix = 'i';
  37352. }
  37353. }
  37354. if ( texture.compareFunction ) {
  37355. snippet = `sampler2DShadow ${ uniform.name };`;
  37356. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  37357. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  37358. } else {
  37359. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  37360. }
  37361. } else if ( uniform.type === 'cubeTexture' ) {
  37362. snippet = `samplerCube ${ uniform.name };`;
  37363. } else if ( uniform.type === 'texture3D' ) {
  37364. snippet = `sampler3D ${ uniform.name };`;
  37365. } else if ( uniform.type === 'buffer' ) {
  37366. const bufferNode = uniform.node;
  37367. const bufferType = this.getType( bufferNode.bufferType );
  37368. const bufferCount = bufferNode.bufferCount;
  37369. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  37370. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  37371. } else {
  37372. const vectorType = this.getVectorType( uniform.type );
  37373. snippet = `${ vectorType } ${ this.getPropertyName( uniform, shaderStage ) };`;
  37374. group = true;
  37375. }
  37376. const precision = uniform.node.precision;
  37377. if ( precision !== null ) {
  37378. snippet = precisionLib[ precision ] + ' ' + snippet;
  37379. }
  37380. if ( group ) {
  37381. snippet = '\t' + snippet;
  37382. const groupName = uniform.groupNode.name;
  37383. const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
  37384. groupSnippets.push( snippet );
  37385. } else {
  37386. snippet = 'uniform ' + snippet;
  37387. bindingSnippets.push( snippet );
  37388. }
  37389. }
  37390. let output = '';
  37391. for ( const name in uniformGroups ) {
  37392. const groupSnippets = uniformGroups[ name ];
  37393. output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
  37394. }
  37395. output += bindingSnippets.join( '\n' );
  37396. return output;
  37397. }
  37398. /**
  37399. * Returns the type for a given buffer attribute.
  37400. *
  37401. * @param {BufferAttribute} attribute - The buffer attribute.
  37402. * @return {String} The type.
  37403. */
  37404. getTypeFromAttribute( attribute ) {
  37405. let nodeType = super.getTypeFromAttribute( attribute );
  37406. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  37407. let dataAttribute = attribute;
  37408. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  37409. const array = dataAttribute.array;
  37410. if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
  37411. nodeType = nodeType.slice( 1 );
  37412. }
  37413. }
  37414. return nodeType;
  37415. }
  37416. /**
  37417. * Returns the shader attributes of the given shader stage as a GLSL string.
  37418. *
  37419. * @param {String} shaderStage - The shader stage.
  37420. * @return {String} The GLSL snippet that defines the shader attributes.
  37421. */
  37422. getAttributes( shaderStage ) {
  37423. let snippet = '';
  37424. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  37425. const attributes = this.getAttributesArray();
  37426. let location = 0;
  37427. for ( const attribute of attributes ) {
  37428. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  37429. }
  37430. }
  37431. return snippet;
  37432. }
  37433. /**
  37434. * Returns the members of the given struct type node as a GLSL string.
  37435. *
  37436. * @param {StructTypeNode} struct - The struct type node.
  37437. * @return {String} The GLSL snippet that defines the struct members.
  37438. */
  37439. getStructMembers( struct ) {
  37440. const snippets = [];
  37441. const members = struct.getMemberTypes();
  37442. for ( let i = 0; i < members.length; i ++ ) {
  37443. const member = members[ i ];
  37444. snippets.push( `layout( location = ${i} ) out ${ member} m${i};` );
  37445. }
  37446. return snippets.join( '\n' );
  37447. }
  37448. /**
  37449. * Returns the structs of the given shader stage as a GLSL string.
  37450. *
  37451. * @param {String} shaderStage - The shader stage.
  37452. * @return {String} The GLSL snippet that defines the structs.
  37453. */
  37454. getStructs( shaderStage ) {
  37455. const snippets = [];
  37456. const structs = this.structs[ shaderStage ];
  37457. if ( structs.length === 0 ) {
  37458. return 'layout( location = 0 ) out vec4 fragColor;\n';
  37459. }
  37460. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  37461. const struct = structs[ index ];
  37462. let snippet = '\n';
  37463. snippet += this.getStructMembers( struct );
  37464. snippet += '\n';
  37465. snippets.push( snippet );
  37466. }
  37467. return snippets.join( '\n\n' );
  37468. }
  37469. /**
  37470. * Returns the varyings of the given shader stage as a GLSL string.
  37471. *
  37472. * @param {String} shaderStage - The shader stage.
  37473. * @return {String} The GLSL snippet that defines the varyings.
  37474. */
  37475. getVaryings( shaderStage ) {
  37476. let snippet = '';
  37477. const varyings = this.varyings;
  37478. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  37479. for ( const varying of varyings ) {
  37480. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  37481. const type = this.getType( varying.type );
  37482. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  37483. snippet += `${flat}${varying.needsInterpolation ? 'out' : '/*out*/'} ${type} ${varying.name};\n`;
  37484. }
  37485. } else if ( shaderStage === 'fragment' ) {
  37486. for ( const varying of varyings ) {
  37487. if ( varying.needsInterpolation ) {
  37488. const type = this.getType( varying.type );
  37489. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  37490. snippet += `${flat}in ${type} ${varying.name};\n`;
  37491. }
  37492. }
  37493. }
  37494. for ( const builtin of this.builtins[ shaderStage ] ) {
  37495. snippet += `${builtin};\n`;
  37496. }
  37497. return snippet;
  37498. }
  37499. /**
  37500. * Returns the vertex index builtin.
  37501. *
  37502. * @return {String} The vertex index.
  37503. */
  37504. getVertexIndex() {
  37505. return 'uint( gl_VertexID )';
  37506. }
  37507. /**
  37508. * Returns the instance index builtin.
  37509. *
  37510. * @return {String} The instance index.
  37511. */
  37512. getInstanceIndex() {
  37513. return 'uint( gl_InstanceID )';
  37514. }
  37515. /**
  37516. * Returns the invocation local index builtin.
  37517. *
  37518. * @return {String} The invocation local index.
  37519. */
  37520. getInvocationLocalIndex() {
  37521. const workgroupSize = this.object.workgroupSize;
  37522. const size = workgroupSize.reduce( ( acc, curr ) => acc * curr, 1 );
  37523. return `uint( gl_InstanceID ) % ${size}u`;
  37524. }
  37525. /**
  37526. * Returns the draw index builtin.
  37527. *
  37528. * @return {String?} The drawIndex shader string. Returns `null` if `WEBGL_multi_draw` isn't supported by the device.
  37529. */
  37530. getDrawIndex() {
  37531. const extensions = this.renderer.backend.extensions;
  37532. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  37533. return 'uint( gl_DrawID )';
  37534. }
  37535. return null;
  37536. }
  37537. /**
  37538. * Returns the front facing builtin.
  37539. *
  37540. * @return {String} The front facing builtin.
  37541. */
  37542. getFrontFacing() {
  37543. return 'gl_FrontFacing';
  37544. }
  37545. /**
  37546. * Returns the frag coord builtin.
  37547. *
  37548. * @return {String} The frag coord builtin.
  37549. */
  37550. getFragCoord() {
  37551. return 'gl_FragCoord.xy';
  37552. }
  37553. /**
  37554. * Returns the frag depth builtin.
  37555. *
  37556. * @return {String} The frag depth builtin.
  37557. */
  37558. getFragDepth() {
  37559. return 'gl_FragDepth';
  37560. }
  37561. /**
  37562. * Enables the given extension.
  37563. *
  37564. * @param {String} name - The extension name.
  37565. * @param {String} behavior - The extension behavior.
  37566. * @param {String} [shaderStage=this.shaderStage] - The shader stage.
  37567. */
  37568. enableExtension( name, behavior, shaderStage = this.shaderStage ) {
  37569. const map = this.extensions[ shaderStage ] || ( this.extensions[ shaderStage ] = new Map() );
  37570. if ( map.has( name ) === false ) {
  37571. map.set( name, {
  37572. name,
  37573. behavior
  37574. } );
  37575. }
  37576. }
  37577. /**
  37578. * Returns the enabled extensions of the given shader stage as a GLSL string.
  37579. *
  37580. * @param {String} shaderStage - The shader stage.
  37581. * @return {String} The GLSL snippet that defines the enabled extensions.
  37582. */
  37583. getExtensions( shaderStage ) {
  37584. const snippets = [];
  37585. if ( shaderStage === 'vertex' ) {
  37586. const ext = this.renderer.backend.extensions;
  37587. const isBatchedMesh = this.object.isBatchedMesh;
  37588. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  37589. this.enableExtension( 'GL_ANGLE_multi_draw', 'require', shaderStage );
  37590. }
  37591. }
  37592. const extensions = this.extensions[ shaderStage ];
  37593. if ( extensions !== undefined ) {
  37594. for ( const { name, behavior } of extensions.values() ) {
  37595. snippets.push( `#extension ${name} : ${behavior}` );
  37596. }
  37597. }
  37598. return snippets.join( '\n' );
  37599. }
  37600. /**
  37601. * Returns the clip distances builtin.
  37602. *
  37603. * @return {String} The clip distances builtin.
  37604. */
  37605. getClipDistance() {
  37606. return 'gl_ClipDistance';
  37607. }
  37608. /**
  37609. * Whether the requested feature is available or not.
  37610. *
  37611. * @param {String} name - The requested feature.
  37612. * @return {Boolean} Whether the requested feature is supported or not.
  37613. */
  37614. isAvailable( name ) {
  37615. let result = supports$1[ name ];
  37616. if ( result === undefined ) {
  37617. let extensionName;
  37618. result = false;
  37619. switch ( name ) {
  37620. case 'float32Filterable':
  37621. extensionName = 'OES_texture_float_linear';
  37622. break;
  37623. case 'clipDistance':
  37624. extensionName = 'WEBGL_clip_cull_distance';
  37625. break;
  37626. }
  37627. if ( extensionName !== undefined ) {
  37628. const extensions = this.renderer.backend.extensions;
  37629. if ( extensions.has( extensionName ) ) {
  37630. extensions.get( extensionName );
  37631. result = true;
  37632. }
  37633. }
  37634. supports$1[ name ] = result;
  37635. }
  37636. return result;
  37637. }
  37638. /**
  37639. * Whether to flip texture data along its vertical axis or not.
  37640. *
  37641. * @return {Boolean} Returns always `true` in context of GLSL.
  37642. */
  37643. isFlipY() {
  37644. return true;
  37645. }
  37646. /**
  37647. * Enables hardware clipping.
  37648. *
  37649. * @param {String} planeCount - The clipping plane count.
  37650. */
  37651. enableHardwareClipping( planeCount ) {
  37652. this.enableExtension( 'GL_ANGLE_clip_cull_distance', 'require' );
  37653. this.builtins[ 'vertex' ].push( `out float gl_ClipDistance[ ${ planeCount } ]` );
  37654. }
  37655. /**
  37656. * Registers a transform in context of Transform Feedback.
  37657. *
  37658. * @param {String} varyingName - The varying name.
  37659. * @param {AttributeNode} attributeNode - The attribute node.
  37660. */
  37661. registerTransform( varyingName, attributeNode ) {
  37662. this.transforms.push( { varyingName, attributeNode } );
  37663. }
  37664. /**
  37665. * Returns the transforms of the given shader stage as a GLSL string.
  37666. *
  37667. * @param {String} shaderStage - The shader stage.
  37668. * @return {String} The GLSL snippet that defines the transforms.
  37669. */
  37670. getTransforms( /* shaderStage */ ) {
  37671. const transforms = this.transforms;
  37672. let snippet = '';
  37673. for ( let i = 0; i < transforms.length; i ++ ) {
  37674. const transform = transforms[ i ];
  37675. const attributeName = this.getPropertyName( transform.attributeNode );
  37676. snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  37677. }
  37678. return snippet;
  37679. }
  37680. /**
  37681. * Returns a GLSL struct based on the given name and variables.
  37682. *
  37683. * @private
  37684. * @param {String} name - The struct name.
  37685. * @param {String} vars - The struct variables.
  37686. * @return {String} The GLSL snippet representing a struct.
  37687. */
  37688. _getGLSLUniformStruct( name, vars ) {
  37689. return `
  37690. layout( std140 ) uniform ${name} {
  37691. ${vars}
  37692. };`;
  37693. }
  37694. /**
  37695. * Returns a GLSL vertex shader based on the given shader data.
  37696. *
  37697. * @private
  37698. * @param {Object} shaderData - The shader data.
  37699. * @return {String} The vertex shader.
  37700. */
  37701. _getGLSLVertexCode( shaderData ) {
  37702. return `#version 300 es
  37703. ${ this.getSignature() }
  37704. // extensions
  37705. ${shaderData.extensions}
  37706. // precision
  37707. ${ defaultPrecisions }
  37708. // uniforms
  37709. ${shaderData.uniforms}
  37710. // varyings
  37711. ${shaderData.varyings}
  37712. // attributes
  37713. ${shaderData.attributes}
  37714. // codes
  37715. ${shaderData.codes}
  37716. void main() {
  37717. // vars
  37718. ${shaderData.vars}
  37719. // transforms
  37720. ${shaderData.transforms}
  37721. // flow
  37722. ${shaderData.flow}
  37723. gl_PointSize = 1.0;
  37724. }
  37725. `;
  37726. }
  37727. /**
  37728. * Returns a GLSL fragment shader based on the given shader data.
  37729. *
  37730. * @private
  37731. * @param {Object} shaderData - The shader data.
  37732. * @return {String} The vertex shader.
  37733. */
  37734. _getGLSLFragmentCode( shaderData ) {
  37735. return `#version 300 es
  37736. ${ this.getSignature() }
  37737. // precision
  37738. ${ defaultPrecisions }
  37739. // uniforms
  37740. ${shaderData.uniforms}
  37741. // varyings
  37742. ${shaderData.varyings}
  37743. // codes
  37744. ${shaderData.codes}
  37745. ${shaderData.structs}
  37746. void main() {
  37747. // vars
  37748. ${shaderData.vars}
  37749. // flow
  37750. ${shaderData.flow}
  37751. }
  37752. `;
  37753. }
  37754. /**
  37755. * Controls the code build of the shader stages.
  37756. */
  37757. buildCode() {
  37758. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  37759. this.sortBindingGroups();
  37760. for ( const shaderStage in shadersData ) {
  37761. let flow = '// code\n\n';
  37762. flow += this.flowCode[ shaderStage ];
  37763. const flowNodes = this.flowNodes[ shaderStage ];
  37764. const mainNode = flowNodes[ flowNodes.length - 1 ];
  37765. for ( const node of flowNodes ) {
  37766. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  37767. const slotName = node.name;
  37768. if ( slotName ) {
  37769. if ( flow.length > 0 ) flow += '\n';
  37770. flow += `\t// flow -> ${ slotName }\n\t`;
  37771. }
  37772. flow += `${ flowSlotData.code }\n\t`;
  37773. if ( node === mainNode && shaderStage !== 'compute' ) {
  37774. flow += '// result\n\t';
  37775. if ( shaderStage === 'vertex' ) {
  37776. flow += 'gl_Position = ';
  37777. flow += `${ flowSlotData.result };`;
  37778. } else if ( shaderStage === 'fragment' ) {
  37779. if ( ! node.outputNode.isOutputStructNode ) {
  37780. flow += 'fragColor = ';
  37781. flow += `${ flowSlotData.result };`;
  37782. }
  37783. }
  37784. }
  37785. }
  37786. const stageData = shadersData[ shaderStage ];
  37787. stageData.extensions = this.getExtensions( shaderStage );
  37788. stageData.uniforms = this.getUniforms( shaderStage );
  37789. stageData.attributes = this.getAttributes( shaderStage );
  37790. stageData.varyings = this.getVaryings( shaderStage );
  37791. stageData.vars = this.getVars( shaderStage );
  37792. stageData.structs = this.getStructs( shaderStage );
  37793. stageData.codes = this.getCodes( shaderStage );
  37794. stageData.transforms = this.getTransforms( shaderStage );
  37795. stageData.flow = flow;
  37796. }
  37797. if ( this.material !== null ) {
  37798. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  37799. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  37800. } else {
  37801. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  37802. }
  37803. }
  37804. /**
  37805. * This method is one of the more important ones since it's responsible
  37806. * for generating a matching binding instance for the given uniform node.
  37807. *
  37808. * These bindings are later used in the renderer to create bind groups
  37809. * and layouts.
  37810. *
  37811. * @param {UniformNode} node - The uniform node.
  37812. * @param {String} type - The node data type.
  37813. * @param {String} shaderStage - The shader stage.
  37814. * @param {String?} [name=null] - An optional uniform name.
  37815. * @return {NodeUniform} The node uniform object.
  37816. */
  37817. getUniformFromNode( node, type, shaderStage, name = null ) {
  37818. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  37819. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  37820. let uniformGPU = nodeData.uniformGPU;
  37821. if ( uniformGPU === undefined ) {
  37822. const group = node.groupNode;
  37823. const groupName = group.name;
  37824. const bindings = this.getBindGroupArray( groupName, shaderStage );
  37825. if ( type === 'texture' ) {
  37826. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  37827. bindings.push( uniformGPU );
  37828. } else if ( type === 'cubeTexture' ) {
  37829. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  37830. bindings.push( uniformGPU );
  37831. } else if ( type === 'texture3D' ) {
  37832. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  37833. bindings.push( uniformGPU );
  37834. } else if ( type === 'buffer' ) {
  37835. node.name = `NodeBuffer_${ node.id }`;
  37836. uniformNode.name = `buffer${ node.id }`;
  37837. const buffer = new NodeUniformBuffer( node, group );
  37838. buffer.name = node.name;
  37839. bindings.push( buffer );
  37840. uniformGPU = buffer;
  37841. } else {
  37842. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  37843. let uniformsGroup = uniformsStage[ groupName ];
  37844. if ( uniformsGroup === undefined ) {
  37845. uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
  37846. //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  37847. uniformsStage[ groupName ] = uniformsGroup;
  37848. bindings.push( uniformsGroup );
  37849. }
  37850. uniformGPU = this.getNodeUniform( uniformNode, type );
  37851. uniformsGroup.addUniform( uniformGPU );
  37852. }
  37853. nodeData.uniformGPU = uniformGPU;
  37854. }
  37855. return uniformNode;
  37856. }
  37857. }
  37858. let _vector2 = null;
  37859. let _color4 = null;
  37860. /**
  37861. * Most of the rendering related logic is implemented in the
  37862. * {@link module:Renderer} module and related management components.
  37863. * Sometimes it is required though to execute commands which are
  37864. * specific to the current 3D backend (which is WebGPU or WebGL 2).
  37865. * This abstract base class defines an interface that encapsulates
  37866. * all backend-related logic. Derived classes for each backend must
  37867. * implement the interface.
  37868. *
  37869. * @abstract
  37870. * @private
  37871. */
  37872. class Backend {
  37873. /**
  37874. * Constructs a new backend.
  37875. *
  37876. * @param {Object} parameters - An object holding parameters for the backend.
  37877. */
  37878. constructor( parameters = {} ) {
  37879. /**
  37880. * The parameters of the backend.
  37881. *
  37882. * @type {Object}
  37883. */
  37884. this.parameters = Object.assign( {}, parameters );
  37885. /**
  37886. * This weak map holds backend-specific data of objects
  37887. * like textures, attributes or render targets.
  37888. *
  37889. * @type {WeakMap}
  37890. */
  37891. this.data = new WeakMap();
  37892. /**
  37893. * A reference to the renderer.
  37894. *
  37895. * @type {Renderer?}
  37896. * @default null
  37897. */
  37898. this.renderer = null;
  37899. /**
  37900. * A reference to the canvas element the renderer is drawing to.
  37901. *
  37902. * @type {(HTMLCanvasElement|OffscreenCanvas)?}
  37903. * @default null
  37904. */
  37905. this.domElement = null;
  37906. /**
  37907. * A reference to the timestamp query pool.
  37908. *
  37909. * @type {{render: TimestampQueryPool?, compute: TimestampQueryPool?}}
  37910. */
  37911. this.timestampQueryPool = {
  37912. 'render': null,
  37913. 'compute': null
  37914. };
  37915. }
  37916. /**
  37917. * Initializes the backend so it is ready for usage. Concrete backends
  37918. * are supposed to implement their rendering context creation and related
  37919. * operations in this method.
  37920. *
  37921. * @async
  37922. * @param {Renderer} renderer - The renderer.
  37923. * @return {Promise} A Promise that resolves when the backend has been initialized.
  37924. */
  37925. async init( renderer ) {
  37926. this.renderer = renderer;
  37927. }
  37928. /**
  37929. * The coordinate system of the backend.
  37930. *
  37931. * @abstract
  37932. * @type {Number}
  37933. * @readonly
  37934. */
  37935. get coordinateSystem() {}
  37936. // render context
  37937. /**
  37938. * This method is executed at the beginning of a render call and
  37939. * can be used by the backend to prepare the state for upcoming
  37940. * draw calls.
  37941. *
  37942. * @abstract
  37943. * @param {RenderContext} renderContext - The render context.
  37944. */
  37945. beginRender( /*renderContext*/ ) {}
  37946. /**
  37947. * This method is executed at the end of a render call and
  37948. * can be used by the backend to finalize work after draw
  37949. * calls.
  37950. *
  37951. * @abstract
  37952. * @param {RenderContext} renderContext - The render context.
  37953. */
  37954. finishRender( /*renderContext*/ ) {}
  37955. /**
  37956. * This method is executed at the beginning of a compute call and
  37957. * can be used by the backend to prepare the state for upcoming
  37958. * compute tasks.
  37959. *
  37960. * @abstract
  37961. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  37962. */
  37963. beginCompute( /*computeGroup*/ ) {}
  37964. /**
  37965. * This method is executed at the end of a compute call and
  37966. * can be used by the backend to finalize work after compute
  37967. * tasks.
  37968. *
  37969. * @abstract
  37970. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  37971. */
  37972. finishCompute( /*computeGroup*/ ) {}
  37973. // render object
  37974. /**
  37975. * Executes a draw command for the given render object.
  37976. *
  37977. * @abstract
  37978. * @param {RenderObject} renderObject - The render object to draw.
  37979. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  37980. */
  37981. draw( /*renderObject, info*/ ) { }
  37982. // compute node
  37983. /**
  37984. * Executes a compute command for the given compute node.
  37985. *
  37986. * @abstract
  37987. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  37988. * @param {Node} computeNode - The compute node.
  37989. * @param {Array<BindGroup>} bindings - The bindings.
  37990. * @param {ComputePipeline} computePipeline - The compute pipeline.
  37991. */
  37992. compute( /*computeGroup, computeNode, computeBindings, computePipeline*/ ) { }
  37993. // program
  37994. /**
  37995. * Creates a shader program from the given programmable stage.
  37996. *
  37997. * @abstract
  37998. * @param {ProgrammableStage} program - The programmable stage.
  37999. */
  38000. createProgram( /*program*/ ) { }
  38001. /**
  38002. * Destroys the shader program of the given programmable stage.
  38003. *
  38004. * @abstract
  38005. * @param {ProgrammableStage} program - The programmable stage.
  38006. */
  38007. destroyProgram( /*program*/ ) { }
  38008. // bindings
  38009. /**
  38010. * Creates bindings from the given bind group definition.
  38011. *
  38012. * @abstract
  38013. * @param {BindGroup} bindGroup - The bind group.
  38014. * @param {Array<BindGroup>} bindings - Array of bind groups.
  38015. * @param {Number} cacheIndex - The cache index.
  38016. * @param {Number} version - The version.
  38017. */
  38018. createBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  38019. /**
  38020. * Updates the given bind group definition.
  38021. *
  38022. * @abstract
  38023. * @param {BindGroup} bindGroup - The bind group.
  38024. * @param {Array<BindGroup>} bindings - Array of bind groups.
  38025. * @param {Number} cacheIndex - The cache index.
  38026. * @param {Number} version - The version.
  38027. */
  38028. updateBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  38029. /**
  38030. * Updates a buffer binding.
  38031. *
  38032. * @abstract
  38033. * @param {Buffer} binding - The buffer binding to update.
  38034. */
  38035. updateBinding( /*binding*/ ) { }
  38036. // pipeline
  38037. /**
  38038. * Creates a render pipeline for the given render object.
  38039. *
  38040. * @abstract
  38041. * @param {RenderObject} renderObject - The render object.
  38042. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  38043. */
  38044. createRenderPipeline( /*renderObject, promises*/ ) { }
  38045. /**
  38046. * Creates a compute pipeline for the given compute node.
  38047. *
  38048. * @abstract
  38049. * @param {ComputePipeline} computePipeline - The compute pipeline.
  38050. * @param {Array<BindGroup>} bindings - The bindings.
  38051. */
  38052. createComputePipeline( /*computePipeline, bindings*/ ) { }
  38053. // cache key
  38054. /**
  38055. * Returns `true` if the render pipeline requires an update.
  38056. *
  38057. * @abstract
  38058. * @param {RenderObject} renderObject - The render object.
  38059. * @return {Boolean} Whether the render pipeline requires an update or not.
  38060. */
  38061. needsRenderUpdate( /*renderObject*/ ) { }
  38062. /**
  38063. * Returns a cache key that is used to identify render pipelines.
  38064. *
  38065. * @abstract
  38066. * @param {RenderObject} renderObject - The render object.
  38067. * @return {String} The cache key.
  38068. */
  38069. getRenderCacheKey( /*renderObject*/ ) { }
  38070. // node builder
  38071. /**
  38072. * Returns a node builder for the given render object.
  38073. *
  38074. * @abstract
  38075. * @param {RenderObject} renderObject - The render object.
  38076. * @param {Renderer} renderer - The renderer.
  38077. * @return {NodeBuilder} The node builder.
  38078. */
  38079. createNodeBuilder( /*renderObject, renderer*/ ) { }
  38080. // textures
  38081. /**
  38082. * Creates a GPU sampler for the given texture.
  38083. *
  38084. * @abstract
  38085. * @param {Texture} texture - The texture to create the sampler for.
  38086. */
  38087. createSampler( /*texture*/ ) { }
  38088. /**
  38089. * Destroys the GPU sampler for the given texture.
  38090. *
  38091. * @abstract
  38092. * @param {Texture} texture - The texture to destroy the sampler for.
  38093. */
  38094. destroySampler( /*texture*/ ) {}
  38095. /**
  38096. * Creates a default texture for the given texture that can be used
  38097. * as a placeholder until the actual texture is ready for usage.
  38098. *
  38099. * @abstract
  38100. * @param {Texture} texture - The texture to create a default texture for.
  38101. */
  38102. createDefaultTexture( /*texture*/ ) { }
  38103. /**
  38104. * Defines a texture on the GPU for the given texture object.
  38105. *
  38106. * @abstract
  38107. * @param {Texture} texture - The texture.
  38108. * @param {Object} [options={}] - Optional configuration parameter.
  38109. */
  38110. createTexture( /*texture, options={}*/ ) { }
  38111. /**
  38112. * Uploads the updated texture data to the GPU.
  38113. *
  38114. * @abstract
  38115. * @param {Texture} texture - The texture.
  38116. * @param {Object} [options={}] - Optional configuration parameter.
  38117. */
  38118. updateTexture( /*texture, options = {}*/ ) { }
  38119. /**
  38120. * Generates mipmaps for the given texture.
  38121. *
  38122. * @abstract
  38123. * @param {Texture} texture - The texture.
  38124. */
  38125. generateMipmaps( /*texture*/ ) { }
  38126. /**
  38127. * Destroys the GPU data for the given texture object.
  38128. *
  38129. * @abstract
  38130. * @param {Texture} texture - The texture.
  38131. */
  38132. destroyTexture( /*texture*/ ) { }
  38133. /**
  38134. * Returns texture data as a typed array.
  38135. *
  38136. * @abstract
  38137. * @async
  38138. * @param {Texture} texture - The texture to copy.
  38139. * @param {Number} x - The x coordinate of the copy origin.
  38140. * @param {Number} y - The y coordinate of the copy origin.
  38141. * @param {Number} width - The width of the copy.
  38142. * @param {Number} height - The height of the copy.
  38143. * @param {Number} faceIndex - The face index.
  38144. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  38145. */
  38146. async copyTextureToBuffer( /*texture, x, y, width, height, faceIndex*/ ) {}
  38147. /**
  38148. * Copies data of the given source texture to the given destination texture.
  38149. *
  38150. * @abstract
  38151. * @param {Texture} srcTexture - The source texture.
  38152. * @param {Texture} dstTexture - The destination texture.
  38153. * @param {Vector4?} [srcRegion=null] - The region of the source texture to copy.
  38154. * @param {(Vector2|Vector3)?} [dstPosition=null] - The destination position of the copy.
  38155. * @param {Number} [level=0] - The mip level to copy.
  38156. */
  38157. copyTextureToTexture( /*srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0*/ ) {}
  38158. /**
  38159. * Copies the current bound framebuffer to the given texture.
  38160. *
  38161. * @abstract
  38162. * @param {Texture} texture - The destination texture.
  38163. * @param {RenderContext} renderContext - The render context.
  38164. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  38165. */
  38166. copyFramebufferToTexture( /*texture, renderContext, rectangle*/ ) {}
  38167. // attributes
  38168. /**
  38169. * Creates the GPU buffer of a shader attribute.
  38170. *
  38171. * @abstract
  38172. * @param {BufferAttribute} attribute - The buffer attribute.
  38173. */
  38174. createAttribute( /*attribute*/ ) { }
  38175. /**
  38176. * Creates the GPU buffer of an indexed shader attribute.
  38177. *
  38178. * @abstract
  38179. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  38180. */
  38181. createIndexAttribute( /*attribute*/ ) { }
  38182. /**
  38183. * Creates the GPU buffer of a storage attribute.
  38184. *
  38185. * @abstract
  38186. * @param {BufferAttribute} attribute - The buffer attribute.
  38187. */
  38188. createStorageAttribute( /*attribute*/ ) { }
  38189. /**
  38190. * Updates the GPU buffer of a shader attribute.
  38191. *
  38192. * @abstract
  38193. * @param {BufferAttribute} attribute - The buffer attribute to update.
  38194. */
  38195. updateAttribute( /*attribute*/ ) { }
  38196. /**
  38197. * Destroys the GPU buffer of a shader attribute.
  38198. *
  38199. * @abstract
  38200. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  38201. */
  38202. destroyAttribute( /*attribute*/ ) { }
  38203. // canvas
  38204. /**
  38205. * Returns the backend's rendering context.
  38206. *
  38207. * @abstract
  38208. * @return {Object} The rendering context.
  38209. */
  38210. getContext() { }
  38211. /**
  38212. * Backends can use this method if they have to run
  38213. * logic when the renderer gets resized.
  38214. *
  38215. * @abstract
  38216. */
  38217. updateSize() { }
  38218. /**
  38219. * Updates the viewport with the values from the given render context.
  38220. *
  38221. * @abstract
  38222. * @param {RenderContext} renderContext - The render context.
  38223. */
  38224. updateViewport( /*renderContext*/ ) {}
  38225. // utils
  38226. /**
  38227. * Returns `true` if the given 3D object is fully occluded by other
  38228. * 3D objects in the scene. Backends must implement this method by using
  38229. * a Occlusion Query API.
  38230. *
  38231. * @abstract
  38232. * @param {RenderContext} renderContext - The render context.
  38233. * @param {Object3D} object - The 3D object to test.
  38234. * @return {Boolean} Whether the 3D object is fully occluded or not.
  38235. */
  38236. isOccluded( /*renderContext, object*/ ) {}
  38237. /**
  38238. * Resolves the time stamp for the given render context and type.
  38239. *
  38240. * @async
  38241. * @abstract
  38242. * @param {String} [type='render'] - The type of the time stamp.
  38243. * @return {Promise<Number>} A Promise that resolves with the time stamp.
  38244. */
  38245. async resolveTimestampsAsync( type = 'render' ) {
  38246. if ( ! this.trackTimestamp ) {
  38247. warnOnce( 'WebGPURenderer: Timestamp tracking is disabled.' );
  38248. return;
  38249. }
  38250. const queryPool = this.timestampQueryPool[ type ];
  38251. if ( ! queryPool ) {
  38252. warnOnce( `WebGPURenderer: No timestamp query pool for type '${type}' found.` );
  38253. return;
  38254. }
  38255. const duration = await queryPool.resolveQueriesAsync();
  38256. this.renderer.info[ type ].timestamp = duration;
  38257. return duration;
  38258. }
  38259. /**
  38260. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  38261. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  38262. *
  38263. * @async
  38264. * @abstract
  38265. * @return {Promise} A Promise that resolves when synchronization has been finished.
  38266. */
  38267. async waitForGPU() {}
  38268. /**
  38269. * This method performs a readback operation by moving buffer data from
  38270. * a storage buffer attribute from the GPU to the CPU.
  38271. *
  38272. * @async
  38273. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  38274. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  38275. */
  38276. async getArrayBufferAsync( /* attribute */ ) {}
  38277. /**
  38278. * Checks if the given feature is supported by the backend.
  38279. *
  38280. * @async
  38281. * @abstract
  38282. * @param {String} name - The feature's name.
  38283. * @return {Promise<Boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  38284. */
  38285. async hasFeatureAsync( /*name*/ ) { }
  38286. /**
  38287. * Checks if the given feature is supported by the backend.
  38288. *
  38289. * @abstract
  38290. * @param {String} name - The feature's name.
  38291. * @return {Boolean} Whether the feature is supported or not.
  38292. */
  38293. hasFeature( /*name*/ ) {}
  38294. /**
  38295. * Returns the maximum anisotropy texture filtering value.
  38296. *
  38297. * @abstract
  38298. * @return {Number} The maximum anisotropy texture filtering value.
  38299. */
  38300. getMaxAnisotropy() {}
  38301. /**
  38302. * Returns the drawing buffer size.
  38303. *
  38304. * @return {Vector2} The drawing buffer size.
  38305. */
  38306. getDrawingBufferSize() {
  38307. _vector2 = _vector2 || new Vector2();
  38308. return this.renderer.getDrawingBufferSize( _vector2 );
  38309. }
  38310. /**
  38311. * Defines the scissor test.
  38312. *
  38313. * @abstract
  38314. * @param {Boolean} boolean - Whether the scissor test should be enabled or not.
  38315. */
  38316. setScissorTest( /*boolean*/ ) { }
  38317. /**
  38318. * Returns the clear color and alpha into a single
  38319. * color object.
  38320. *
  38321. * @return {Color4} The clear color.
  38322. */
  38323. getClearColor() {
  38324. const renderer = this.renderer;
  38325. _color4 = _color4 || new Color4();
  38326. renderer.getClearColor( _color4 );
  38327. _color4.getRGB( _color4, this.renderer.currentColorSpace );
  38328. return _color4;
  38329. }
  38330. /**
  38331. * Returns the DOM element. If no DOM element exists, the backend
  38332. * creates a new one.
  38333. *
  38334. * @return {HTMLCanvasElement} The DOM element.
  38335. */
  38336. getDomElement() {
  38337. let domElement = this.domElement;
  38338. if ( domElement === null ) {
  38339. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  38340. // OffscreenCanvas does not have setAttribute, see #22811
  38341. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  38342. this.domElement = domElement;
  38343. }
  38344. return domElement;
  38345. }
  38346. /**
  38347. * Sets a dictionary for the given object into the
  38348. * internal data structure.
  38349. *
  38350. * @param {Object} object - The object.
  38351. * @param {Object} value - The dictionary to set.
  38352. */
  38353. set( object, value ) {
  38354. this.data.set( object, value );
  38355. }
  38356. /**
  38357. * Returns the dictionary for the given object.
  38358. *
  38359. * @param {Object} object - The object.
  38360. * @return {Object} The object's dictionary.
  38361. */
  38362. get( object ) {
  38363. let map = this.data.get( object );
  38364. if ( map === undefined ) {
  38365. map = {};
  38366. this.data.set( object, map );
  38367. }
  38368. return map;
  38369. }
  38370. /**
  38371. * Checks if the given object has a dictionary
  38372. * with data defined.
  38373. *
  38374. * @param {Object} object - The object.
  38375. * @return {Boolean} Whether a dictionary for the given object as been defined or not.
  38376. */
  38377. has( object ) {
  38378. return this.data.has( object );
  38379. }
  38380. /**
  38381. * Deletes an object from the internal data structure.
  38382. *
  38383. * @param {Object} object - The object to delete.
  38384. */
  38385. delete( object ) {
  38386. this.data.delete( object );
  38387. }
  38388. /**
  38389. * Frees internal resources.
  38390. *
  38391. * @abstract
  38392. */
  38393. dispose() { }
  38394. }
  38395. let _id$1 = 0;
  38396. /**
  38397. * This module is internally used in context of compute shaders.
  38398. * This type of shader is not natively supported in WebGL 2 and
  38399. * thus implemented via Transform Feedback. `DualAttributeData`
  38400. * manages the related data.
  38401. *
  38402. * @private
  38403. */
  38404. class DualAttributeData {
  38405. constructor( attributeData, dualBuffer ) {
  38406. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  38407. this.type = attributeData.type;
  38408. this.bufferType = attributeData.bufferType;
  38409. this.pbo = attributeData.pbo;
  38410. this.byteLength = attributeData.byteLength;
  38411. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  38412. this.version = attributeData.version;
  38413. this.isInteger = attributeData.isInteger;
  38414. this.activeBufferIndex = 0;
  38415. this.baseId = attributeData.id;
  38416. }
  38417. get id() {
  38418. return `${ this.baseId }|${ this.activeBufferIndex }`;
  38419. }
  38420. get bufferGPU() {
  38421. return this.buffers[ this.activeBufferIndex ];
  38422. }
  38423. get transformBuffer() {
  38424. return this.buffers[ this.activeBufferIndex ^ 1 ];
  38425. }
  38426. switchBuffers() {
  38427. this.activeBufferIndex ^= 1;
  38428. }
  38429. }
  38430. /**
  38431. * A WebGL 2 backend utility module for managing shader attributes.
  38432. *
  38433. * @private
  38434. */
  38435. class WebGLAttributeUtils {
  38436. /**
  38437. * Constructs a new utility object.
  38438. *
  38439. * @param {WebGLBackend} backend - The WebGL 2 backend.
  38440. */
  38441. constructor( backend ) {
  38442. /**
  38443. * A reference to the WebGL 2 backend.
  38444. *
  38445. * @type {WebGLBackend}
  38446. */
  38447. this.backend = backend;
  38448. }
  38449. /**
  38450. * Creates the GPU buffer for the given buffer attribute.
  38451. *
  38452. * @param {BufferAttribute} attribute - The buffer attribute.
  38453. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  38454. */
  38455. createAttribute( attribute, bufferType ) {
  38456. const backend = this.backend;
  38457. const { gl } = backend;
  38458. const array = attribute.array;
  38459. const usage = attribute.usage || gl.STATIC_DRAW;
  38460. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  38461. const bufferData = backend.get( bufferAttribute );
  38462. let bufferGPU = bufferData.bufferGPU;
  38463. if ( bufferGPU === undefined ) {
  38464. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  38465. bufferData.bufferGPU = bufferGPU;
  38466. bufferData.bufferType = bufferType;
  38467. bufferData.version = bufferAttribute.version;
  38468. }
  38469. //attribute.onUploadCallback();
  38470. let type;
  38471. if ( array instanceof Float32Array ) {
  38472. type = gl.FLOAT;
  38473. } else if ( array instanceof Uint16Array ) {
  38474. if ( attribute.isFloat16BufferAttribute ) {
  38475. type = gl.HALF_FLOAT;
  38476. } else {
  38477. type = gl.UNSIGNED_SHORT;
  38478. }
  38479. } else if ( array instanceof Int16Array ) {
  38480. type = gl.SHORT;
  38481. } else if ( array instanceof Uint32Array ) {
  38482. type = gl.UNSIGNED_INT;
  38483. } else if ( array instanceof Int32Array ) {
  38484. type = gl.INT;
  38485. } else if ( array instanceof Int8Array ) {
  38486. type = gl.BYTE;
  38487. } else if ( array instanceof Uint8Array ) {
  38488. type = gl.UNSIGNED_BYTE;
  38489. } else if ( array instanceof Uint8ClampedArray ) {
  38490. type = gl.UNSIGNED_BYTE;
  38491. } else {
  38492. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  38493. }
  38494. let attributeData = {
  38495. bufferGPU,
  38496. bufferType,
  38497. type,
  38498. byteLength: array.byteLength,
  38499. bytesPerElement: array.BYTES_PER_ELEMENT,
  38500. version: attribute.version,
  38501. pbo: attribute.pbo,
  38502. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType,
  38503. id: _id$1 ++
  38504. };
  38505. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  38506. // create buffer for transform feedback use
  38507. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  38508. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  38509. }
  38510. backend.set( attribute, attributeData );
  38511. }
  38512. /**
  38513. * Updates the GPU buffer of the given buffer attribute.
  38514. *
  38515. * @param {BufferAttribute} attribute - The buffer attribute.
  38516. */
  38517. updateAttribute( attribute ) {
  38518. const backend = this.backend;
  38519. const { gl } = backend;
  38520. const array = attribute.array;
  38521. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  38522. const bufferData = backend.get( bufferAttribute );
  38523. const bufferType = bufferData.bufferType;
  38524. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  38525. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  38526. if ( updateRanges.length === 0 ) {
  38527. // Not using update ranges
  38528. gl.bufferSubData( bufferType, 0, array );
  38529. } else {
  38530. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  38531. const range = updateRanges[ i ];
  38532. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  38533. array, range.start, range.count );
  38534. }
  38535. bufferAttribute.clearUpdateRanges();
  38536. }
  38537. gl.bindBuffer( bufferType, null );
  38538. bufferData.version = bufferAttribute.version;
  38539. }
  38540. /**
  38541. * Destroys the GPU buffer of the given buffer attribute.
  38542. *
  38543. * @param {BufferAttribute} attribute - The buffer attribute.
  38544. */
  38545. destroyAttribute( attribute ) {
  38546. const backend = this.backend;
  38547. const { gl } = backend;
  38548. if ( attribute.isInterleavedBufferAttribute ) {
  38549. backend.delete( attribute.data );
  38550. }
  38551. const attributeData = backend.get( attribute );
  38552. gl.deleteBuffer( attributeData.bufferGPU );
  38553. backend.delete( attribute );
  38554. }
  38555. /**
  38556. * This method performs a readback operation by moving buffer data from
  38557. * a storage buffer attribute from the GPU to the CPU.
  38558. *
  38559. * @async
  38560. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  38561. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  38562. */
  38563. async getArrayBufferAsync( attribute ) {
  38564. const backend = this.backend;
  38565. const { gl } = backend;
  38566. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  38567. const { bufferGPU } = backend.get( bufferAttribute );
  38568. const array = attribute.array;
  38569. const byteLength = array.byteLength;
  38570. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  38571. const writeBuffer = gl.createBuffer();
  38572. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  38573. gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ );
  38574. gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength );
  38575. await backend.utils._clientWaitAsync();
  38576. const dstBuffer = new attribute.array.constructor( array.length );
  38577. // Ensure the buffer is bound before reading
  38578. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  38579. gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer );
  38580. gl.deleteBuffer( writeBuffer );
  38581. gl.bindBuffer( gl.COPY_READ_BUFFER, null );
  38582. gl.bindBuffer( gl.COPY_WRITE_BUFFER, null );
  38583. return dstBuffer.buffer;
  38584. }
  38585. /**
  38586. * Creates a WebGL buffer with the given data.
  38587. *
  38588. * @private
  38589. * @param {WebGL2RenderingContext} gl - The rendering context.
  38590. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  38591. * @param {TypedArray} array - The array of the buffer attribute.
  38592. * @param {GLenum} usage - The usage.
  38593. * @return {WebGLBuffer} The WebGL buffer.
  38594. */
  38595. _createBuffer( gl, bufferType, array, usage ) {
  38596. const bufferGPU = gl.createBuffer();
  38597. gl.bindBuffer( bufferType, bufferGPU );
  38598. gl.bufferData( bufferType, array, usage );
  38599. gl.bindBuffer( bufferType, null );
  38600. return bufferGPU;
  38601. }
  38602. }
  38603. let equationToGL, factorToGL;
  38604. /**
  38605. * A WebGL 2 backend utility module for managing the WebGL state.
  38606. *
  38607. * The major goal of this module is to reduce the number of state changes
  38608. * by caching the WEbGL state with a series of variables. In this way, the
  38609. * renderer only executes state change commands when necessary which
  38610. * improves the overall performance.
  38611. *
  38612. * @private
  38613. */
  38614. class WebGLState {
  38615. /**
  38616. * Constructs a new utility object.
  38617. *
  38618. * @param {WebGLBackend} backend - The WebGL 2 backend.
  38619. */
  38620. constructor( backend ) {
  38621. /**
  38622. * A reference to the WebGL 2 backend.
  38623. *
  38624. * @type {WebGLBackend}
  38625. */
  38626. this.backend = backend;
  38627. /**
  38628. * A reference to the rendering context.
  38629. *
  38630. * @type {WebGL2RenderingContext}
  38631. */
  38632. this.gl = this.backend.gl;
  38633. // Below properties are intended to cache
  38634. // the WebGL state and are not explicitly
  38635. // documented for convenience reasons.
  38636. this.enabled = {};
  38637. this.currentFlipSided = null;
  38638. this.currentCullFace = null;
  38639. this.currentProgram = null;
  38640. this.currentBlendingEnabled = false;
  38641. this.currentBlending = null;
  38642. this.currentBlendSrc = null;
  38643. this.currentBlendDst = null;
  38644. this.currentBlendSrcAlpha = null;
  38645. this.currentBlendDstAlpha = null;
  38646. this.currentPremultipledAlpha = null;
  38647. this.currentPolygonOffsetFactor = null;
  38648. this.currentPolygonOffsetUnits = null;
  38649. this.currentColorMask = null;
  38650. this.currentDepthFunc = null;
  38651. this.currentDepthMask = null;
  38652. this.currentStencilFunc = null;
  38653. this.currentStencilRef = null;
  38654. this.currentStencilFuncMask = null;
  38655. this.currentStencilFail = null;
  38656. this.currentStencilZFail = null;
  38657. this.currentStencilZPass = null;
  38658. this.currentStencilMask = null;
  38659. this.currentLineWidth = null;
  38660. this.currentClippingPlanes = 0;
  38661. this.currentBoundFramebuffers = {};
  38662. this.currentDrawbuffers = new WeakMap();
  38663. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  38664. this.currentTextureSlot = null;
  38665. this.currentBoundTextures = {};
  38666. this.currentBoundBufferBases = {};
  38667. this._init();
  38668. }
  38669. /**
  38670. * Inits the state of the utility.
  38671. *
  38672. * @private
  38673. */
  38674. _init() {
  38675. const gl = this.gl;
  38676. // Store only WebGL constants here.
  38677. equationToGL = {
  38678. [ AddEquation ]: gl.FUNC_ADD,
  38679. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  38680. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  38681. };
  38682. factorToGL = {
  38683. [ ZeroFactor ]: gl.ZERO,
  38684. [ OneFactor ]: gl.ONE,
  38685. [ SrcColorFactor ]: gl.SRC_COLOR,
  38686. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  38687. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  38688. [ DstColorFactor ]: gl.DST_COLOR,
  38689. [ DstAlphaFactor ]: gl.DST_ALPHA,
  38690. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  38691. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  38692. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  38693. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  38694. };
  38695. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  38696. const viewportParam = gl.getParameter( gl.VIEWPORT );
  38697. this.currentScissor = new Vector4().fromArray( scissorParam );
  38698. this.currentViewport = new Vector4().fromArray( viewportParam );
  38699. this._tempVec4 = new Vector4();
  38700. }
  38701. /**
  38702. * Enables the given WebGL capability.
  38703. *
  38704. * This method caches the capability state so
  38705. * `gl.enable()` is only called when necessary.
  38706. *
  38707. * @param {GLenum} id - The capability to enable.
  38708. */
  38709. enable( id ) {
  38710. const { enabled } = this;
  38711. if ( enabled[ id ] !== true ) {
  38712. this.gl.enable( id );
  38713. enabled[ id ] = true;
  38714. }
  38715. }
  38716. /**
  38717. * Disables the given WebGL capability.
  38718. *
  38719. * This method caches the capability state so
  38720. * `gl.disable()` is only called when necessary.
  38721. *
  38722. * @param {GLenum} id - The capability to enable.
  38723. */
  38724. disable( id ) {
  38725. const { enabled } = this;
  38726. if ( enabled[ id ] !== false ) {
  38727. this.gl.disable( id );
  38728. enabled[ id ] = false;
  38729. }
  38730. }
  38731. /**
  38732. * Specifies whether polygons are front- or back-facing
  38733. * by setting the winding orientation.
  38734. *
  38735. * This method caches the state so `gl.frontFace()` is only
  38736. * called when necessary.
  38737. *
  38738. * @param {Boolean} flipSided - Whether triangles flipped their sides or not.
  38739. */
  38740. setFlipSided( flipSided ) {
  38741. if ( this.currentFlipSided !== flipSided ) {
  38742. const { gl } = this;
  38743. if ( flipSided ) {
  38744. gl.frontFace( gl.CW );
  38745. } else {
  38746. gl.frontFace( gl.CCW );
  38747. }
  38748. this.currentFlipSided = flipSided;
  38749. }
  38750. }
  38751. /**
  38752. * Specifies whether or not front- and/or back-facing
  38753. * polygons can be culled.
  38754. *
  38755. * This method caches the state so `gl.cullFace()` is only
  38756. * called when necessary.
  38757. *
  38758. * @param {Number} cullFace - Defines which polygons are candidates for culling.
  38759. */
  38760. setCullFace( cullFace ) {
  38761. const { gl } = this;
  38762. if ( cullFace !== CullFaceNone ) {
  38763. this.enable( gl.CULL_FACE );
  38764. if ( cullFace !== this.currentCullFace ) {
  38765. if ( cullFace === CullFaceBack ) {
  38766. gl.cullFace( gl.BACK );
  38767. } else if ( cullFace === CullFaceFront ) {
  38768. gl.cullFace( gl.FRONT );
  38769. } else {
  38770. gl.cullFace( gl.FRONT_AND_BACK );
  38771. }
  38772. }
  38773. } else {
  38774. this.disable( gl.CULL_FACE );
  38775. }
  38776. this.currentCullFace = cullFace;
  38777. }
  38778. /**
  38779. * Specifies the width of line primitives.
  38780. *
  38781. * This method caches the state so `gl.lineWidth()` is only
  38782. * called when necessary.
  38783. *
  38784. * @param {Number} width - The line width.
  38785. */
  38786. setLineWidth( width ) {
  38787. const { currentLineWidth, gl } = this;
  38788. if ( width !== currentLineWidth ) {
  38789. gl.lineWidth( width );
  38790. this.currentLineWidth = width;
  38791. }
  38792. }
  38793. /**
  38794. * Defines the blending.
  38795. *
  38796. * This method caches the state so `gl.blendEquation()`, `gl.blendEquationSeparate()`,
  38797. * `gl.blendFunc()` and `gl.blendFuncSeparate()` are only called when necessary.
  38798. *
  38799. * @param {Number} blending - The blending type.
  38800. * @param {Number} blendEquation - The blending equation.
  38801. * @param {Number} blendSrc - Only relevant for custom blending. The RGB source blending factor.
  38802. * @param {Number} blendDst - Only relevant for custom blending. The RGB destination blending factor.
  38803. * @param {Number} blendEquationAlpha - Only relevant for custom blending. The blending equation for alpha.
  38804. * @param {Number} blendSrcAlpha - Only relevant for custom blending. The alpha source blending factor.
  38805. * @param {Number} blendDstAlpha - Only relevant for custom blending. The alpha destination blending factor.
  38806. * @param {Boolean} premultipliedAlpha - Whether premultiplied alpha is enabled or not.
  38807. */
  38808. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  38809. const { gl } = this;
  38810. if ( blending === NoBlending ) {
  38811. if ( this.currentBlendingEnabled === true ) {
  38812. this.disable( gl.BLEND );
  38813. this.currentBlendingEnabled = false;
  38814. }
  38815. return;
  38816. }
  38817. if ( this.currentBlendingEnabled === false ) {
  38818. this.enable( gl.BLEND );
  38819. this.currentBlendingEnabled = true;
  38820. }
  38821. if ( blending !== CustomBlending ) {
  38822. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  38823. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  38824. gl.blendEquation( gl.FUNC_ADD );
  38825. this.currentBlendEquation = AddEquation;
  38826. this.currentBlendEquationAlpha = AddEquation;
  38827. }
  38828. if ( premultipliedAlpha ) {
  38829. switch ( blending ) {
  38830. case NormalBlending:
  38831. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  38832. break;
  38833. case AdditiveBlending:
  38834. gl.blendFunc( gl.ONE, gl.ONE );
  38835. break;
  38836. case SubtractiveBlending:
  38837. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  38838. break;
  38839. case MultiplyBlending:
  38840. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  38841. break;
  38842. default:
  38843. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  38844. break;
  38845. }
  38846. } else {
  38847. switch ( blending ) {
  38848. case NormalBlending:
  38849. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  38850. break;
  38851. case AdditiveBlending:
  38852. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  38853. break;
  38854. case SubtractiveBlending:
  38855. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  38856. break;
  38857. case MultiplyBlending:
  38858. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  38859. break;
  38860. default:
  38861. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  38862. break;
  38863. }
  38864. }
  38865. this.currentBlendSrc = null;
  38866. this.currentBlendDst = null;
  38867. this.currentBlendSrcAlpha = null;
  38868. this.currentBlendDstAlpha = null;
  38869. this.currentBlending = blending;
  38870. this.currentPremultipledAlpha = premultipliedAlpha;
  38871. }
  38872. return;
  38873. }
  38874. // custom blending
  38875. blendEquationAlpha = blendEquationAlpha || blendEquation;
  38876. blendSrcAlpha = blendSrcAlpha || blendSrc;
  38877. blendDstAlpha = blendDstAlpha || blendDst;
  38878. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  38879. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  38880. this.currentBlendEquation = blendEquation;
  38881. this.currentBlendEquationAlpha = blendEquationAlpha;
  38882. }
  38883. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  38884. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  38885. this.currentBlendSrc = blendSrc;
  38886. this.currentBlendDst = blendDst;
  38887. this.currentBlendSrcAlpha = blendSrcAlpha;
  38888. this.currentBlendDstAlpha = blendDstAlpha;
  38889. }
  38890. this.currentBlending = blending;
  38891. this.currentPremultipledAlpha = false;
  38892. }
  38893. /**
  38894. * Specifies whether colors can be written when rendering
  38895. * into a framebuffer or not.
  38896. *
  38897. * This method caches the state so `gl.colorMask()` is only
  38898. * called when necessary.
  38899. *
  38900. * @param {Boolean} colorMask - The color mask.
  38901. */
  38902. setColorMask( colorMask ) {
  38903. if ( this.currentColorMask !== colorMask ) {
  38904. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  38905. this.currentColorMask = colorMask;
  38906. }
  38907. }
  38908. /**
  38909. * Specifies whether the depth test is enabled or not.
  38910. *
  38911. * @param {Boolean} depthTest - Whether the depth test is enabled or not.
  38912. */
  38913. setDepthTest( depthTest ) {
  38914. const { gl } = this;
  38915. if ( depthTest ) {
  38916. this.enable( gl.DEPTH_TEST );
  38917. } else {
  38918. this.disable( gl.DEPTH_TEST );
  38919. }
  38920. }
  38921. /**
  38922. * Specifies whether depth values can be written when rendering
  38923. * into a framebuffer or not.
  38924. *
  38925. * This method caches the state so `gl.depthMask()` is only
  38926. * called when necessary.
  38927. *
  38928. * @param {Boolean} depthMask - The depth mask.
  38929. */
  38930. setDepthMask( depthMask ) {
  38931. if ( this.currentDepthMask !== depthMask ) {
  38932. this.gl.depthMask( depthMask );
  38933. this.currentDepthMask = depthMask;
  38934. }
  38935. }
  38936. /**
  38937. * Specifies the depth compare function.
  38938. *
  38939. * This method caches the state so `gl.depthFunc()` is only
  38940. * called when necessary.
  38941. *
  38942. * @param {Number} depthFunc - The depth compare function.
  38943. */
  38944. setDepthFunc( depthFunc ) {
  38945. if ( this.currentDepthFunc !== depthFunc ) {
  38946. const { gl } = this;
  38947. switch ( depthFunc ) {
  38948. case NeverDepth:
  38949. gl.depthFunc( gl.NEVER );
  38950. break;
  38951. case AlwaysDepth:
  38952. gl.depthFunc( gl.ALWAYS );
  38953. break;
  38954. case LessDepth:
  38955. gl.depthFunc( gl.LESS );
  38956. break;
  38957. case LessEqualDepth:
  38958. gl.depthFunc( gl.LEQUAL );
  38959. break;
  38960. case EqualDepth:
  38961. gl.depthFunc( gl.EQUAL );
  38962. break;
  38963. case GreaterEqualDepth:
  38964. gl.depthFunc( gl.GEQUAL );
  38965. break;
  38966. case GreaterDepth:
  38967. gl.depthFunc( gl.GREATER );
  38968. break;
  38969. case NotEqualDepth:
  38970. gl.depthFunc( gl.NOTEQUAL );
  38971. break;
  38972. default:
  38973. gl.depthFunc( gl.LEQUAL );
  38974. }
  38975. this.currentDepthFunc = depthFunc;
  38976. }
  38977. }
  38978. /**
  38979. * Specifies the viewport.
  38980. *
  38981. * @param {Number} x - The x-coordinate of the lower left corner of the viewport.
  38982. * @param {Number} y - The y-coordinate of the lower left corner of the viewport.
  38983. * @param {Number} width - The width of the viewport.
  38984. * @param {Number} height - The height of the viewport.
  38985. *
  38986. */
  38987. scissor( x, y, width, height ) {
  38988. const scissor = this._tempVec4.set( x, y, width, height );
  38989. if ( this.currentScissor.equals( scissor ) === false ) {
  38990. const { gl } = this;
  38991. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  38992. this.currentScissor.copy( scissor );
  38993. }
  38994. }
  38995. /**
  38996. * Specifies the viewport.
  38997. *
  38998. * @param {Number} x - The x-coordinate of the lower left corner of the viewport.
  38999. * @param {Number} y - The y-coordinate of the lower left corner of the viewport.
  39000. * @param {Number} width - The width of the viewport.
  39001. * @param {Number} height - The height of the viewport.
  39002. *
  39003. */
  39004. viewport( x, y, width, height ) {
  39005. const viewport = this._tempVec4.set( x, y, width, height );
  39006. if ( this.currentViewport.equals( viewport ) === false ) {
  39007. const { gl } = this;
  39008. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  39009. this.currentViewport.copy( viewport );
  39010. }
  39011. }
  39012. /**
  39013. * Defines the scissor test.
  39014. *
  39015. * @param {Boolean} boolean - Whether the scissor test should be enabled or not.
  39016. */
  39017. setScissorTest( boolean ) {
  39018. const gl = this.gl;
  39019. if ( boolean ) {
  39020. gl.enable( gl.SCISSOR_TEST );
  39021. } else {
  39022. gl.disable( gl.SCISSOR_TEST );
  39023. }
  39024. }
  39025. /**
  39026. * Specifies whether the stencil test is enabled or not.
  39027. *
  39028. * @param {Boolean} stencilTest - Whether the stencil test is enabled or not.
  39029. */
  39030. setStencilTest( stencilTest ) {
  39031. const { gl } = this;
  39032. if ( stencilTest ) {
  39033. this.enable( gl.STENCIL_TEST );
  39034. } else {
  39035. this.disable( gl.STENCIL_TEST );
  39036. }
  39037. }
  39038. /**
  39039. * Specifies whether stencil values can be written when rendering
  39040. * into a framebuffer or not.
  39041. *
  39042. * This method caches the state so `gl.stencilMask()` is only
  39043. * called when necessary.
  39044. *
  39045. * @param {Boolean} stencilMask - The stencil mask.
  39046. */
  39047. setStencilMask( stencilMask ) {
  39048. if ( this.currentStencilMask !== stencilMask ) {
  39049. this.gl.stencilMask( stencilMask );
  39050. this.currentStencilMask = stencilMask;
  39051. }
  39052. }
  39053. /**
  39054. * Specifies whether the stencil test functions.
  39055. *
  39056. * This method caches the state so `gl.stencilFunc()` is only
  39057. * called when necessary.
  39058. *
  39059. * @param {Number} stencilFunc - The stencil compare function.
  39060. * @param {Number} stencilRef - The reference value for the stencil test.
  39061. * @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.
  39062. */
  39063. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  39064. if ( this.currentStencilFunc !== stencilFunc ||
  39065. this.currentStencilRef !== stencilRef ||
  39066. this.currentStencilFuncMask !== stencilMask ) {
  39067. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  39068. this.currentStencilFunc = stencilFunc;
  39069. this.currentStencilRef = stencilRef;
  39070. this.currentStencilFuncMask = stencilMask;
  39071. }
  39072. }
  39073. /**
  39074. * Specifies whether the stencil test operation.
  39075. *
  39076. * This method caches the state so `gl.stencilOp()` is only
  39077. * called when necessary.
  39078. *
  39079. * @param {Number} stencilFail - The function to use when the stencil test fails.
  39080. * @param {Number} stencilZFail - The function to use when the stencil test passes, but the depth test fail.
  39081. * @param {Number} stencilZPass - The function to use when both the stencil test and the depth test pass,
  39082. * or when the stencil test passes and there is no depth buffer or depth testing is disabled.
  39083. */
  39084. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  39085. if ( this.currentStencilFail !== stencilFail ||
  39086. this.currentStencilZFail !== stencilZFail ||
  39087. this.currentStencilZPass !== stencilZPass ) {
  39088. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  39089. this.currentStencilFail = stencilFail;
  39090. this.currentStencilZFail = stencilZFail;
  39091. this.currentStencilZPass = stencilZPass;
  39092. }
  39093. }
  39094. /**
  39095. * Configures the WebGL state for the given material.
  39096. *
  39097. * @param {Material} material - The material to configure the state for.
  39098. * @param {Number} frontFaceCW - Whether the front faces are counter-clockwise or not.
  39099. * @param {Number} hardwareClippingPlanes - The number of hardware clipping planes.
  39100. */
  39101. setMaterial( material, frontFaceCW, hardwareClippingPlanes ) {
  39102. const { gl } = this;
  39103. material.side === DoubleSide
  39104. ? this.disable( gl.CULL_FACE )
  39105. : this.enable( gl.CULL_FACE );
  39106. let flipSided = ( material.side === BackSide );
  39107. if ( frontFaceCW ) flipSided = ! flipSided;
  39108. this.setFlipSided( flipSided );
  39109. ( material.blending === NormalBlending && material.transparent === false )
  39110. ? this.setBlending( NoBlending )
  39111. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  39112. this.setDepthFunc( material.depthFunc );
  39113. this.setDepthTest( material.depthTest );
  39114. this.setDepthMask( material.depthWrite );
  39115. this.setColorMask( material.colorWrite );
  39116. const stencilWrite = material.stencilWrite;
  39117. this.setStencilTest( stencilWrite );
  39118. if ( stencilWrite ) {
  39119. this.setStencilMask( material.stencilWriteMask );
  39120. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  39121. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  39122. }
  39123. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  39124. material.alphaToCoverage === true && this.backend.renderer.samples > 1
  39125. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  39126. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  39127. if ( hardwareClippingPlanes > 0 ) {
  39128. if ( this.currentClippingPlanes !== hardwareClippingPlanes ) {
  39129. const CLIP_DISTANCE0_WEBGL = 0x3000;
  39130. for ( let i = 0; i < 8; i ++ ) {
  39131. if ( i < hardwareClippingPlanes ) {
  39132. this.enable( CLIP_DISTANCE0_WEBGL + i );
  39133. } else {
  39134. this.disable( CLIP_DISTANCE0_WEBGL + i );
  39135. }
  39136. }
  39137. }
  39138. }
  39139. }
  39140. /**
  39141. * Specifies the polygon offset.
  39142. *
  39143. * This method caches the state so `gl.polygonOffset()` is only
  39144. * called when necessary.
  39145. *
  39146. * @param {Boolean} polygonOffset - Whether polygon offset is enabled or not.
  39147. * @param {Number} factor - The scale factor for the variable depth offset for each polygon.
  39148. * @param {Number} units - The multiplier by which an implementation-specific value is multiplied with to create a constant depth offset.
  39149. */
  39150. setPolygonOffset( polygonOffset, factor, units ) {
  39151. const { gl } = this;
  39152. if ( polygonOffset ) {
  39153. this.enable( gl.POLYGON_OFFSET_FILL );
  39154. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  39155. gl.polygonOffset( factor, units );
  39156. this.currentPolygonOffsetFactor = factor;
  39157. this.currentPolygonOffsetUnits = units;
  39158. }
  39159. } else {
  39160. this.disable( gl.POLYGON_OFFSET_FILL );
  39161. }
  39162. }
  39163. /**
  39164. * Defines the usage of the given WebGL program.
  39165. *
  39166. * This method caches the state so `gl.useProgram()` is only
  39167. * called when necessary.
  39168. *
  39169. * @param {WebGLProgram} program - The WebGL program to use.
  39170. * @return {Boolean} Whether a program change has been executed or not.
  39171. */
  39172. useProgram( program ) {
  39173. if ( this.currentProgram !== program ) {
  39174. this.gl.useProgram( program );
  39175. this.currentProgram = program;
  39176. return true;
  39177. }
  39178. return false;
  39179. }
  39180. // framebuffer
  39181. /**
  39182. * Binds the given framebuffer.
  39183. *
  39184. * This method caches the state so `gl.bindFramebuffer()` is only
  39185. * called when necessary.
  39186. *
  39187. * @param {Number} target - The binding point (target).
  39188. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer to bind.
  39189. * @return {Boolean} Whether a bind has been executed or not.
  39190. */
  39191. bindFramebuffer( target, framebuffer ) {
  39192. const { gl, currentBoundFramebuffers } = this;
  39193. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  39194. gl.bindFramebuffer( target, framebuffer );
  39195. currentBoundFramebuffers[ target ] = framebuffer;
  39196. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  39197. if ( target === gl.DRAW_FRAMEBUFFER ) {
  39198. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  39199. }
  39200. if ( target === gl.FRAMEBUFFER ) {
  39201. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  39202. }
  39203. return true;
  39204. }
  39205. return false;
  39206. }
  39207. /**
  39208. * Defines draw buffers to which fragment colors are written into.
  39209. * Configures the MRT setup of custom framebuffers.
  39210. *
  39211. * This method caches the state so `gl.drawBuffers()` is only
  39212. * called when necessary.
  39213. *
  39214. * @param {RenderContext} renderContext - The render context.
  39215. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer.
  39216. */
  39217. drawBuffers( renderContext, framebuffer ) {
  39218. const { gl } = this;
  39219. let drawBuffers = [];
  39220. let needsUpdate = false;
  39221. if ( renderContext.textures !== null ) {
  39222. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  39223. if ( drawBuffers === undefined ) {
  39224. drawBuffers = [];
  39225. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  39226. }
  39227. const textures = renderContext.textures;
  39228. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  39229. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  39230. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  39231. }
  39232. drawBuffers.length = textures.length;
  39233. needsUpdate = true;
  39234. }
  39235. } else {
  39236. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  39237. drawBuffers[ 0 ] = gl.BACK;
  39238. needsUpdate = true;
  39239. }
  39240. }
  39241. if ( needsUpdate ) {
  39242. gl.drawBuffers( drawBuffers );
  39243. }
  39244. }
  39245. // texture
  39246. /**
  39247. * Makes the given texture unit active.
  39248. *
  39249. * This method caches the state so `gl.activeTexture()` is only
  39250. * called when necessary.
  39251. *
  39252. * @param {Number} webglSlot - The texture unit to make active.
  39253. */
  39254. activeTexture( webglSlot ) {
  39255. const { gl, currentTextureSlot, maxTextures } = this;
  39256. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  39257. if ( currentTextureSlot !== webglSlot ) {
  39258. gl.activeTexture( webglSlot );
  39259. this.currentTextureSlot = webglSlot;
  39260. }
  39261. }
  39262. /**
  39263. * Binds the given WebGL texture to a target.
  39264. *
  39265. * This method caches the state so `gl.bindTexture()` is only
  39266. * called when necessary.
  39267. *
  39268. * @param {Number} webglType - The binding point (target).
  39269. * @param {WebGLTexture} webglTexture - The WebGL texture to bind.
  39270. * @param {Number} webglSlot - The texture.
  39271. */
  39272. bindTexture( webglType, webglTexture, webglSlot ) {
  39273. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  39274. if ( webglSlot === undefined ) {
  39275. if ( currentTextureSlot === null ) {
  39276. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  39277. } else {
  39278. webglSlot = currentTextureSlot;
  39279. }
  39280. }
  39281. let boundTexture = currentBoundTextures[ webglSlot ];
  39282. if ( boundTexture === undefined ) {
  39283. boundTexture = { type: undefined, texture: undefined };
  39284. currentBoundTextures[ webglSlot ] = boundTexture;
  39285. }
  39286. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  39287. if ( currentTextureSlot !== webglSlot ) {
  39288. gl.activeTexture( webglSlot );
  39289. this.currentTextureSlot = webglSlot;
  39290. }
  39291. gl.bindTexture( webglType, webglTexture );
  39292. boundTexture.type = webglType;
  39293. boundTexture.texture = webglTexture;
  39294. }
  39295. }
  39296. /**
  39297. * Binds a given WebGL buffer to a given binding point (target) at a given index.
  39298. *
  39299. * This method caches the state so `gl.bindBufferBase()` is only
  39300. * called when necessary.
  39301. *
  39302. * @param {Number} target - The target for the bind operation.
  39303. * @param {Number} index - The index of the target.
  39304. * @param {WebGLBuffer} buffer - The WebGL buffer.
  39305. * @return {Boolean} Whether a bind has been executed or not.
  39306. */
  39307. bindBufferBase( target, index, buffer ) {
  39308. const { gl } = this;
  39309. const key = `${target}-${index}`;
  39310. if ( this.currentBoundBufferBases[ key ] !== buffer ) {
  39311. gl.bindBufferBase( target, index, buffer );
  39312. this.currentBoundBufferBases[ key ] = buffer;
  39313. return true;
  39314. }
  39315. return false;
  39316. }
  39317. /**
  39318. * Unbinds the current bound texture.
  39319. *
  39320. * This method caches the state so `gl.bindTexture()` is only
  39321. * called when necessary.
  39322. */
  39323. unbindTexture() {
  39324. const { gl, currentTextureSlot, currentBoundTextures } = this;
  39325. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  39326. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  39327. gl.bindTexture( boundTexture.type, null );
  39328. boundTexture.type = undefined;
  39329. boundTexture.texture = undefined;
  39330. }
  39331. }
  39332. }
  39333. /**
  39334. * A WebGL 2 backend utility module with common helpers.
  39335. *
  39336. * @private
  39337. */
  39338. class WebGLUtils {
  39339. /**
  39340. * Constructs a new utility object.
  39341. *
  39342. * @param {WebGLBackend} backend - The WebGL 2 backend.
  39343. */
  39344. constructor( backend ) {
  39345. /**
  39346. * A reference to the WebGL 2 backend.
  39347. *
  39348. * @type {WebGLBackend}
  39349. */
  39350. this.backend = backend;
  39351. /**
  39352. * A reference to the rendering context.
  39353. *
  39354. * @type {WebGL2RenderingContext}
  39355. */
  39356. this.gl = this.backend.gl;
  39357. /**
  39358. * A reference to a backend module holding extension-related
  39359. * utility functions.
  39360. *
  39361. * @type {WebGLExtensions}
  39362. */
  39363. this.extensions = backend.extensions;
  39364. }
  39365. /**
  39366. * Converts the given three.js constant into a WebGL constant.
  39367. * The method currently supports the conversion of texture formats
  39368. * and types.
  39369. *
  39370. * @param {Number} p - The three.js constant.
  39371. * @param {String} [colorSpace=NoColorSpace] - The color space.
  39372. * @return {Number} The corresponding WebGL constant.
  39373. */
  39374. convert( p, colorSpace = NoColorSpace ) {
  39375. const { gl, extensions } = this;
  39376. let extension;
  39377. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  39378. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  39379. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  39380. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  39381. if ( p === ByteType ) return gl.BYTE;
  39382. if ( p === ShortType ) return gl.SHORT;
  39383. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  39384. if ( p === IntType ) return gl.INT;
  39385. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  39386. if ( p === FloatType ) return gl.FLOAT;
  39387. if ( p === HalfFloatType ) {
  39388. return gl.HALF_FLOAT;
  39389. }
  39390. if ( p === AlphaFormat ) return gl.ALPHA;
  39391. if ( p === RGBFormat ) return gl.RGB;
  39392. if ( p === RGBAFormat ) return gl.RGBA;
  39393. if ( p === LuminanceFormat ) return gl.LUMINANCE;
  39394. if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;
  39395. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  39396. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  39397. // WebGL2 formats.
  39398. if ( p === RedFormat ) return gl.RED;
  39399. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  39400. if ( p === RGFormat ) return gl.RG;
  39401. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  39402. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  39403. // S3TC
  39404. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  39405. if ( colorSpace === SRGBColorSpace ) {
  39406. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  39407. if ( extension !== null ) {
  39408. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  39409. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  39410. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  39411. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  39412. } else {
  39413. return null;
  39414. }
  39415. } else {
  39416. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  39417. if ( extension !== null ) {
  39418. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  39419. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  39420. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  39421. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  39422. } else {
  39423. return null;
  39424. }
  39425. }
  39426. }
  39427. // PVRTC
  39428. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  39429. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  39430. if ( extension !== null ) {
  39431. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  39432. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  39433. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  39434. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  39435. } else {
  39436. return null;
  39437. }
  39438. }
  39439. // ETC
  39440. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  39441. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  39442. if ( extension !== null ) {
  39443. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  39444. if ( p === RGBA_ETC2_EAC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  39445. } else {
  39446. return null;
  39447. }
  39448. }
  39449. // ASTC
  39450. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  39451. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  39452. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  39453. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  39454. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  39455. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  39456. if ( extension !== null ) {
  39457. if ( p === RGBA_ASTC_4x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  39458. if ( p === RGBA_ASTC_5x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  39459. if ( p === RGBA_ASTC_5x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  39460. if ( p === RGBA_ASTC_6x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  39461. if ( p === RGBA_ASTC_6x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  39462. if ( p === RGBA_ASTC_8x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  39463. if ( p === RGBA_ASTC_8x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  39464. if ( p === RGBA_ASTC_8x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  39465. if ( p === RGBA_ASTC_10x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  39466. if ( p === RGBA_ASTC_10x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  39467. if ( p === RGBA_ASTC_10x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  39468. if ( p === RGBA_ASTC_10x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  39469. if ( p === RGBA_ASTC_12x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  39470. if ( p === RGBA_ASTC_12x12_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  39471. } else {
  39472. return null;
  39473. }
  39474. }
  39475. // BPTC
  39476. if ( p === RGBA_BPTC_Format ) {
  39477. extension = extensions.get( 'EXT_texture_compression_bptc' );
  39478. if ( extension !== null ) {
  39479. if ( p === RGBA_BPTC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  39480. } else {
  39481. return null;
  39482. }
  39483. }
  39484. // RGTC
  39485. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  39486. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  39487. if ( extension !== null ) {
  39488. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  39489. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  39490. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  39491. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  39492. } else {
  39493. return null;
  39494. }
  39495. }
  39496. //
  39497. if ( p === UnsignedInt248Type ) {
  39498. return gl.UNSIGNED_INT_24_8;
  39499. }
  39500. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  39501. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  39502. }
  39503. /**
  39504. * This method can be used to synchronize the CPU with the GPU by waiting until
  39505. * ongoing GPU commands have been completed.
  39506. *
  39507. * @private
  39508. * @return {Promise} A promise that resolves when all ongoing GPU commands have been completed.
  39509. */
  39510. _clientWaitAsync() {
  39511. const { gl } = this;
  39512. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  39513. gl.flush();
  39514. return new Promise( ( resolve, reject ) => {
  39515. function test() {
  39516. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  39517. if ( res === gl.WAIT_FAILED ) {
  39518. gl.deleteSync( sync );
  39519. reject();
  39520. return;
  39521. }
  39522. if ( res === gl.TIMEOUT_EXPIRED ) {
  39523. requestAnimationFrame( test );
  39524. return;
  39525. }
  39526. gl.deleteSync( sync );
  39527. resolve();
  39528. }
  39529. test();
  39530. } );
  39531. }
  39532. }
  39533. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  39534. /**
  39535. * A WebGL 2 backend utility module for managing textures.
  39536. *
  39537. * @private
  39538. */
  39539. class WebGLTextureUtils {
  39540. /**
  39541. * Constructs a new utility object.
  39542. *
  39543. * @param {WebGLBackend} backend - The WebGL 2 backend.
  39544. */
  39545. constructor( backend ) {
  39546. /**
  39547. * A reference to the WebGL 2 backend.
  39548. *
  39549. * @type {WebGLBackend}
  39550. */
  39551. this.backend = backend;
  39552. /**
  39553. * A reference to the rendering context.
  39554. *
  39555. * @type {WebGL2RenderingContext}
  39556. */
  39557. this.gl = backend.gl;
  39558. /**
  39559. * A reference to a backend module holding extension-related
  39560. * utility functions.
  39561. *
  39562. * @type {WebGLExtensions}
  39563. */
  39564. this.extensions = backend.extensions;
  39565. /**
  39566. * A dictionary for managing default textures. The key
  39567. * is the binding point (target), the value the WEbGL texture object.
  39568. *
  39569. * @type {Object<GLenum,WebGLTexture>}
  39570. */
  39571. this.defaultTextures = {};
  39572. if ( initialized === false ) {
  39573. this._init();
  39574. initialized = true;
  39575. }
  39576. }
  39577. /**
  39578. * Inits the state of the utility.
  39579. *
  39580. * @private
  39581. */
  39582. _init() {
  39583. const gl = this.gl;
  39584. // Store only WebGL constants here.
  39585. wrappingToGL = {
  39586. [ RepeatWrapping ]: gl.REPEAT,
  39587. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  39588. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  39589. };
  39590. filterToGL = {
  39591. [ NearestFilter ]: gl.NEAREST,
  39592. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  39593. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  39594. [ LinearFilter ]: gl.LINEAR,
  39595. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  39596. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  39597. };
  39598. compareToGL = {
  39599. [ NeverCompare ]: gl.NEVER,
  39600. [ AlwaysCompare ]: gl.ALWAYS,
  39601. [ LessCompare ]: gl.LESS,
  39602. [ LessEqualCompare ]: gl.LEQUAL,
  39603. [ EqualCompare ]: gl.EQUAL,
  39604. [ GreaterEqualCompare ]: gl.GEQUAL,
  39605. [ GreaterCompare ]: gl.GREATER,
  39606. [ NotEqualCompare ]: gl.NOTEQUAL
  39607. };
  39608. }
  39609. /**
  39610. * Returns the native texture type for the given texture.
  39611. *
  39612. * @param {Texture} texture - The texture.
  39613. * @return {GLenum} The native texture type.
  39614. */
  39615. getGLTextureType( texture ) {
  39616. const { gl } = this;
  39617. let glTextureType;
  39618. if ( texture.isCubeTexture === true ) {
  39619. glTextureType = gl.TEXTURE_CUBE_MAP;
  39620. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  39621. glTextureType = gl.TEXTURE_2D_ARRAY;
  39622. } else if ( texture.isData3DTexture === true ) { // TODO: isCompressed3DTexture, wait for #26642
  39623. glTextureType = gl.TEXTURE_3D;
  39624. } else {
  39625. glTextureType = gl.TEXTURE_2D;
  39626. }
  39627. return glTextureType;
  39628. }
  39629. /**
  39630. * Returns the native texture type for the given texture.
  39631. *
  39632. * @param {String?} internalFormatName - The internal format name. When `null`, the internal format is derived from the subsequent parameters.
  39633. * @param {GLenum} glFormat - The WebGL format.
  39634. * @param {GLenum} glType - The WebGL type.
  39635. * @param {String} colorSpace - The texture's color space.
  39636. * @param {Boolean} [forceLinearTransfer=false] - Whether to force a linear transfer or not.
  39637. * @return {GLenum} The internal format.
  39638. */
  39639. getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  39640. const { gl, extensions } = this;
  39641. if ( internalFormatName !== null ) {
  39642. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  39643. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  39644. }
  39645. let internalFormat = glFormat;
  39646. if ( glFormat === gl.RED ) {
  39647. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  39648. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  39649. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  39650. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16;
  39651. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  39652. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  39653. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  39654. if ( glType === gl.INT ) internalFormat = gl.R32I;
  39655. }
  39656. if ( glFormat === gl.RED_INTEGER ) {
  39657. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  39658. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  39659. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  39660. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  39661. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  39662. if ( glType === gl.INT ) internalFormat = gl.R32I;
  39663. }
  39664. if ( glFormat === gl.RG ) {
  39665. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  39666. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  39667. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  39668. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16;
  39669. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  39670. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  39671. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  39672. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  39673. }
  39674. if ( glFormat === gl.RG_INTEGER ) {
  39675. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  39676. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  39677. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  39678. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  39679. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  39680. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  39681. }
  39682. if ( glFormat === gl.RGB ) {
  39683. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  39684. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  39685. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8;
  39686. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16;
  39687. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  39688. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  39689. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  39690. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  39691. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8 : gl.RGB8;
  39692. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  39693. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  39694. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  39695. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  39696. }
  39697. if ( glFormat === gl.RGB_INTEGER ) {
  39698. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  39699. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  39700. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  39701. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  39702. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  39703. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  39704. }
  39705. if ( glFormat === gl.RGBA ) {
  39706. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  39707. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  39708. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8;
  39709. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16;
  39710. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  39711. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  39712. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  39713. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  39714. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  39715. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  39716. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  39717. }
  39718. if ( glFormat === gl.RGBA_INTEGER ) {
  39719. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  39720. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  39721. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  39722. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  39723. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  39724. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  39725. }
  39726. if ( glFormat === gl.DEPTH_COMPONENT ) {
  39727. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH24_STENCIL8;
  39728. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  39729. }
  39730. if ( glFormat === gl.DEPTH_STENCIL ) {
  39731. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  39732. }
  39733. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  39734. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  39735. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  39736. extensions.get( 'EXT_color_buffer_float' );
  39737. }
  39738. return internalFormat;
  39739. }
  39740. /**
  39741. * Sets the texture parameters for the given texture.
  39742. *
  39743. * @param {GLenum} textureType - The texture type.
  39744. * @param {Texture} texture - The texture.
  39745. */
  39746. setTextureParameters( textureType, texture ) {
  39747. const { gl, extensions, backend } = this;
  39748. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  39749. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  39750. gl.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  39751. gl.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE );
  39752. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  39753. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  39754. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  39755. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  39756. }
  39757. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  39758. const hasMipmaps = texture.mipmaps !== undefined && texture.mipmaps.length > 0;
  39759. // follow WebGPU backend mapping for texture filtering
  39760. const minFilter = texture.minFilter === LinearFilter && hasMipmaps ? LinearMipmapLinearFilter : texture.minFilter;
  39761. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  39762. if ( texture.compareFunction ) {
  39763. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  39764. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  39765. }
  39766. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  39767. if ( texture.magFilter === NearestFilter ) return;
  39768. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  39769. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  39770. if ( texture.anisotropy > 1 ) {
  39771. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  39772. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) );
  39773. }
  39774. }
  39775. }
  39776. /**
  39777. * Creates a default texture for the given texture that can be used
  39778. * as a placeholder until the actual texture is ready for usage.
  39779. *
  39780. * @param {Texture} texture - The texture to create a default texture for.
  39781. */
  39782. createDefaultTexture( texture ) {
  39783. const { gl, backend, defaultTextures } = this;
  39784. const glTextureType = this.getGLTextureType( texture );
  39785. let textureGPU = defaultTextures[ glTextureType ];
  39786. if ( textureGPU === undefined ) {
  39787. textureGPU = gl.createTexture();
  39788. backend.state.bindTexture( glTextureType, textureGPU );
  39789. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  39790. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  39791. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  39792. defaultTextures[ glTextureType ] = textureGPU;
  39793. }
  39794. backend.set( texture, {
  39795. textureGPU,
  39796. glTextureType,
  39797. isDefault: true
  39798. } );
  39799. }
  39800. /**
  39801. * Defines a texture on the GPU for the given texture object.
  39802. *
  39803. * @param {Texture} texture - The texture.
  39804. * @param {Object} [options={}] - Optional configuration parameter.
  39805. * @return {undefined}
  39806. */
  39807. createTexture( texture, options ) {
  39808. const { gl, backend } = this;
  39809. const { levels, width, height, depth } = options;
  39810. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  39811. const glType = backend.utils.convert( texture.type );
  39812. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  39813. const textureGPU = gl.createTexture();
  39814. const glTextureType = this.getGLTextureType( texture );
  39815. backend.state.bindTexture( glTextureType, textureGPU );
  39816. this.setTextureParameters( glTextureType, texture );
  39817. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  39818. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  39819. } else if ( texture.isData3DTexture ) {
  39820. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  39821. } else if ( ! texture.isVideoTexture ) {
  39822. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  39823. }
  39824. backend.set( texture, {
  39825. textureGPU,
  39826. glTextureType,
  39827. glFormat,
  39828. glType,
  39829. glInternalFormat
  39830. } );
  39831. }
  39832. /**
  39833. * Uploads texture buffer data to the GPU memory.
  39834. *
  39835. * @param {WebGLBuffer} buffer - The buffer data.
  39836. * @param {Texture} texture - The texture,
  39837. */
  39838. copyBufferToTexture( buffer, texture ) {
  39839. const { gl, backend } = this;
  39840. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  39841. const { width, height } = texture.source.data;
  39842. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  39843. backend.state.bindTexture( glTextureType, textureGPU );
  39844. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  39845. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  39846. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  39847. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  39848. backend.state.unbindTexture();
  39849. // debug
  39850. // const framebuffer = gl.createFramebuffer();
  39851. // gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  39852. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  39853. // const readout = new Float32Array( width * height * 4 );
  39854. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  39855. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  39856. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  39857. // gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  39858. // console.log( readout );
  39859. }
  39860. /**
  39861. * Uploads the updated texture data to the GPU.
  39862. *
  39863. * @param {Texture} texture - The texture.
  39864. * @param {Object} [options={}] - Optional configuration parameter.
  39865. */
  39866. updateTexture( texture, options ) {
  39867. const { gl } = this;
  39868. const { width, height } = options;
  39869. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  39870. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  39871. return;
  39872. const getImage = ( source ) => {
  39873. if ( source.isDataTexture ) {
  39874. return source.image.data;
  39875. } else if ( ( typeof HTMLImageElement !== 'undefined' && source instanceof HTMLImageElement ) ||
  39876. ( typeof HTMLCanvasElement !== 'undefined' && source instanceof HTMLCanvasElement ) ||
  39877. ( typeof ImageBitmap !== 'undefined' && source instanceof ImageBitmap ) ||
  39878. source instanceof OffscreenCanvas ) {
  39879. return source;
  39880. }
  39881. return source.data;
  39882. };
  39883. this.backend.state.bindTexture( glTextureType, textureGPU );
  39884. this.setTextureParameters( glTextureType, texture );
  39885. if ( texture.isCompressedTexture ) {
  39886. const mipmaps = texture.mipmaps;
  39887. const image = options.image;
  39888. for ( let i = 0; i < mipmaps.length; i ++ ) {
  39889. const mipmap = mipmaps[ i ];
  39890. if ( texture.isCompressedArrayTexture ) {
  39891. if ( texture.format !== gl.RGBA ) {
  39892. if ( glFormat !== null ) {
  39893. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  39894. } else {
  39895. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  39896. }
  39897. } else {
  39898. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  39899. }
  39900. } else {
  39901. if ( glFormat !== null ) {
  39902. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  39903. } else {
  39904. console.warn( 'Unsupported compressed texture format' );
  39905. }
  39906. }
  39907. }
  39908. } else if ( texture.isCubeTexture ) {
  39909. const images = options.images;
  39910. for ( let i = 0; i < 6; i ++ ) {
  39911. const image = getImage( images[ i ] );
  39912. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  39913. }
  39914. } else if ( texture.isDataArrayTexture ) {
  39915. const image = options.image;
  39916. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  39917. } else if ( texture.isData3DTexture ) {
  39918. const image = options.image;
  39919. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  39920. } else if ( texture.isVideoTexture ) {
  39921. texture.update();
  39922. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  39923. } else {
  39924. const image = getImage( options.image );
  39925. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  39926. }
  39927. }
  39928. /**
  39929. * Generates mipmaps for the given texture.
  39930. *
  39931. * @param {Texture} texture - The texture.
  39932. */
  39933. generateMipmaps( texture ) {
  39934. const { gl, backend } = this;
  39935. const { textureGPU, glTextureType } = backend.get( texture );
  39936. backend.state.bindTexture( glTextureType, textureGPU );
  39937. gl.generateMipmap( glTextureType );
  39938. }
  39939. /**
  39940. * Deallocates the render buffers of the given render target.
  39941. *
  39942. * @param {RenderTarget} renderTarget - The render target.
  39943. */
  39944. deallocateRenderBuffers( renderTarget ) {
  39945. const { gl, backend } = this;
  39946. // remove framebuffer reference
  39947. if ( renderTarget ) {
  39948. const renderContextData = backend.get( renderTarget );
  39949. renderContextData.renderBufferStorageSetup = undefined;
  39950. if ( renderContextData.framebuffers ) {
  39951. for ( const cacheKey in renderContextData.framebuffers ) {
  39952. gl.deleteFramebuffer( renderContextData.framebuffers[ cacheKey ] );
  39953. }
  39954. delete renderContextData.framebuffers;
  39955. }
  39956. if ( renderContextData.depthRenderbuffer ) {
  39957. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  39958. delete renderContextData.depthRenderbuffer;
  39959. }
  39960. if ( renderContextData.stencilRenderbuffer ) {
  39961. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  39962. delete renderContextData.stencilRenderbuffer;
  39963. }
  39964. if ( renderContextData.msaaFrameBuffer ) {
  39965. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  39966. delete renderContextData.msaaFrameBuffer;
  39967. }
  39968. if ( renderContextData.msaaRenderbuffers ) {
  39969. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  39970. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  39971. }
  39972. delete renderContextData.msaaRenderbuffers;
  39973. }
  39974. }
  39975. }
  39976. /**
  39977. * Destroys the GPU data for the given texture object.
  39978. *
  39979. * @param {Texture} texture - The texture.
  39980. */
  39981. destroyTexture( texture ) {
  39982. const { gl, backend } = this;
  39983. const { textureGPU, renderTarget } = backend.get( texture );
  39984. this.deallocateRenderBuffers( renderTarget );
  39985. gl.deleteTexture( textureGPU );
  39986. backend.delete( texture );
  39987. }
  39988. /**
  39989. * Copies data of the given source texture to the given destination texture.
  39990. *
  39991. * @param {Texture} srcTexture - The source texture.
  39992. * @param {Texture} dstTexture - The destination texture.
  39993. * @param {Vector4?} [srcRegion=null] - The region of the source texture to copy.
  39994. * @param {(Vector2|Vector3)?} [dstPosition=null] - The destination position of the copy.
  39995. * @param {Number} [level=0] - The mip level to copy.
  39996. */
  39997. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  39998. const { gl, backend } = this;
  39999. const { state } = this.backend;
  40000. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  40001. let width, height, minX, minY;
  40002. let dstX, dstY;
  40003. if ( srcRegion !== null ) {
  40004. width = srcRegion.max.x - srcRegion.min.x;
  40005. height = srcRegion.max.y - srcRegion.min.y;
  40006. minX = srcRegion.min.x;
  40007. minY = srcRegion.min.y;
  40008. } else {
  40009. width = srcTexture.image.width;
  40010. height = srcTexture.image.height;
  40011. minX = 0;
  40012. minY = 0;
  40013. }
  40014. if ( dstPosition !== null ) {
  40015. dstX = dstPosition.x;
  40016. dstY = dstPosition.y;
  40017. } else {
  40018. dstX = 0;
  40019. dstY = 0;
  40020. }
  40021. state.bindTexture( glTextureType, dstTextureGPU );
  40022. // As another texture upload may have changed pixelStorei
  40023. // parameters, make sure they are correct for the dstTexture
  40024. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  40025. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  40026. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  40027. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  40028. const currentUnpackRowLen = gl.getParameter( gl.UNPACK_ROW_LENGTH );
  40029. const currentUnpackImageHeight = gl.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  40030. const currentUnpackSkipPixels = gl.getParameter( gl.UNPACK_SKIP_PIXELS );
  40031. const currentUnpackSkipRows = gl.getParameter( gl.UNPACK_SKIP_ROWS );
  40032. const currentUnpackSkipImages = gl.getParameter( gl.UNPACK_SKIP_IMAGES );
  40033. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ level ] : srcTexture.image;
  40034. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  40035. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  40036. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  40037. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  40038. if ( srcTexture.isRenderTargetTexture || srcTexture.isDepthTexture ) {
  40039. const srcTextureData = backend.get( srcTexture );
  40040. const dstTextureData = backend.get( dstTexture );
  40041. const srcRenderContextData = backend.get( srcTextureData.renderTarget );
  40042. const dstRenderContextData = backend.get( dstTextureData.renderTarget );
  40043. const srcFramebuffer = srcRenderContextData.framebuffers[ srcTextureData.cacheKey ];
  40044. const dstFramebuffer = dstRenderContextData.framebuffers[ dstTextureData.cacheKey ];
  40045. state.bindFramebuffer( gl.READ_FRAMEBUFFER, srcFramebuffer );
  40046. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, dstFramebuffer );
  40047. let mask = gl.COLOR_BUFFER_BIT;
  40048. if ( srcTexture.isDepthTexture ) mask = gl.DEPTH_BUFFER_BIT;
  40049. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, mask, gl.NEAREST );
  40050. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  40051. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  40052. } else {
  40053. if ( srcTexture.isDataTexture ) {
  40054. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image.data );
  40055. } else {
  40056. if ( srcTexture.isCompressedTexture ) {
  40057. gl.compressedTexSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, image.width, image.height, glFormat, image.data );
  40058. } else {
  40059. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image );
  40060. }
  40061. }
  40062. }
  40063. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  40064. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  40065. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  40066. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  40067. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  40068. // Generate mipmaps only when copying level 0
  40069. if ( level === 0 && dstTexture.generateMipmaps ) gl.generateMipmap( gl.TEXTURE_2D );
  40070. state.unbindTexture();
  40071. }
  40072. /**
  40073. * Copies the current bound framebuffer to the given texture.
  40074. *
  40075. * @param {Texture} texture - The destination texture.
  40076. * @param {RenderContext} renderContext - The render context.
  40077. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  40078. */
  40079. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  40080. const { gl } = this;
  40081. const { state } = this.backend;
  40082. const { textureGPU } = this.backend.get( texture );
  40083. const { x, y, z: width, w: height } = rectangle;
  40084. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  40085. const srcHeight = renderContext.renderTarget ? renderContext.renderTarget.height : this.backend.getDrawingBufferSize().y;
  40086. if ( requireDrawFrameBuffer ) {
  40087. const partial = ( x !== 0 || y !== 0 );
  40088. let mask;
  40089. let attachment;
  40090. if ( texture.isDepthTexture === true ) {
  40091. mask = gl.DEPTH_BUFFER_BIT;
  40092. attachment = gl.DEPTH_ATTACHMENT;
  40093. if ( renderContext.stencil ) {
  40094. mask |= gl.STENCIL_BUFFER_BIT;
  40095. }
  40096. } else {
  40097. mask = gl.COLOR_BUFFER_BIT;
  40098. attachment = gl.COLOR_ATTACHMENT0;
  40099. }
  40100. if ( partial ) {
  40101. const renderTargetContextData = this.backend.get( renderContext.renderTarget );
  40102. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  40103. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  40104. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  40105. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  40106. const flippedY = srcHeight - y - height;
  40107. gl.blitFramebuffer( x, flippedY, x + width, flippedY + height, x, flippedY, x + width, flippedY + height, mask, gl.NEAREST );
  40108. state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  40109. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  40110. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, flippedY, width, height );
  40111. state.unbindTexture();
  40112. } else {
  40113. const fb = gl.createFramebuffer();
  40114. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  40115. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  40116. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  40117. gl.deleteFramebuffer( fb );
  40118. }
  40119. } else {
  40120. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  40121. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, srcHeight - height - y, width, height );
  40122. state.unbindTexture();
  40123. }
  40124. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  40125. this.backend._setFramebuffer( renderContext );
  40126. }
  40127. /**
  40128. * SetupS storage for internal depth/stencil buffers and bind to correct framebuffer.
  40129. *
  40130. * @param {WebGLRenderbuffer} renderbuffer - The render buffer.
  40131. * @param {RenderContext} renderContext - The render context.
  40132. */
  40133. setupRenderBufferStorage( renderbuffer, renderContext ) {
  40134. const { gl } = this;
  40135. const renderTarget = renderContext.renderTarget;
  40136. const { samples, depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  40137. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  40138. if ( depthBuffer && ! stencilBuffer ) {
  40139. let glInternalFormat = gl.DEPTH_COMPONENT24;
  40140. if ( samples > 0 ) {
  40141. if ( depthTexture && depthTexture.isDepthTexture ) {
  40142. if ( depthTexture.type === gl.FLOAT ) {
  40143. glInternalFormat = gl.DEPTH_COMPONENT32F;
  40144. }
  40145. }
  40146. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  40147. } else {
  40148. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  40149. }
  40150. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  40151. } else if ( depthBuffer && stencilBuffer ) {
  40152. if ( samples > 0 ) {
  40153. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  40154. } else {
  40155. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  40156. }
  40157. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  40158. }
  40159. }
  40160. /**
  40161. * Returns texture data as a typed array.
  40162. *
  40163. * @async
  40164. * @param {Texture} texture - The texture to copy.
  40165. * @param {Number} x - The x coordinate of the copy origin.
  40166. * @param {Number} y - The y coordinate of the copy origin.
  40167. * @param {Number} width - The width of the copy.
  40168. * @param {Number} height - The height of the copy.
  40169. * @param {Number} faceIndex - The face index.
  40170. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  40171. */
  40172. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  40173. const { backend, gl } = this;
  40174. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  40175. const fb = gl.createFramebuffer();
  40176. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  40177. const target = texture.isCubeTexture ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex : gl.TEXTURE_2D;
  40178. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, target, textureGPU, 0 );
  40179. const typedArrayType = this._getTypedArrayType( glType );
  40180. const bytesPerTexel = this._getBytesPerTexel( glType, glFormat );
  40181. const elementCount = width * height;
  40182. const byteLength = elementCount * bytesPerTexel;
  40183. const buffer = gl.createBuffer();
  40184. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  40185. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  40186. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  40187. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  40188. await backend.utils._clientWaitAsync();
  40189. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  40190. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  40191. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  40192. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  40193. gl.deleteFramebuffer( fb );
  40194. return dstBuffer;
  40195. }
  40196. /**
  40197. * Returns the corresponding typed array type for the given WebGL data type.
  40198. *
  40199. * @private
  40200. * @param {GLenum} glType - The WebGL data type.
  40201. * @return {TypedArray.constructor} The typed array type.
  40202. */
  40203. _getTypedArrayType( glType ) {
  40204. const { gl } = this;
  40205. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  40206. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  40207. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  40208. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  40209. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  40210. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  40211. if ( glType === gl.HALF_FLOAT ) return Uint16Array;
  40212. if ( glType === gl.FLOAT ) return Float32Array;
  40213. throw new Error( `Unsupported WebGL type: ${glType}` );
  40214. }
  40215. /**
  40216. * Returns the bytes-per-texel value for the given WebGL data type and texture format.
  40217. *
  40218. * @private
  40219. * @param {GLenum} glType - The WebGL data type.
  40220. * @param {GLenum} glFormat - The WebGL texture format.
  40221. * @return {Number} The bytes-per-texel.
  40222. */
  40223. _getBytesPerTexel( glType, glFormat ) {
  40224. const { gl } = this;
  40225. let bytesPerComponent = 0;
  40226. if ( glType === gl.UNSIGNED_BYTE ) bytesPerComponent = 1;
  40227. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ||
  40228. glType === gl.UNSIGNED_SHORT_5_5_5_1 ||
  40229. glType === gl.UNSIGNED_SHORT_5_6_5 ||
  40230. glType === gl.UNSIGNED_SHORT ||
  40231. glType === gl.HALF_FLOAT ) bytesPerComponent = 2;
  40232. if ( glType === gl.UNSIGNED_INT ||
  40233. glType === gl.FLOAT ) bytesPerComponent = 4;
  40234. if ( glFormat === gl.RGBA ) return bytesPerComponent * 4;
  40235. if ( glFormat === gl.RGB ) return bytesPerComponent * 3;
  40236. if ( glFormat === gl.ALPHA ) return bytesPerComponent;
  40237. }
  40238. }
  40239. /**
  40240. * A WebGL 2 backend utility module for managing extensions.
  40241. *
  40242. * @private
  40243. */
  40244. class WebGLExtensions {
  40245. /**
  40246. * Constructs a new utility object.
  40247. *
  40248. * @param {WebGLBackend} backend - The WebGL 2 backend.
  40249. */
  40250. constructor( backend ) {
  40251. /**
  40252. * A reference to the WebGL 2 backend.
  40253. *
  40254. * @type {WebGLBackend}
  40255. */
  40256. this.backend = backend;
  40257. /**
  40258. * A reference to the rendering context.
  40259. *
  40260. * @type {WebGL2RenderingContext}
  40261. */
  40262. this.gl = this.backend.gl;
  40263. /**
  40264. * A list with all the supported WebGL extensions.
  40265. *
  40266. * @type {Array<String>}
  40267. */
  40268. this.availableExtensions = this.gl.getSupportedExtensions();
  40269. /**
  40270. * A dictionary with requested WebGL extensions.
  40271. * The key is the name of the extension, the value
  40272. * the requested extension object.
  40273. *
  40274. * @type {Object<String,Object>}
  40275. */
  40276. this.extensions = {};
  40277. }
  40278. /**
  40279. * Returns the extension object for the given extension name.
  40280. *
  40281. * @param {String} name - The extension name.
  40282. * @return {Object} The extension object.
  40283. */
  40284. get( name ) {
  40285. let extension = this.extensions[ name ];
  40286. if ( extension === undefined ) {
  40287. extension = this.gl.getExtension( name );
  40288. this.extensions[ name ] = extension;
  40289. }
  40290. return extension;
  40291. }
  40292. /**
  40293. * Returns `true` if the requested extension is available.
  40294. *
  40295. * @param {String} name - The extension name.
  40296. * @return {Boolean} Whether the given extension is available or not.
  40297. */
  40298. has( name ) {
  40299. return this.availableExtensions.includes( name );
  40300. }
  40301. }
  40302. /**
  40303. * A WebGL 2 backend utility module for managing the device's capabilities.
  40304. *
  40305. * @private
  40306. */
  40307. class WebGLCapabilities {
  40308. /**
  40309. * Constructs a new utility object.
  40310. *
  40311. * @param {WebGLBackend} backend - The WebGL 2 backend.
  40312. */
  40313. constructor( backend ) {
  40314. /**
  40315. * A reference to the WebGL 2 backend.
  40316. *
  40317. * @type {WebGLBackend}
  40318. */
  40319. this.backend = backend;
  40320. /**
  40321. * This value holds the cached max anisotropy value.
  40322. *
  40323. * @type {Number?}
  40324. * @default null
  40325. */
  40326. this.maxAnisotropy = null;
  40327. }
  40328. /**
  40329. * Returns the maximum anisotropy texture filtering value. This value
  40330. * depends on the device and is reported by the `EXT_texture_filter_anisotropic`
  40331. * WebGL extension.
  40332. *
  40333. * @return {Number} The maximum anisotropy texture filtering value.
  40334. */
  40335. getMaxAnisotropy() {
  40336. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  40337. const gl = this.backend.gl;
  40338. const extensions = this.backend.extensions;
  40339. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  40340. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  40341. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  40342. } else {
  40343. this.maxAnisotropy = 0;
  40344. }
  40345. return this.maxAnisotropy;
  40346. }
  40347. }
  40348. const GLFeatureName = {
  40349. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  40350. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  40351. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  40352. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  40353. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  40354. 'WEBKIT_WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  40355. 'WEBGL_compressed_texture_s3tc': 'texture-compression-bc',
  40356. 'EXT_texture_compression_bptc': 'texture-compression-bptc',
  40357. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  40358. };
  40359. class WebGLBufferRenderer {
  40360. constructor( backend ) {
  40361. this.gl = backend.gl;
  40362. this.extensions = backend.extensions;
  40363. this.info = backend.renderer.info;
  40364. this.mode = null;
  40365. this.index = 0;
  40366. this.type = null;
  40367. this.object = null;
  40368. }
  40369. render( start, count ) {
  40370. const { gl, mode, object, type, info, index } = this;
  40371. if ( index !== 0 ) {
  40372. gl.drawElements( mode, count, type, start );
  40373. } else {
  40374. gl.drawArrays( mode, start, count );
  40375. }
  40376. info.update( object, count, mode, 1 );
  40377. }
  40378. renderInstances( start, count, primcount ) {
  40379. const { gl, mode, type, index, object, info } = this;
  40380. if ( primcount === 0 ) return;
  40381. if ( index !== 0 ) {
  40382. gl.drawElementsInstanced( mode, count, type, start, primcount );
  40383. } else {
  40384. gl.drawArraysInstanced( mode, start, count, primcount );
  40385. }
  40386. info.update( object, count, mode, primcount );
  40387. }
  40388. renderMultiDraw( starts, counts, drawCount ) {
  40389. const { extensions, mode, object, info } = this;
  40390. if ( drawCount === 0 ) return;
  40391. const extension = extensions.get( 'WEBGL_multi_draw' );
  40392. if ( extension === null ) {
  40393. for ( let i = 0; i < drawCount; i ++ ) {
  40394. this.render( starts[ i ], counts[ i ] );
  40395. }
  40396. } else {
  40397. if ( this.index !== 0 ) {
  40398. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  40399. } else {
  40400. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  40401. }
  40402. let elementCount = 0;
  40403. for ( let i = 0; i < drawCount; i ++ ) {
  40404. elementCount += counts[ i ];
  40405. }
  40406. info.update( object, elementCount, mode, 1 );
  40407. }
  40408. }
  40409. renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  40410. const { extensions, mode, object, info } = this;
  40411. if ( drawCount === 0 ) return;
  40412. const extension = extensions.get( 'WEBGL_multi_draw' );
  40413. if ( extension === null ) {
  40414. for ( let i = 0; i < drawCount; i ++ ) {
  40415. this.renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  40416. }
  40417. } else {
  40418. if ( this.index !== 0 ) {
  40419. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, this.type, starts, 0, primcount, 0, drawCount );
  40420. } else {
  40421. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  40422. }
  40423. let elementCount = 0;
  40424. for ( let i = 0; i < drawCount; i ++ ) {
  40425. elementCount += counts[ i ] * primcount[ i ];
  40426. }
  40427. info.update( object, elementCount, mode, 1 );
  40428. }
  40429. }
  40430. //
  40431. }
  40432. class TimestampQueryPool {
  40433. constructor( maxQueries = 256 ) {
  40434. this.trackTimestamp = true;
  40435. this.maxQueries = maxQueries;
  40436. this.currentQueryIndex = 0; // how many queries allocated so far
  40437. this.queryOffsets = new Map(); // track offsets for different contexts
  40438. this.isDisposed = false;
  40439. this.lastValue = 0;
  40440. this.pendingResolve = false;
  40441. }
  40442. /**
  40443. * Allocate queries for a specific renderContext.
  40444. *
  40445. * @abstract
  40446. */
  40447. allocateQueriesForContext( /* renderContext */ ) {}
  40448. /**
  40449. * Resolve all timestamps and return data (or process them).
  40450. *
  40451. * @abstract
  40452. * @returns {Promise<Number>|Number} The resolved timestamp value.
  40453. */
  40454. async resolveQueriesAsync() {}
  40455. /**
  40456. * Dispose of the query pool.
  40457. *
  40458. * @abstract
  40459. */
  40460. dispose() {}
  40461. }
  40462. /**
  40463. * Manages a pool of WebGL timestamp queries for performance measurement.
  40464. * Handles creation, execution, and resolution of timer queries using WebGL extensions.
  40465. * @extends TimestampQueryPool
  40466. */
  40467. class WebGLTimestampQueryPool extends TimestampQueryPool {
  40468. /**
  40469. * Creates a new WebGL timestamp query pool.
  40470. * @param {WebGLRenderingContext|WebGL2RenderingContext} gl - The WebGL context.
  40471. * @param {string} type - The type identifier for this query pool.
  40472. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  40473. */
  40474. constructor( gl, type, maxQueries = 2048 ) {
  40475. super( maxQueries );
  40476. this.gl = gl;
  40477. this.type = type;
  40478. // Check for timer query extensions
  40479. this.ext = gl.getExtension( 'EXT_disjoint_timer_query_webgl2' ) ||
  40480. gl.getExtension( 'EXT_disjoint_timer_query' );
  40481. if ( ! this.ext ) {
  40482. console.warn( 'EXT_disjoint_timer_query not supported; timestamps will be disabled.' );
  40483. this.trackTimestamp = false;
  40484. return;
  40485. }
  40486. // Create query objects
  40487. this.queries = [];
  40488. for ( let i = 0; i < this.maxQueries; i ++ ) {
  40489. this.queries.push( gl.createQuery() );
  40490. }
  40491. this.activeQuery = null;
  40492. this.queryStates = new Map(); // Track state of each query: 'inactive', 'started', 'ended'
  40493. }
  40494. /**
  40495. * Allocates a pair of queries for a given render context.
  40496. * @param {Object} renderContext - The render context to allocate queries for.
  40497. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  40498. */
  40499. allocateQueriesForContext( renderContext ) {
  40500. if ( ! this.trackTimestamp ) return null;
  40501. // Check if we have enough space for a new query pair
  40502. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  40503. 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() } ).` );
  40504. return null;
  40505. }
  40506. const baseOffset = this.currentQueryIndex;
  40507. this.currentQueryIndex += 2;
  40508. // Initialize query states
  40509. this.queryStates.set( baseOffset, 'inactive' );
  40510. this.queryOffsets.set( renderContext.id, baseOffset );
  40511. return baseOffset;
  40512. }
  40513. /**
  40514. * Begins a timestamp query for the specified render context.
  40515. * @param {Object} renderContext - The render context to begin timing for.
  40516. */
  40517. beginQuery( renderContext ) {
  40518. if ( ! this.trackTimestamp || this.isDisposed ) {
  40519. return;
  40520. }
  40521. const baseOffset = this.queryOffsets.get( renderContext.id );
  40522. if ( baseOffset == null ) {
  40523. return;
  40524. }
  40525. // Don't start a new query if there's an active one
  40526. if ( this.activeQuery !== null ) {
  40527. return;
  40528. }
  40529. const query = this.queries[ baseOffset ];
  40530. if ( ! query ) {
  40531. return;
  40532. }
  40533. try {
  40534. // Only begin if query is inactive
  40535. if ( this.queryStates.get( baseOffset ) === 'inactive' ) {
  40536. this.gl.beginQuery( this.ext.TIME_ELAPSED_EXT, query );
  40537. this.activeQuery = baseOffset;
  40538. this.queryStates.set( baseOffset, 'started' );
  40539. }
  40540. } catch ( error ) {
  40541. console.error( 'Error in beginQuery:', error );
  40542. this.activeQuery = null;
  40543. this.queryStates.set( baseOffset, 'inactive' );
  40544. }
  40545. }
  40546. /**
  40547. * Ends the active timestamp query for the specified render context.
  40548. * @param {Object} renderContext - The render context to end timing for.
  40549. * @param {string} renderContext.id - Unique identifier for the render context.
  40550. */
  40551. endQuery( renderContext ) {
  40552. if ( ! this.trackTimestamp || this.isDisposed ) {
  40553. return;
  40554. }
  40555. const baseOffset = this.queryOffsets.get( renderContext.id );
  40556. if ( baseOffset == null ) {
  40557. return;
  40558. }
  40559. // Only end if this is the active query
  40560. if ( this.activeQuery !== baseOffset ) {
  40561. return;
  40562. }
  40563. try {
  40564. this.gl.endQuery( this.ext.TIME_ELAPSED_EXT );
  40565. this.queryStates.set( baseOffset, 'ended' );
  40566. this.activeQuery = null;
  40567. } catch ( error ) {
  40568. console.error( 'Error in endQuery:', error );
  40569. // Reset state on error
  40570. this.queryStates.set( baseOffset, 'inactive' );
  40571. this.activeQuery = null;
  40572. }
  40573. }
  40574. /**
  40575. * Asynchronously resolves all completed queries and returns the total duration.
  40576. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  40577. */
  40578. async resolveQueriesAsync() {
  40579. if ( ! this.trackTimestamp || this.pendingResolve ) {
  40580. return this.lastValue;
  40581. }
  40582. this.pendingResolve = true;
  40583. try {
  40584. // Wait for all ended queries to complete
  40585. const resolvePromises = [];
  40586. for ( const [ baseOffset, state ] of this.queryStates ) {
  40587. if ( state === 'ended' ) {
  40588. const query = this.queries[ baseOffset ];
  40589. resolvePromises.push( this.resolveQuery( query ) );
  40590. }
  40591. }
  40592. if ( resolvePromises.length === 0 ) {
  40593. return this.lastValue;
  40594. }
  40595. const results = await Promise.all( resolvePromises );
  40596. const totalDuration = results.reduce( ( acc, val ) => acc + val, 0 );
  40597. // Store the last valid result
  40598. this.lastValue = totalDuration;
  40599. // Reset states
  40600. this.currentQueryIndex = 0;
  40601. this.queryOffsets.clear();
  40602. this.queryStates.clear();
  40603. this.activeQuery = null;
  40604. return totalDuration;
  40605. } catch ( error ) {
  40606. console.error( 'Error resolving queries:', error );
  40607. return this.lastValue;
  40608. } finally {
  40609. this.pendingResolve = false;
  40610. }
  40611. }
  40612. /**
  40613. * Resolves a single query, checking for completion and disjoint operation.
  40614. * @private
  40615. * @param {WebGLQuery} query - The query object to resolve.
  40616. * @returns {Promise<number>} The elapsed time in milliseconds.
  40617. */
  40618. async resolveQuery( query ) {
  40619. return new Promise( ( resolve ) => {
  40620. if ( this.isDisposed ) {
  40621. resolve( this.lastValue );
  40622. return;
  40623. }
  40624. let timeoutId;
  40625. let isResolved = false;
  40626. const cleanup = () => {
  40627. if ( timeoutId ) {
  40628. clearTimeout( timeoutId );
  40629. timeoutId = null;
  40630. }
  40631. };
  40632. const finalizeResolution = ( value ) => {
  40633. if ( ! isResolved ) {
  40634. isResolved = true;
  40635. cleanup();
  40636. resolve( value );
  40637. }
  40638. };
  40639. const checkQuery = () => {
  40640. if ( this.isDisposed ) {
  40641. finalizeResolution( this.lastValue );
  40642. return;
  40643. }
  40644. try {
  40645. // Check if the GPU timer was disjoint (i.e., timing was unreliable)
  40646. const disjoint = this.gl.getParameter( this.ext.GPU_DISJOINT_EXT );
  40647. if ( disjoint ) {
  40648. finalizeResolution( this.lastValue );
  40649. return;
  40650. }
  40651. const available = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT_AVAILABLE );
  40652. if ( ! available ) {
  40653. timeoutId = setTimeout( checkQuery, 1 );
  40654. return;
  40655. }
  40656. const elapsed = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT );
  40657. resolve( Number( elapsed ) / 1e6 ); // Convert nanoseconds to milliseconds
  40658. } catch ( error ) {
  40659. console.error( 'Error checking query:', error );
  40660. resolve( this.lastValue );
  40661. }
  40662. };
  40663. checkQuery();
  40664. } );
  40665. }
  40666. /**
  40667. * Releases all resources held by this query pool.
  40668. * This includes deleting all query objects and clearing internal state.
  40669. */
  40670. dispose() {
  40671. if ( this.isDisposed ) {
  40672. return;
  40673. }
  40674. this.isDisposed = true;
  40675. if ( ! this.trackTimestamp ) return;
  40676. for ( const query of this.queries ) {
  40677. this.gl.deleteQuery( query );
  40678. }
  40679. this.queries = [];
  40680. this.queryStates.clear();
  40681. this.queryOffsets.clear();
  40682. this.lastValue = 0;
  40683. this.activeQuery = null;
  40684. }
  40685. }
  40686. /**
  40687. * A backend implementation targeting WebGL 2.
  40688. *
  40689. * @private
  40690. * @augments Backend
  40691. */
  40692. class WebGLBackend extends Backend {
  40693. /**
  40694. * Constructs a new WebGPU backend.
  40695. *
  40696. * @param {Object} parameters - The configuration parameter.
  40697. * @param {Boolean} [parameters.logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  40698. * @param {Boolean} [parameters.alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  40699. * @param {Boolean} [parameters.depth=true] - Whether the default framebuffer should have a depth buffer or not.
  40700. * @param {Boolean} [parameters.stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  40701. * @param {Boolean} [parameters.antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  40702. * @param {Number} [parameters.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.
  40703. * @param {Boolean} [parameters.forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  40704. * @param {WebGL2RenderingContext} [parameters.context=undefined] - A WebGL 2 rendering context.
  40705. */
  40706. constructor( parameters = {} ) {
  40707. super( parameters );
  40708. /**
  40709. * This flag can be used for type testing.
  40710. *
  40711. * @type {Boolean}
  40712. * @readonly
  40713. * @default true
  40714. */
  40715. this.isWebGLBackend = true;
  40716. /**
  40717. * A reference to a backend module holding shader attribute-related
  40718. * utility functions.
  40719. *
  40720. * @type {WebGLAttributeUtils?}
  40721. * @default null
  40722. */
  40723. this.attributeUtils = null;
  40724. /**
  40725. * A reference to a backend module holding extension-related
  40726. * utility functions.
  40727. *
  40728. * @type {WebGLExtensions?}
  40729. * @default null
  40730. */
  40731. this.extensions = null;
  40732. /**
  40733. * A reference to a backend module holding capability-related
  40734. * utility functions.
  40735. *
  40736. * @type {WebGLCapabilities?}
  40737. * @default null
  40738. */
  40739. this.capabilities = null;
  40740. /**
  40741. * A reference to a backend module holding texture-related
  40742. * utility functions.
  40743. *
  40744. * @type {WebGLTextureUtils?}
  40745. * @default null
  40746. */
  40747. this.textureUtils = null;
  40748. /**
  40749. * A reference to a backend module holding renderer-related
  40750. * utility functions.
  40751. *
  40752. * @type {WebGLBufferRenderer?}
  40753. * @default null
  40754. */
  40755. this.bufferRenderer = null;
  40756. /**
  40757. * A reference to the rendering context.
  40758. *
  40759. * @type {WebGL2RenderingContext?}
  40760. * @default null
  40761. */
  40762. this.gl = null;
  40763. /**
  40764. * A reference to a backend module holding state-related
  40765. * utility functions.
  40766. *
  40767. * @type {WebGLState?}
  40768. * @default null
  40769. */
  40770. this.state = null;
  40771. /**
  40772. * A reference to a backend module holding common
  40773. * utility functions.
  40774. *
  40775. * @type {WebGLUtils?}
  40776. * @default null
  40777. */
  40778. this.utils = null;
  40779. /**
  40780. * Dictionary for caching VAOs.
  40781. *
  40782. * @type {Object<String,WebGLVertexArrayObject>}
  40783. */
  40784. this.vaoCache = {};
  40785. /**
  40786. * Dictionary for caching transform feedback objects.
  40787. *
  40788. * @type {Object<String,WebGLTransformFeedback>}
  40789. */
  40790. this.transformFeedbackCache = {};
  40791. /**
  40792. * Controls if `gl.RASTERIZER_DISCARD` should be enabled or not.
  40793. * Only relevant when using compute shaders.
  40794. *
  40795. * @type {Boolean}
  40796. * @default false
  40797. */
  40798. this.discard = false;
  40799. /**
  40800. * A reference to the `EXT_disjoint_timer_query_webgl2` extension. `null` if the
  40801. * device does not support the extension.
  40802. *
  40803. * @type {EXTDisjointTimerQueryWebGL2?}
  40804. * @default null
  40805. */
  40806. this.disjoint = null;
  40807. /**
  40808. * A reference to the `KHR_parallel_shader_compile` extension. `null` if the
  40809. * device does not support the extension.
  40810. *
  40811. * @type {KHRParallelShaderCompile?}
  40812. * @default null
  40813. */
  40814. this.parallel = null;
  40815. /**
  40816. * Whether to track timestamps with a Timestamp Query API or not.
  40817. *
  40818. * @type {Boolean}
  40819. * @default false
  40820. */
  40821. this.trackTimestamp = ( parameters.trackTimestamp === true );
  40822. /**
  40823. * A reference to the current render context.
  40824. *
  40825. * @private
  40826. * @type {RenderContext}
  40827. * @default null
  40828. */
  40829. this._currentContext = null;
  40830. /**
  40831. * A unique collection of bindings.
  40832. *
  40833. * @private
  40834. * @type {WeakSet}
  40835. */
  40836. this._knownBindings = new WeakSet();
  40837. /**
  40838. * The target framebuffer when rendering with
  40839. * the WebXR device API.
  40840. *
  40841. * @private
  40842. * @type {WebGLFramebuffer}
  40843. * @default null
  40844. */
  40845. this._xrFamebuffer = null;
  40846. }
  40847. /**
  40848. * Initializes the backend so it is ready for usage.
  40849. *
  40850. * @param {Renderer} renderer - The renderer.
  40851. */
  40852. init( renderer ) {
  40853. super.init( renderer );
  40854. //
  40855. const parameters = this.parameters;
  40856. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2' );
  40857. function onContextLost( event ) {
  40858. event.preventDefault();
  40859. const contextLossInfo = {
  40860. api: 'WebGL',
  40861. message: event.statusMessage || 'Unknown reason',
  40862. reason: null,
  40863. originalEvent: event
  40864. };
  40865. renderer.onDeviceLost( contextLossInfo );
  40866. }
  40867. this._onContextLost = onContextLost;
  40868. renderer.domElement.addEventListener( 'webglcontextlost', onContextLost, false );
  40869. this.gl = glContext;
  40870. this.extensions = new WebGLExtensions( this );
  40871. this.capabilities = new WebGLCapabilities( this );
  40872. this.attributeUtils = new WebGLAttributeUtils( this );
  40873. this.textureUtils = new WebGLTextureUtils( this );
  40874. this.bufferRenderer = new WebGLBufferRenderer( this );
  40875. this.state = new WebGLState( this );
  40876. this.utils = new WebGLUtils( this );
  40877. this.extensions.get( 'EXT_color_buffer_float' );
  40878. this.extensions.get( 'WEBGL_clip_cull_distance' );
  40879. this.extensions.get( 'OES_texture_float_linear' );
  40880. this.extensions.get( 'EXT_color_buffer_half_float' );
  40881. this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  40882. this.extensions.get( 'WEBGL_render_shared_exponent' );
  40883. this.extensions.get( 'WEBGL_multi_draw' );
  40884. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  40885. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  40886. }
  40887. /**
  40888. * The coordinate system of the backend.
  40889. *
  40890. * @type {Number}
  40891. * @readonly
  40892. */
  40893. get coordinateSystem() {
  40894. return WebGLCoordinateSystem;
  40895. }
  40896. /**
  40897. * This method performs a readback operation by moving buffer data from
  40898. * a storage buffer attribute from the GPU to the CPU.
  40899. *
  40900. * @async
  40901. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  40902. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  40903. */
  40904. async getArrayBufferAsync( attribute ) {
  40905. return await this.attributeUtils.getArrayBufferAsync( attribute );
  40906. }
  40907. /**
  40908. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  40909. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  40910. *
  40911. * @async
  40912. * @return {Promise} A Promise that resolves when synchronization has been finished.
  40913. */
  40914. async waitForGPU() {
  40915. await this.utils._clientWaitAsync();
  40916. }
  40917. /**
  40918. * Ensures the backend is XR compatible.
  40919. *
  40920. * @async
  40921. * @return {Promise} A Promise that resolve when the renderer is XR compatible.
  40922. */
  40923. async makeXRCompatible() {
  40924. const attributes = this.gl.getContextAttributes();
  40925. if ( attributes.xrCompatible !== true ) {
  40926. await this.gl.makeXRCompatible();
  40927. }
  40928. }
  40929. /**
  40930. * Sets the XR rendering destination.
  40931. *
  40932. * @param {WebGLFramebuffer} xrFamebuffer - The XR framebuffer.
  40933. */
  40934. setXRTarget( xrFamebuffer ) {
  40935. this._xrFamebuffer = xrFamebuffer;
  40936. }
  40937. /**
  40938. * Configures the given XR render target with external textures.
  40939. *
  40940. * This method is only relevant when using the WebXR Layers API.
  40941. *
  40942. * @param {XRRenderTarget} renderTarget - The XR render target.
  40943. * @param {WebGLTexture} colorTexture - A native color texture.
  40944. * @param {WebGLTexture?} [depthTexture=null] - A native depth texture.
  40945. */
  40946. setXRRenderTargetTextures( renderTarget, colorTexture, depthTexture = null ) {
  40947. const gl = this.gl;
  40948. this.set( renderTarget.texture, { textureGPU: colorTexture, glInternalFormat: gl.RGBA8 } ); // see #24698 why RGBA8 and not SRGB8_ALPHA8 is used
  40949. if ( depthTexture !== null ) {
  40950. const glInternalFormat = renderTarget.stencilBuffer ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  40951. this.set( renderTarget.depthTexture, { textureGPU: depthTexture, glInternalFormat: glInternalFormat } );
  40952. renderTarget.autoAllocateDepthBuffer = false;
  40953. }
  40954. }
  40955. /**
  40956. * Inits a time stamp query for the given render context.
  40957. *
  40958. * @param {RenderContext} renderContext - The render context.
  40959. */
  40960. initTimestampQuery( renderContext ) {
  40961. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  40962. const type = renderContext.isComputeNode ? 'compute' : 'render';
  40963. if ( ! this.timestampQueryPool[ type ] ) {
  40964. // TODO: Variable maxQueries?
  40965. this.timestampQueryPool[ type ] = new WebGLTimestampQueryPool( this.gl, type, 2048 );
  40966. }
  40967. const timestampQueryPool = this.timestampQueryPool[ type ];
  40968. const baseOffset = timestampQueryPool.allocateQueriesForContext( renderContext );
  40969. if ( baseOffset !== null ) {
  40970. timestampQueryPool.beginQuery( renderContext );
  40971. }
  40972. }
  40973. // timestamp utils
  40974. /**
  40975. * Prepares the timestamp buffer.
  40976. *
  40977. * @param {RenderContext} renderContext - The render context.
  40978. */
  40979. prepareTimestampBuffer( renderContext ) {
  40980. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  40981. const type = renderContext.isComputeNode ? 'compute' : 'render';
  40982. const timestampQueryPool = this.timestampQueryPool[ type ];
  40983. timestampQueryPool.endQuery( renderContext );
  40984. }
  40985. /**
  40986. * Returns the backend's rendering context.
  40987. *
  40988. * @return {WebGL2RenderingContext} The rendering context.
  40989. */
  40990. getContext() {
  40991. return this.gl;
  40992. }
  40993. /**
  40994. * This method is executed at the beginning of a render call and prepares
  40995. * the WebGL state for upcoming render calls
  40996. *
  40997. * @param {RenderContext} renderContext - The render context.
  40998. */
  40999. beginRender( renderContext ) {
  41000. const { state, gl } = this;
  41001. const renderContextData = this.get( renderContext );
  41002. //
  41003. //
  41004. this.initTimestampQuery( renderContext );
  41005. renderContextData.previousContext = this._currentContext;
  41006. this._currentContext = renderContext;
  41007. this._setFramebuffer( renderContext );
  41008. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  41009. //
  41010. if ( renderContext.viewport ) {
  41011. this.updateViewport( renderContext );
  41012. } else {
  41013. state.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  41014. }
  41015. if ( renderContext.scissor ) {
  41016. const { x, y, width, height } = renderContext.scissorValue;
  41017. state.scissor( x, renderContext.height - height - y, width, height );
  41018. }
  41019. const occlusionQueryCount = renderContext.occlusionQueryCount;
  41020. if ( occlusionQueryCount > 0 ) {
  41021. // Get a reference to the array of objects with queries. The renderContextData property
  41022. // can be changed by another render pass before the async reading of all previous queries complete
  41023. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  41024. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  41025. renderContextData.lastOcclusionObject = null;
  41026. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  41027. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  41028. renderContextData.occlusionQueryIndex = 0;
  41029. }
  41030. }
  41031. /**
  41032. * This method is executed at the end of a render call and finalizes work
  41033. * after draw calls.
  41034. *
  41035. * @param {RenderContext} renderContext - The render context.
  41036. */
  41037. finishRender( renderContext ) {
  41038. const { gl, state } = this;
  41039. const renderContextData = this.get( renderContext );
  41040. const previousContext = renderContextData.previousContext;
  41041. const occlusionQueryCount = renderContext.occlusionQueryCount;
  41042. if ( occlusionQueryCount > 0 ) {
  41043. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  41044. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  41045. }
  41046. this.resolveOccludedAsync( renderContext );
  41047. }
  41048. const textures = renderContext.textures;
  41049. if ( textures !== null ) {
  41050. for ( let i = 0; i < textures.length; i ++ ) {
  41051. const texture = textures[ i ];
  41052. if ( texture.generateMipmaps ) {
  41053. this.generateMipmaps( texture );
  41054. }
  41055. }
  41056. }
  41057. this._currentContext = previousContext;
  41058. if ( renderContext.textures !== null && renderContext.renderTarget ) {
  41059. const renderTargetContextData = this.get( renderContext.renderTarget );
  41060. const { samples } = renderContext.renderTarget;
  41061. if ( samples > 0 ) {
  41062. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  41063. const mask = gl.COLOR_BUFFER_BIT;
  41064. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  41065. const textures = renderContext.textures;
  41066. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  41067. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  41068. for ( let i = 0; i < textures.length; i ++ ) {
  41069. // TODO Add support for MRT
  41070. if ( renderContext.scissor ) {
  41071. const { x, y, width, height } = renderContext.scissorValue;
  41072. const viewY = renderContext.height - height - y;
  41073. gl.blitFramebuffer( x, viewY, x + width, viewY + height, x, viewY, x + width, viewY + height, mask, gl.NEAREST );
  41074. gl.invalidateSubFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray, x, viewY, width, height );
  41075. } else {
  41076. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  41077. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  41078. }
  41079. }
  41080. }
  41081. }
  41082. if ( previousContext !== null ) {
  41083. this._setFramebuffer( previousContext );
  41084. if ( previousContext.viewport ) {
  41085. this.updateViewport( previousContext );
  41086. } else {
  41087. state.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  41088. }
  41089. }
  41090. this.prepareTimestampBuffer( renderContext );
  41091. }
  41092. /**
  41093. * This method processes the result of occlusion queries and writes it
  41094. * into render context data.
  41095. *
  41096. * @async
  41097. * @param {RenderContext} renderContext - The render context.
  41098. */
  41099. resolveOccludedAsync( renderContext ) {
  41100. const renderContextData = this.get( renderContext );
  41101. // handle occlusion query results
  41102. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  41103. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  41104. const occluded = new WeakSet();
  41105. const { gl } = this;
  41106. renderContextData.currentOcclusionQueryObjects = null;
  41107. renderContextData.currentOcclusionQueries = null;
  41108. const check = () => {
  41109. let completed = 0;
  41110. // check all queries and requeue as appropriate
  41111. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  41112. const query = currentOcclusionQueries[ i ];
  41113. if ( query === null ) continue;
  41114. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  41115. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) === 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  41116. currentOcclusionQueries[ i ] = null;
  41117. gl.deleteQuery( query );
  41118. completed ++;
  41119. }
  41120. }
  41121. if ( completed < currentOcclusionQueries.length ) {
  41122. requestAnimationFrame( check );
  41123. } else {
  41124. renderContextData.occluded = occluded;
  41125. }
  41126. };
  41127. check();
  41128. }
  41129. }
  41130. /**
  41131. * Returns `true` if the given 3D object is fully occluded by other
  41132. * 3D objects in the scene.
  41133. *
  41134. * @param {RenderContext} renderContext - The render context.
  41135. * @param {Object3D} object - The 3D object to test.
  41136. * @return {Boolean} Whether the 3D object is fully occluded or not.
  41137. */
  41138. isOccluded( renderContext, object ) {
  41139. const renderContextData = this.get( renderContext );
  41140. return renderContextData.occluded && renderContextData.occluded.has( object );
  41141. }
  41142. /**
  41143. * Updates the viewport with the values from the given render context.
  41144. *
  41145. * @param {RenderContext} renderContext - The render context.
  41146. */
  41147. updateViewport( renderContext ) {
  41148. const { state } = this;
  41149. const { x, y, width, height } = renderContext.viewportValue;
  41150. state.viewport( x, renderContext.height - height - y, width, height );
  41151. }
  41152. /**
  41153. * Defines the scissor test.
  41154. *
  41155. * @param {Boolean} boolean - Whether the scissor test should be enabled or not.
  41156. */
  41157. setScissorTest( boolean ) {
  41158. const state = this.state;
  41159. state.setScissorTest( boolean );
  41160. }
  41161. /**
  41162. * Performs a clear operation.
  41163. *
  41164. * @param {Boolean} color - Whether the color buffer should be cleared or not.
  41165. * @param {Boolean} depth - Whether the depth buffer should be cleared or not.
  41166. * @param {Boolean} stencil - Whether the stencil buffer should be cleared or not.
  41167. * @param {Object?} [descriptor=null] - The render context of the current set render target.
  41168. * @param {Boolean} [setFrameBuffer=true] - TODO.
  41169. */
  41170. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true ) {
  41171. const { gl } = this;
  41172. if ( descriptor === null ) {
  41173. const clearColor = this.getClearColor();
  41174. // premultiply alpha
  41175. clearColor.r *= clearColor.a;
  41176. clearColor.g *= clearColor.a;
  41177. clearColor.b *= clearColor.a;
  41178. descriptor = {
  41179. textures: null,
  41180. clearColorValue: clearColor
  41181. };
  41182. }
  41183. //
  41184. let clear = 0;
  41185. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  41186. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  41187. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  41188. if ( clear !== 0 ) {
  41189. let clearColor;
  41190. if ( descriptor.clearColorValue ) {
  41191. clearColor = descriptor.clearColorValue;
  41192. } else {
  41193. clearColor = this.getClearColor();
  41194. // premultiply alpha
  41195. clearColor.r *= clearColor.a;
  41196. clearColor.g *= clearColor.a;
  41197. clearColor.b *= clearColor.a;
  41198. }
  41199. if ( depth ) this.state.setDepthMask( true );
  41200. if ( descriptor.textures === null ) {
  41201. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  41202. gl.clear( clear );
  41203. } else {
  41204. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  41205. if ( color ) {
  41206. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  41207. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  41208. }
  41209. }
  41210. if ( depth && stencil ) {
  41211. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, 1, 0 );
  41212. } else if ( depth ) {
  41213. gl.clearBufferfv( gl.DEPTH, 0, [ 1.0 ] );
  41214. } else if ( stencil ) {
  41215. gl.clearBufferiv( gl.STENCIL, 0, [ 0 ] );
  41216. }
  41217. }
  41218. }
  41219. }
  41220. /**
  41221. * This method is executed at the beginning of a compute call and
  41222. * prepares the state for upcoming compute tasks.
  41223. *
  41224. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  41225. */
  41226. beginCompute( computeGroup ) {
  41227. const { state, gl } = this;
  41228. state.bindFramebuffer( gl.FRAMEBUFFER, null );
  41229. this.initTimestampQuery( computeGroup );
  41230. }
  41231. /**
  41232. * Executes a compute command for the given compute node.
  41233. *
  41234. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  41235. * @param {Node} computeNode - The compute node.
  41236. * @param {Array<BindGroup>} bindings - The bindings.
  41237. * @param {ComputePipeline} pipeline - The compute pipeline.
  41238. */
  41239. compute( computeGroup, computeNode, bindings, pipeline ) {
  41240. const { state, gl } = this;
  41241. if ( this.discard === false ) {
  41242. // required here to handle async behaviour of render.compute()
  41243. gl.enable( gl.RASTERIZER_DISCARD );
  41244. this.discard = true;
  41245. }
  41246. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  41247. const vaoKey = this._getVaoKey( null, attributes );
  41248. const vaoGPU = this.vaoCache[ vaoKey ];
  41249. if ( vaoGPU === undefined ) {
  41250. this._createVao( null, attributes );
  41251. } else {
  41252. gl.bindVertexArray( vaoGPU );
  41253. }
  41254. state.useProgram( programGPU );
  41255. this._bindUniforms( bindings );
  41256. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  41257. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  41258. gl.beginTransformFeedback( gl.POINTS );
  41259. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  41260. gl.drawArraysInstanced( gl.POINTS, 0, 1, computeNode.count );
  41261. } else {
  41262. gl.drawArrays( gl.POINTS, 0, computeNode.count );
  41263. }
  41264. gl.endTransformFeedback();
  41265. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  41266. // switch active buffers
  41267. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  41268. const dualAttributeData = transformBuffers[ i ];
  41269. if ( dualAttributeData.pbo ) {
  41270. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  41271. }
  41272. dualAttributeData.switchBuffers();
  41273. }
  41274. }
  41275. /**
  41276. * This method is executed at the end of a compute call and
  41277. * finalizes work after compute tasks.
  41278. *
  41279. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  41280. */
  41281. finishCompute( computeGroup ) {
  41282. const gl = this.gl;
  41283. this.discard = false;
  41284. gl.disable( gl.RASTERIZER_DISCARD );
  41285. this.prepareTimestampBuffer( computeGroup );
  41286. if ( this._currentContext ) {
  41287. this._setFramebuffer( this._currentContext );
  41288. }
  41289. }
  41290. /**
  41291. * Executes a draw command for the given render object.
  41292. *
  41293. * @param {RenderObject} renderObject - The render object to draw.
  41294. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  41295. */
  41296. draw( renderObject/*, info*/ ) {
  41297. const { object, pipeline, material, context, hardwareClippingPlanes } = renderObject;
  41298. const { programGPU } = this.get( pipeline );
  41299. const { gl, state } = this;
  41300. const contextData = this.get( context );
  41301. const drawParams = renderObject.getDrawParameters();
  41302. if ( drawParams === null ) return;
  41303. //
  41304. this._bindUniforms( renderObject.getBindings() );
  41305. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  41306. state.setMaterial( material, frontFaceCW, hardwareClippingPlanes );
  41307. state.useProgram( programGPU );
  41308. //
  41309. const renderObjectData = this.get( renderObject );
  41310. let vaoGPU = renderObjectData.staticVao;
  41311. if ( vaoGPU === undefined || renderObjectData.geometryId !== renderObject.geometry.id ) {
  41312. const vaoKey = this._getVaoKey( renderObject.getIndex(), renderObject.getAttributes() );
  41313. vaoGPU = this.vaoCache[ vaoKey ];
  41314. if ( vaoGPU === undefined ) {
  41315. let staticVao;
  41316. ( { vaoGPU, staticVao } = this._createVao( renderObject.getIndex(), renderObject.getAttributes() ) );
  41317. if ( staticVao ) {
  41318. renderObjectData.staticVao = vaoGPU;
  41319. renderObjectData.geometryId = renderObject.geometry.id;
  41320. }
  41321. }
  41322. }
  41323. gl.bindVertexArray( vaoGPU );
  41324. //
  41325. const index = renderObject.getIndex();
  41326. //
  41327. const lastObject = contextData.lastOcclusionObject;
  41328. if ( lastObject !== object && lastObject !== undefined ) {
  41329. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  41330. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  41331. contextData.occlusionQueryIndex ++;
  41332. }
  41333. if ( object.occlusionTest === true ) {
  41334. const query = gl.createQuery();
  41335. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  41336. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  41337. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  41338. }
  41339. contextData.lastOcclusionObject = object;
  41340. }
  41341. //
  41342. const renderer = this.bufferRenderer;
  41343. if ( object.isPoints ) renderer.mode = gl.POINTS;
  41344. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  41345. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  41346. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  41347. else {
  41348. if ( material.wireframe === true ) {
  41349. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  41350. renderer.mode = gl.LINES;
  41351. } else {
  41352. renderer.mode = gl.TRIANGLES;
  41353. }
  41354. }
  41355. //
  41356. const { vertexCount, instanceCount } = drawParams;
  41357. let { firstVertex } = drawParams;
  41358. renderer.object = object;
  41359. if ( index !== null ) {
  41360. firstVertex *= index.array.BYTES_PER_ELEMENT;
  41361. const indexData = this.get( index );
  41362. renderer.index = index.count;
  41363. renderer.type = indexData.type;
  41364. } else {
  41365. renderer.index = 0;
  41366. }
  41367. const draw = () => {
  41368. if ( object.isBatchedMesh ) {
  41369. if ( object._multiDrawInstances !== null ) {
  41370. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  41371. } else if ( ! this.hasFeature( 'WEBGL_multi_draw' ) ) {
  41372. warnOnce( 'THREE.WebGLRenderer: WEBGL_multi_draw not supported.' );
  41373. } else {
  41374. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  41375. }
  41376. } else if ( instanceCount > 1 ) {
  41377. renderer.renderInstances( firstVertex, vertexCount, instanceCount );
  41378. } else {
  41379. renderer.render( firstVertex, vertexCount );
  41380. }
  41381. };
  41382. if ( renderObject.camera.isArrayCamera && renderObject.camera.cameras.length > 0 ) {
  41383. const cameraData = this.get( renderObject.camera );
  41384. const cameras = renderObject.camera.cameras;
  41385. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' ).bindings[ 0 ];
  41386. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  41387. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  41388. const indexesGPU = [];
  41389. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  41390. const bufferGPU = gl.createBuffer();
  41391. data[ 0 ] = i;
  41392. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  41393. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.STATIC_DRAW );
  41394. indexesGPU.push( bufferGPU );
  41395. }
  41396. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  41397. }
  41398. const cameraIndexData = this.get( cameraIndex );
  41399. const pixelRatio = this.renderer.getPixelRatio();
  41400. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  41401. const subCamera = cameras[ i ];
  41402. if ( object.layers.test( subCamera.layers ) ) {
  41403. const vp = subCamera.viewport;
  41404. const x = vp.x * pixelRatio;
  41405. const y = vp.y * pixelRatio;
  41406. const width = vp.width * pixelRatio;
  41407. const height = vp.height * pixelRatio;
  41408. state.viewport(
  41409. Math.floor( x ),
  41410. Math.floor( renderObject.context.height - height - y ),
  41411. Math.floor( width ),
  41412. Math.floor( height )
  41413. );
  41414. state.bindBufferBase( gl.UNIFORM_BUFFER, cameraIndexData.index, cameraData.indexesGPU[ i ] );
  41415. draw();
  41416. }
  41417. }
  41418. } else {
  41419. draw();
  41420. }
  41421. //
  41422. gl.bindVertexArray( null );
  41423. }
  41424. /**
  41425. * Explain why always null is returned.
  41426. *
  41427. * @param {RenderObject} renderObject - The render object.
  41428. * @return {Boolean} Whether the render pipeline requires an update or not.
  41429. */
  41430. needsRenderUpdate( /*renderObject*/ ) {
  41431. return false;
  41432. }
  41433. /**
  41434. * Explain why no cache key is computed.
  41435. *
  41436. * @param {RenderObject} renderObject - The render object.
  41437. * @return {String} The cache key.
  41438. */
  41439. getRenderCacheKey( /*renderObject*/ ) {
  41440. return '';
  41441. }
  41442. // textures
  41443. /**
  41444. * Creates a default texture for the given texture that can be used
  41445. * as a placeholder until the actual texture is ready for usage.
  41446. *
  41447. * @param {Texture} texture - The texture to create a default texture for.
  41448. */
  41449. createDefaultTexture( texture ) {
  41450. this.textureUtils.createDefaultTexture( texture );
  41451. }
  41452. /**
  41453. * Defines a texture on the GPU for the given texture object.
  41454. *
  41455. * @param {Texture} texture - The texture.
  41456. * @param {Object} [options={}] - Optional configuration parameter.
  41457. */
  41458. createTexture( texture, options ) {
  41459. this.textureUtils.createTexture( texture, options );
  41460. }
  41461. /**
  41462. * Uploads the updated texture data to the GPU.
  41463. *
  41464. * @param {Texture} texture - The texture.
  41465. * @param {Object} [options={}] - Optional configuration parameter.
  41466. */
  41467. updateTexture( texture, options ) {
  41468. this.textureUtils.updateTexture( texture, options );
  41469. }
  41470. /**
  41471. * Generates mipmaps for the given texture.
  41472. *
  41473. * @param {Texture} texture - The texture.
  41474. */
  41475. generateMipmaps( texture ) {
  41476. this.textureUtils.generateMipmaps( texture );
  41477. }
  41478. /**
  41479. * Destroys the GPU data for the given texture object.
  41480. *
  41481. * @param {Texture} texture - The texture.
  41482. */
  41483. destroyTexture( texture ) {
  41484. this.textureUtils.destroyTexture( texture );
  41485. }
  41486. /**
  41487. * Returns texture data as a typed array.
  41488. *
  41489. * @async
  41490. * @param {Texture} texture - The texture to copy.
  41491. * @param {Number} x - The x coordinate of the copy origin.
  41492. * @param {Number} y - The y coordinate of the copy origin.
  41493. * @param {Number} width - The width of the copy.
  41494. * @param {Number} height - The height of the copy.
  41495. * @param {Number} faceIndex - The face index.
  41496. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  41497. */
  41498. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  41499. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  41500. }
  41501. /**
  41502. * This method does nothing since WebGL 2 has no concept of samplers.
  41503. *
  41504. * @param {Texture} texture - The texture to create the sampler for.
  41505. */
  41506. createSampler( /*texture*/ ) {
  41507. //console.warn( 'Abstract class.' );
  41508. }
  41509. /**
  41510. * This method does nothing since WebGL 2 has no concept of samplers.
  41511. *
  41512. * @param {Texture} texture - The texture to destroy the sampler for.
  41513. */
  41514. destroySampler( /*texture*/ ) {}
  41515. // node builder
  41516. /**
  41517. * Returns a node builder for the given render object.
  41518. *
  41519. * @param {RenderObject} object - The render object.
  41520. * @param {Renderer} renderer - The renderer.
  41521. * @return {GLSLNodeBuilder} The node builder.
  41522. */
  41523. createNodeBuilder( object, renderer ) {
  41524. return new GLSLNodeBuilder( object, renderer );
  41525. }
  41526. // program
  41527. /**
  41528. * Creates a shader program from the given programmable stage.
  41529. *
  41530. * @param {ProgrammableStage} program - The programmable stage.
  41531. */
  41532. createProgram( program ) {
  41533. const gl = this.gl;
  41534. const { stage, code } = program;
  41535. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  41536. gl.shaderSource( shader, code );
  41537. gl.compileShader( shader );
  41538. this.set( program, {
  41539. shaderGPU: shader
  41540. } );
  41541. }
  41542. /**
  41543. * Destroys the shader program of the given programmable stage.
  41544. *
  41545. * @param {ProgrammableStage} program - The programmable stage.
  41546. */
  41547. destroyProgram( program ) {
  41548. this.delete( program );
  41549. }
  41550. /**
  41551. * Creates a render pipeline for the given render object.
  41552. *
  41553. * @param {RenderObject} renderObject - The render object.
  41554. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  41555. */
  41556. createRenderPipeline( renderObject, promises ) {
  41557. const gl = this.gl;
  41558. const pipeline = renderObject.pipeline;
  41559. // Program
  41560. const { fragmentProgram, vertexProgram } = pipeline;
  41561. const programGPU = gl.createProgram();
  41562. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  41563. const vertexShader = this.get( vertexProgram ).shaderGPU;
  41564. gl.attachShader( programGPU, fragmentShader );
  41565. gl.attachShader( programGPU, vertexShader );
  41566. gl.linkProgram( programGPU );
  41567. this.set( pipeline, {
  41568. programGPU,
  41569. fragmentShader,
  41570. vertexShader
  41571. } );
  41572. if ( promises !== null && this.parallel ) {
  41573. const p = new Promise( ( resolve /*, reject*/ ) => {
  41574. const parallel = this.parallel;
  41575. const checkStatus = () => {
  41576. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  41577. this._completeCompile( renderObject, pipeline );
  41578. resolve();
  41579. } else {
  41580. requestAnimationFrame( checkStatus );
  41581. }
  41582. };
  41583. checkStatus();
  41584. } );
  41585. promises.push( p );
  41586. return;
  41587. }
  41588. this._completeCompile( renderObject, pipeline );
  41589. }
  41590. /**
  41591. * Formats the source code of error messages.
  41592. *
  41593. * @private
  41594. * @param {String} string - The code.
  41595. * @param {Number} errorLine - The error line.
  41596. * @return {String} The formatted code.
  41597. */
  41598. _handleSource( string, errorLine ) {
  41599. const lines = string.split( '\n' );
  41600. const lines2 = [];
  41601. const from = Math.max( errorLine - 6, 0 );
  41602. const to = Math.min( errorLine + 6, lines.length );
  41603. for ( let i = from; i < to; i ++ ) {
  41604. const line = i + 1;
  41605. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  41606. }
  41607. return lines2.join( '\n' );
  41608. }
  41609. /**
  41610. * Gets the shader compilation errors from the info log.
  41611. *
  41612. * @private
  41613. * @param {WebGL2RenderingContext} gl - The rendering context.
  41614. * @param {WebGLShader} shader - The WebGL shader object.
  41615. * @param {String} type - The shader type.
  41616. * @return {String} The shader errors.
  41617. */
  41618. _getShaderErrors( gl, shader, type ) {
  41619. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  41620. const errors = gl.getShaderInfoLog( shader ).trim();
  41621. if ( status && errors === '' ) return '';
  41622. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  41623. if ( errorMatches ) {
  41624. const errorLine = parseInt( errorMatches[ 1 ] );
  41625. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  41626. } else {
  41627. return errors;
  41628. }
  41629. }
  41630. /**
  41631. * Logs shader compilation errors.
  41632. *
  41633. * @private
  41634. * @param {WebGLProgram} programGPU - The WebGL program.
  41635. * @param {WebGLShader} glFragmentShader - The fragment shader as a native WebGL shader object.
  41636. * @param {WebGLShader} glVertexShader - The vertex shader as a native WebGL shader object.
  41637. */
  41638. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  41639. if ( this.renderer.debug.checkShaderErrors ) {
  41640. const gl = this.gl;
  41641. const programLog = gl.getProgramInfoLog( programGPU ).trim();
  41642. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  41643. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  41644. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  41645. } else {
  41646. // default error reporting
  41647. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  41648. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  41649. console.error(
  41650. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  41651. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  41652. 'Program Info Log: ' + programLog + '\n' +
  41653. vertexErrors + '\n' +
  41654. fragmentErrors
  41655. );
  41656. }
  41657. } else if ( programLog !== '' ) {
  41658. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  41659. }
  41660. }
  41661. }
  41662. /**
  41663. * Completes the shader program setup for the given render object.
  41664. *
  41665. * @private
  41666. * @param {RenderObject} renderObject - The render object.
  41667. * @param {RenderPipeline} pipeline - The render pipeline.
  41668. */
  41669. _completeCompile( renderObject, pipeline ) {
  41670. const { state, gl } = this;
  41671. const pipelineData = this.get( pipeline );
  41672. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  41673. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  41674. this._logProgramError( programGPU, fragmentShader, vertexShader );
  41675. }
  41676. state.useProgram( programGPU );
  41677. // Bindings
  41678. const bindings = renderObject.getBindings();
  41679. this._setupBindings( bindings, programGPU );
  41680. //
  41681. this.set( pipeline, {
  41682. programGPU
  41683. } );
  41684. }
  41685. /**
  41686. * Creates a compute pipeline for the given compute node.
  41687. *
  41688. * @param {ComputePipeline} computePipeline - The compute pipeline.
  41689. * @param {Array<BindGroup>} bindings - The bindings.
  41690. */
  41691. createComputePipeline( computePipeline, bindings ) {
  41692. const { state, gl } = this;
  41693. // Program
  41694. const fragmentProgram = {
  41695. stage: 'fragment',
  41696. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  41697. };
  41698. this.createProgram( fragmentProgram );
  41699. const { computeProgram } = computePipeline;
  41700. const programGPU = gl.createProgram();
  41701. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  41702. const vertexShader = this.get( computeProgram ).shaderGPU;
  41703. const transforms = computeProgram.transforms;
  41704. const transformVaryingNames = [];
  41705. const transformAttributeNodes = [];
  41706. for ( let i = 0; i < transforms.length; i ++ ) {
  41707. const transform = transforms[ i ];
  41708. transformVaryingNames.push( transform.varyingName );
  41709. transformAttributeNodes.push( transform.attributeNode );
  41710. }
  41711. gl.attachShader( programGPU, fragmentShader );
  41712. gl.attachShader( programGPU, vertexShader );
  41713. gl.transformFeedbackVaryings(
  41714. programGPU,
  41715. transformVaryingNames,
  41716. gl.SEPARATE_ATTRIBS
  41717. );
  41718. gl.linkProgram( programGPU );
  41719. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  41720. this._logProgramError( programGPU, fragmentShader, vertexShader );
  41721. }
  41722. state.useProgram( programGPU );
  41723. // Bindings
  41724. this._setupBindings( bindings, programGPU );
  41725. const attributeNodes = computeProgram.attributes;
  41726. const attributes = [];
  41727. const transformBuffers = [];
  41728. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  41729. const attribute = attributeNodes[ i ].node.attribute;
  41730. attributes.push( attribute );
  41731. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  41732. }
  41733. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  41734. const attribute = transformAttributeNodes[ i ].attribute;
  41735. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  41736. const attributeData = this.get( attribute );
  41737. transformBuffers.push( attributeData );
  41738. }
  41739. //
  41740. this.set( computePipeline, {
  41741. programGPU,
  41742. transformBuffers,
  41743. attributes
  41744. } );
  41745. }
  41746. /**
  41747. * Creates bindings from the given bind group definition.
  41748. *
  41749. * @param {BindGroup} bindGroup - The bind group.
  41750. * @param {Array<BindGroup>} bindings - Array of bind groups.
  41751. * @param {Number} cacheIndex - The cache index.
  41752. * @param {Number} version - The version.
  41753. */
  41754. createBindings( bindGroup, bindings /*, cacheIndex, version*/ ) {
  41755. if ( this._knownBindings.has( bindings ) === false ) {
  41756. this._knownBindings.add( bindings );
  41757. let uniformBuffers = 0;
  41758. let textures = 0;
  41759. for ( const bindGroup of bindings ) {
  41760. this.set( bindGroup, {
  41761. textures: textures,
  41762. uniformBuffers: uniformBuffers
  41763. } );
  41764. for ( const binding of bindGroup.bindings ) {
  41765. if ( binding.isUniformBuffer ) uniformBuffers ++;
  41766. if ( binding.isSampledTexture ) textures ++;
  41767. }
  41768. }
  41769. }
  41770. this.updateBindings( bindGroup, bindings );
  41771. }
  41772. /**
  41773. * Updates the given bind group definition.
  41774. *
  41775. * @param {BindGroup} bindGroup - The bind group.
  41776. * @param {Array<BindGroup>} bindings - Array of bind groups.
  41777. * @param {Number} cacheIndex - The cache index.
  41778. * @param {Number} version - The version.
  41779. */
  41780. updateBindings( bindGroup /*, bindings, cacheIndex, version*/ ) {
  41781. const { gl } = this;
  41782. const bindGroupData = this.get( bindGroup );
  41783. let i = bindGroupData.uniformBuffers;
  41784. let t = bindGroupData.textures;
  41785. for ( const binding of bindGroup.bindings ) {
  41786. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  41787. const data = binding.buffer;
  41788. const bufferGPU = gl.createBuffer();
  41789. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  41790. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  41791. this.set( binding, {
  41792. index: i ++,
  41793. bufferGPU
  41794. } );
  41795. } else if ( binding.isSampledTexture ) {
  41796. const { textureGPU, glTextureType } = this.get( binding.texture );
  41797. this.set( binding, {
  41798. index: t ++,
  41799. textureGPU,
  41800. glTextureType
  41801. } );
  41802. }
  41803. }
  41804. }
  41805. /**
  41806. * Updates a buffer binding.
  41807. *
  41808. * @param {Buffer} binding - The buffer binding to update.
  41809. */
  41810. updateBinding( binding ) {
  41811. const gl = this.gl;
  41812. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  41813. const bindingData = this.get( binding );
  41814. const bufferGPU = bindingData.bufferGPU;
  41815. const data = binding.buffer;
  41816. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  41817. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  41818. }
  41819. }
  41820. // attributes
  41821. /**
  41822. * Creates the GPU buffer of an indexed shader attribute.
  41823. *
  41824. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  41825. */
  41826. createIndexAttribute( attribute ) {
  41827. const gl = this.gl;
  41828. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  41829. }
  41830. /**
  41831. * Creates the GPU buffer of a shader attribute.
  41832. *
  41833. * @param {BufferAttribute} attribute - The buffer attribute.
  41834. */
  41835. createAttribute( attribute ) {
  41836. if ( this.has( attribute ) ) return;
  41837. const gl = this.gl;
  41838. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  41839. }
  41840. /**
  41841. * Creates the GPU buffer of a storage attribute.
  41842. *
  41843. * @param {BufferAttribute} attribute - The buffer attribute.
  41844. */
  41845. createStorageAttribute( attribute ) {
  41846. if ( this.has( attribute ) ) return;
  41847. const gl = this.gl;
  41848. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  41849. }
  41850. /**
  41851. * Updates the GPU buffer of a shader attribute.
  41852. *
  41853. * @param {BufferAttribute} attribute - The buffer attribute to update.
  41854. */
  41855. updateAttribute( attribute ) {
  41856. this.attributeUtils.updateAttribute( attribute );
  41857. }
  41858. /**
  41859. * Destroys the GPU buffer of a shader attribute.
  41860. *
  41861. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  41862. */
  41863. destroyAttribute( attribute ) {
  41864. this.attributeUtils.destroyAttribute( attribute );
  41865. }
  41866. /**
  41867. * Checks if the given feature is supported by the backend.
  41868. *
  41869. * @param {String} name - The feature's name.
  41870. * @return {Boolean} Whether the feature is supported or not.
  41871. */
  41872. hasFeature( name ) {
  41873. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  41874. const extensions = this.extensions;
  41875. for ( let i = 0; i < keysMatching.length; i ++ ) {
  41876. if ( extensions.has( keysMatching[ i ] ) ) return true;
  41877. }
  41878. return false;
  41879. }
  41880. /**
  41881. * Returns the maximum anisotropy texture filtering value.
  41882. *
  41883. * @return {Number} The maximum anisotropy texture filtering value.
  41884. */
  41885. getMaxAnisotropy() {
  41886. return this.capabilities.getMaxAnisotropy();
  41887. }
  41888. /**
  41889. * Copies data of the given source texture to the given destination texture.
  41890. *
  41891. * @param {Texture} srcTexture - The source texture.
  41892. * @param {Texture} dstTexture - The destination texture.
  41893. * @param {Vector4?} [srcRegion=null] - The region of the source texture to copy.
  41894. * @param {(Vector2|Vector3)?} [dstPosition=null] - The destination position of the copy.
  41895. * @param {Number} [level=0] - The mip level to copy.
  41896. */
  41897. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  41898. this.textureUtils.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  41899. }
  41900. /**
  41901. * Copies the current bound framebuffer to the given texture.
  41902. *
  41903. * @param {Texture} texture - The destination texture.
  41904. * @param {RenderContext} renderContext - The render context.
  41905. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  41906. */
  41907. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  41908. this.textureUtils.copyFramebufferToTexture( texture, renderContext, rectangle );
  41909. }
  41910. /**
  41911. * Configures the active framebuffer from the given render context.
  41912. *
  41913. * @private
  41914. * @param {RenderContext} descriptor - The render context.
  41915. */
  41916. _setFramebuffer( descriptor ) {
  41917. const { gl, state } = this;
  41918. let currentFrameBuffer = null;
  41919. if ( descriptor.textures !== null ) {
  41920. const renderTarget = descriptor.renderTarget;
  41921. const renderTargetContextData = this.get( renderTarget );
  41922. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  41923. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  41924. const isRenderTarget3D = renderTarget.isRenderTarget3D === true;
  41925. const isRenderTargetArray = renderTarget.isRenderTargetArray === true;
  41926. const isXRRenderTarget = renderTarget.isXRRenderTarget === true;
  41927. const hasExternalTextures = ( isXRRenderTarget === true && renderTarget.hasExternalTextures === true );
  41928. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  41929. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  41930. const cacheKey = getCacheKey( descriptor );
  41931. let fb;
  41932. if ( isCube ) {
  41933. renderTargetContextData.cubeFramebuffers || ( renderTargetContextData.cubeFramebuffers = {} );
  41934. fb = renderTargetContextData.cubeFramebuffers[ cacheKey ];
  41935. } else if ( isXRRenderTarget && hasExternalTextures === false ) {
  41936. fb = this._xrFamebuffer;
  41937. } else {
  41938. renderTargetContextData.framebuffers || ( renderTargetContextData.framebuffers = {} );
  41939. fb = renderTargetContextData.framebuffers[ cacheKey ];
  41940. }
  41941. if ( fb === undefined ) {
  41942. fb = gl.createFramebuffer();
  41943. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  41944. const textures = descriptor.textures;
  41945. if ( isCube ) {
  41946. renderTargetContextData.cubeFramebuffers[ cacheKey ] = fb;
  41947. const { textureGPU } = this.get( textures[ 0 ] );
  41948. const cubeFace = this.renderer._activeCubeFace;
  41949. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, 0 );
  41950. } else {
  41951. renderTargetContextData.framebuffers[ cacheKey ] = fb;
  41952. for ( let i = 0; i < textures.length; i ++ ) {
  41953. const texture = textures[ i ];
  41954. const textureData = this.get( texture );
  41955. textureData.renderTarget = descriptor.renderTarget;
  41956. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  41957. const attachment = gl.COLOR_ATTACHMENT0 + i;
  41958. if ( isRenderTarget3D || isRenderTargetArray ) {
  41959. const layer = this.renderer._activeCubeFace;
  41960. gl.framebufferTextureLayer( gl.FRAMEBUFFER, attachment, textureData.textureGPU, 0, layer );
  41961. } else {
  41962. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  41963. }
  41964. }
  41965. state.drawBuffers( descriptor, fb );
  41966. }
  41967. if ( descriptor.depthTexture !== null ) {
  41968. const textureData = this.get( descriptor.depthTexture );
  41969. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  41970. textureData.renderTarget = descriptor.renderTarget;
  41971. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  41972. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  41973. }
  41974. } else {
  41975. // rebind external XR textures
  41976. if ( isXRRenderTarget && hasExternalTextures ) {
  41977. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  41978. // rebind color
  41979. const textureData = this.get( descriptor.textures[ 0 ] );
  41980. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  41981. // rebind depth
  41982. if ( descriptor.depthTexture !== null ) {
  41983. const textureData = this.get( descriptor.depthTexture );
  41984. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  41985. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  41986. }
  41987. }
  41988. }
  41989. if ( samples > 0 ) {
  41990. if ( msaaFb === undefined ) {
  41991. const invalidationArray = [];
  41992. msaaFb = gl.createFramebuffer();
  41993. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  41994. const msaaRenderbuffers = [];
  41995. const textures = descriptor.textures;
  41996. for ( let i = 0; i < textures.length; i ++ ) {
  41997. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  41998. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  41999. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  42000. if ( depthBuffer ) {
  42001. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  42002. invalidationArray.push( depthStyle );
  42003. }
  42004. const texture = descriptor.textures[ i ];
  42005. const textureData = this.get( texture );
  42006. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, descriptor.width, descriptor.height );
  42007. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  42008. }
  42009. renderTargetContextData.msaaFrameBuffer = msaaFb;
  42010. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  42011. if ( depthRenderbuffer === undefined ) {
  42012. depthRenderbuffer = gl.createRenderbuffer();
  42013. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, descriptor );
  42014. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  42015. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  42016. invalidationArray.push( depthStyle );
  42017. }
  42018. renderTargetContextData.invalidationArray = invalidationArray;
  42019. }
  42020. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  42021. } else {
  42022. currentFrameBuffer = fb;
  42023. }
  42024. }
  42025. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  42026. }
  42027. /**
  42028. * Computes the VAO key for the given index and attributes.
  42029. *
  42030. * @private
  42031. * @param {BufferAttribute?} index - The index. `null` for non-indexed geometries.
  42032. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  42033. * @return {String} The VAO key.
  42034. */
  42035. _getVaoKey( index, attributes ) {
  42036. let key = '';
  42037. if ( index !== null ) {
  42038. const indexData = this.get( index );
  42039. key += ':' + indexData.id;
  42040. }
  42041. for ( let i = 0; i < attributes.length; i ++ ) {
  42042. const attributeData = this.get( attributes[ i ] );
  42043. key += ':' + attributeData.id;
  42044. }
  42045. return key;
  42046. }
  42047. /**
  42048. * Creates a VAO from the index and attributes.
  42049. *
  42050. * @private
  42051. * @param {BufferAttribute?} index - The index. `null` for non-indexed geometries.
  42052. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  42053. * @return {Object} The VAO data.
  42054. */
  42055. _createVao( index, attributes ) {
  42056. const { gl } = this;
  42057. const vaoGPU = gl.createVertexArray();
  42058. let key = '';
  42059. let staticVao = true;
  42060. gl.bindVertexArray( vaoGPU );
  42061. if ( index !== null ) {
  42062. const indexData = this.get( index );
  42063. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexData.bufferGPU );
  42064. key += ':' + indexData.id;
  42065. }
  42066. for ( let i = 0; i < attributes.length; i ++ ) {
  42067. const attribute = attributes[ i ];
  42068. const attributeData = this.get( attribute );
  42069. key += ':' + attributeData.id;
  42070. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  42071. gl.enableVertexAttribArray( i );
  42072. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) staticVao = false;
  42073. let stride, offset;
  42074. if ( attribute.isInterleavedBufferAttribute === true ) {
  42075. stride = attribute.data.stride * attributeData.bytesPerElement;
  42076. offset = attribute.offset * attributeData.bytesPerElement;
  42077. } else {
  42078. stride = 0;
  42079. offset = 0;
  42080. }
  42081. if ( attributeData.isInteger ) {
  42082. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  42083. } else {
  42084. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  42085. }
  42086. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  42087. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  42088. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  42089. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  42090. }
  42091. }
  42092. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  42093. this.vaoCache[ key ] = vaoGPU;
  42094. return { vaoGPU, staticVao };
  42095. }
  42096. /**
  42097. * Creates a transform feedback from the given transform buffers.
  42098. *
  42099. * @private
  42100. * @param {Array<DualAttributeData>} transformBuffers - The transform buffers.
  42101. * @return {WebGLTransformFeedback} The transform feedback.
  42102. */
  42103. _getTransformFeedback( transformBuffers ) {
  42104. let key = '';
  42105. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  42106. key += ':' + transformBuffers[ i ].id;
  42107. }
  42108. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  42109. if ( transformFeedbackGPU !== undefined ) {
  42110. return transformFeedbackGPU;
  42111. }
  42112. const { gl } = this;
  42113. transformFeedbackGPU = gl.createTransformFeedback();
  42114. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  42115. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  42116. const attributeData = transformBuffers[ i ];
  42117. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  42118. }
  42119. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  42120. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  42121. return transformFeedbackGPU;
  42122. }
  42123. /**
  42124. * Setups the given bindings.
  42125. *
  42126. * @private
  42127. * @param {Array<BindGroup>} bindings - The bindings.
  42128. * @param {WebGLProgram} programGPU - The WebGL program.
  42129. */
  42130. _setupBindings( bindings, programGPU ) {
  42131. const gl = this.gl;
  42132. for ( const bindGroup of bindings ) {
  42133. for ( const binding of bindGroup.bindings ) {
  42134. const bindingData = this.get( binding );
  42135. const index = bindingData.index;
  42136. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  42137. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  42138. gl.uniformBlockBinding( programGPU, location, index );
  42139. } else if ( binding.isSampledTexture ) {
  42140. const location = gl.getUniformLocation( programGPU, binding.name );
  42141. gl.uniform1i( location, index );
  42142. }
  42143. }
  42144. }
  42145. }
  42146. /**
  42147. * Binds the given uniforms.
  42148. *
  42149. * @private
  42150. * @param {Array<BindGroup>} bindings - The bindings.
  42151. */
  42152. _bindUniforms( bindings ) {
  42153. const { gl, state } = this;
  42154. for ( const bindGroup of bindings ) {
  42155. for ( const binding of bindGroup.bindings ) {
  42156. const bindingData = this.get( binding );
  42157. const index = bindingData.index;
  42158. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  42159. // TODO USE bindBufferRange to group multiple uniform buffers
  42160. state.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  42161. } else if ( binding.isSampledTexture ) {
  42162. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  42163. }
  42164. }
  42165. }
  42166. }
  42167. /**
  42168. * Frees internal resources.
  42169. */
  42170. dispose() {
  42171. const extension = this.extensions.get( 'WEBGL_lose_context' );
  42172. if ( extension ) extension.loseContext();
  42173. this.renderer.domElement.removeEventListener( 'webglcontextlost', this._onContextLost );
  42174. }
  42175. }
  42176. const GPUPrimitiveTopology = {
  42177. PointList: 'point-list',
  42178. LineList: 'line-list',
  42179. LineStrip: 'line-strip',
  42180. TriangleList: 'triangle-list',
  42181. TriangleStrip: 'triangle-strip',
  42182. };
  42183. const GPUCompareFunction = {
  42184. Never: 'never',
  42185. Less: 'less',
  42186. Equal: 'equal',
  42187. LessEqual: 'less-equal',
  42188. Greater: 'greater',
  42189. NotEqual: 'not-equal',
  42190. GreaterEqual: 'greater-equal',
  42191. Always: 'always'
  42192. };
  42193. const GPUStoreOp = {
  42194. Store: 'store',
  42195. Discard: 'discard'
  42196. };
  42197. const GPULoadOp = {
  42198. Load: 'load',
  42199. Clear: 'clear'
  42200. };
  42201. const GPUFrontFace = {
  42202. CCW: 'ccw',
  42203. CW: 'cw'
  42204. };
  42205. const GPUCullMode = {
  42206. None: 'none',
  42207. Front: 'front',
  42208. Back: 'back'
  42209. };
  42210. const GPUIndexFormat = {
  42211. Uint16: 'uint16',
  42212. Uint32: 'uint32'
  42213. };
  42214. const GPUTextureFormat = {
  42215. // 8-bit formats
  42216. R8Unorm: 'r8unorm',
  42217. R8Snorm: 'r8snorm',
  42218. R8Uint: 'r8uint',
  42219. R8Sint: 'r8sint',
  42220. // 16-bit formats
  42221. R16Uint: 'r16uint',
  42222. R16Sint: 'r16sint',
  42223. R16Float: 'r16float',
  42224. RG8Unorm: 'rg8unorm',
  42225. RG8Snorm: 'rg8snorm',
  42226. RG8Uint: 'rg8uint',
  42227. RG8Sint: 'rg8sint',
  42228. // 32-bit formats
  42229. R32Uint: 'r32uint',
  42230. R32Sint: 'r32sint',
  42231. R32Float: 'r32float',
  42232. RG16Uint: 'rg16uint',
  42233. RG16Sint: 'rg16sint',
  42234. RG16Float: 'rg16float',
  42235. RGBA8Unorm: 'rgba8unorm',
  42236. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  42237. RGBA8Snorm: 'rgba8snorm',
  42238. RGBA8Uint: 'rgba8uint',
  42239. RGBA8Sint: 'rgba8sint',
  42240. BGRA8Unorm: 'bgra8unorm',
  42241. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  42242. // Packed 32-bit formats
  42243. RGB9E5UFloat: 'rgb9e5ufloat',
  42244. RGB10A2Unorm: 'rgb10a2unorm',
  42245. RG11B10uFloat: 'rgb10a2unorm',
  42246. // 64-bit formats
  42247. RG32Uint: 'rg32uint',
  42248. RG32Sint: 'rg32sint',
  42249. RG32Float: 'rg32float',
  42250. RGBA16Uint: 'rgba16uint',
  42251. RGBA16Sint: 'rgba16sint',
  42252. RGBA16Float: 'rgba16float',
  42253. // 128-bit formats
  42254. RGBA32Uint: 'rgba32uint',
  42255. RGBA32Sint: 'rgba32sint',
  42256. RGBA32Float: 'rgba32float',
  42257. // Depth and stencil formats
  42258. Stencil8: 'stencil8',
  42259. Depth16Unorm: 'depth16unorm',
  42260. Depth24Plus: 'depth24plus',
  42261. Depth24PlusStencil8: 'depth24plus-stencil8',
  42262. Depth32Float: 'depth32float',
  42263. // 'depth32float-stencil8' extension
  42264. Depth32FloatStencil8: 'depth32float-stencil8',
  42265. // BC compressed formats usable if 'texture-compression-bc' is both
  42266. // supported by the device/user agent and enabled in requestDevice.
  42267. BC1RGBAUnorm: 'bc1-rgba-unorm',
  42268. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  42269. BC2RGBAUnorm: 'bc2-rgba-unorm',
  42270. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  42271. BC3RGBAUnorm: 'bc3-rgba-unorm',
  42272. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  42273. BC4RUnorm: 'bc4-r-unorm',
  42274. BC4RSnorm: 'bc4-r-snorm',
  42275. BC5RGUnorm: 'bc5-rg-unorm',
  42276. BC5RGSnorm: 'bc5-rg-snorm',
  42277. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  42278. BC6HRGBFloat: 'bc6h-rgb-float',
  42279. BC7RGBAUnorm: 'bc7-rgba-unorm',
  42280. BC7RGBAUnormSRGB: 'bc7-rgba-srgb',
  42281. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  42282. // supported by the device/user agent and enabled in requestDevice.
  42283. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  42284. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  42285. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  42286. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  42287. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  42288. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  42289. EACR11Unorm: 'eac-r11unorm',
  42290. EACR11Snorm: 'eac-r11snorm',
  42291. EACRG11Unorm: 'eac-rg11unorm',
  42292. EACRG11Snorm: 'eac-rg11snorm',
  42293. // ASTC compressed formats usable if 'texture-compression-astc' is both
  42294. // supported by the device/user agent and enabled in requestDevice.
  42295. ASTC4x4Unorm: 'astc-4x4-unorm',
  42296. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  42297. ASTC5x4Unorm: 'astc-5x4-unorm',
  42298. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  42299. ASTC5x5Unorm: 'astc-5x5-unorm',
  42300. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  42301. ASTC6x5Unorm: 'astc-6x5-unorm',
  42302. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  42303. ASTC6x6Unorm: 'astc-6x6-unorm',
  42304. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  42305. ASTC8x5Unorm: 'astc-8x5-unorm',
  42306. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  42307. ASTC8x6Unorm: 'astc-8x6-unorm',
  42308. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  42309. ASTC8x8Unorm: 'astc-8x8-unorm',
  42310. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  42311. ASTC10x5Unorm: 'astc-10x5-unorm',
  42312. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  42313. ASTC10x6Unorm: 'astc-10x6-unorm',
  42314. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  42315. ASTC10x8Unorm: 'astc-10x8-unorm',
  42316. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  42317. ASTC10x10Unorm: 'astc-10x10-unorm',
  42318. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  42319. ASTC12x10Unorm: 'astc-12x10-unorm',
  42320. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  42321. ASTC12x12Unorm: 'astc-12x12-unorm',
  42322. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  42323. };
  42324. const GPUAddressMode = {
  42325. ClampToEdge: 'clamp-to-edge',
  42326. Repeat: 'repeat',
  42327. MirrorRepeat: 'mirror-repeat'
  42328. };
  42329. const GPUFilterMode = {
  42330. Linear: 'linear',
  42331. Nearest: 'nearest'
  42332. };
  42333. const GPUBlendFactor = {
  42334. Zero: 'zero',
  42335. One: 'one',
  42336. Src: 'src',
  42337. OneMinusSrc: 'one-minus-src',
  42338. SrcAlpha: 'src-alpha',
  42339. OneMinusSrcAlpha: 'one-minus-src-alpha',
  42340. Dst: 'dst',
  42341. OneMinusDstColor: 'one-minus-dst',
  42342. DstAlpha: 'dst-alpha',
  42343. OneMinusDstAlpha: 'one-minus-dst-alpha',
  42344. SrcAlphaSaturated: 'src-alpha-saturated',
  42345. Constant: 'constant',
  42346. OneMinusConstant: 'one-minus-constant'
  42347. };
  42348. const GPUBlendOperation = {
  42349. Add: 'add',
  42350. Subtract: 'subtract',
  42351. ReverseSubtract: 'reverse-subtract',
  42352. Min: 'min',
  42353. Max: 'max'
  42354. };
  42355. const GPUColorWriteFlags = {
  42356. None: 0,
  42357. Red: 0x1,
  42358. Green: 0x2,
  42359. Blue: 0x4,
  42360. Alpha: 0x8,
  42361. All: 0xF
  42362. };
  42363. const GPUStencilOperation = {
  42364. Keep: 'keep',
  42365. Zero: 'zero',
  42366. Replace: 'replace',
  42367. Invert: 'invert',
  42368. IncrementClamp: 'increment-clamp',
  42369. DecrementClamp: 'decrement-clamp',
  42370. IncrementWrap: 'increment-wrap',
  42371. DecrementWrap: 'decrement-wrap'
  42372. };
  42373. const GPUBufferBindingType = {
  42374. Uniform: 'uniform',
  42375. Storage: 'storage',
  42376. ReadOnlyStorage: 'read-only-storage'
  42377. };
  42378. const GPUStorageTextureAccess = {
  42379. WriteOnly: 'write-only',
  42380. ReadOnly: 'read-only',
  42381. ReadWrite: 'read-write',
  42382. };
  42383. const GPUTextureSampleType = {
  42384. Float: 'float',
  42385. UnfilterableFloat: 'unfilterable-float',
  42386. Depth: 'depth',
  42387. SInt: 'sint',
  42388. UInt: 'uint'
  42389. };
  42390. const GPUTextureDimension = {
  42391. OneD: '1d',
  42392. TwoD: '2d',
  42393. ThreeD: '3d'
  42394. };
  42395. const GPUTextureViewDimension = {
  42396. OneD: '1d',
  42397. TwoD: '2d',
  42398. TwoDArray: '2d-array',
  42399. Cube: 'cube',
  42400. CubeArray: 'cube-array',
  42401. ThreeD: '3d'
  42402. };
  42403. const GPUTextureAspect = {
  42404. All: 'all',
  42405. StencilOnly: 'stencil-only',
  42406. DepthOnly: 'depth-only'
  42407. };
  42408. const GPUInputStepMode = {
  42409. Vertex: 'vertex',
  42410. Instance: 'instance'
  42411. };
  42412. const GPUFeatureName = {
  42413. DepthClipControl: 'depth-clip-control',
  42414. Depth32FloatStencil8: 'depth32float-stencil8',
  42415. TextureCompressionBC: 'texture-compression-bc',
  42416. TextureCompressionETC2: 'texture-compression-etc2',
  42417. TextureCompressionASTC: 'texture-compression-astc',
  42418. TimestampQuery: 'timestamp-query',
  42419. IndirectFirstInstance: 'indirect-first-instance',
  42420. ShaderF16: 'shader-f16',
  42421. RG11B10UFloat: 'rg11b10ufloat-renderable',
  42422. BGRA8UNormStorage: 'bgra8unorm-storage',
  42423. Float32Filterable: 'float32-filterable',
  42424. ClipDistances: 'clip-distances',
  42425. DualSourceBlending: 'dual-source-blending',
  42426. Subgroups: 'subgroups'
  42427. };
  42428. /**
  42429. * Represents a sampler binding type.
  42430. *
  42431. * @private
  42432. * @augments Binding
  42433. */
  42434. class Sampler extends Binding {
  42435. /**
  42436. * Constructs a new sampler.
  42437. *
  42438. * @param {String} name - The samplers's name.
  42439. * @param {Texture?} texture - The texture this binding is referring to.
  42440. */
  42441. constructor( name, texture ) {
  42442. super( name );
  42443. /**
  42444. * The texture the sampler is referring to.
  42445. *
  42446. * @type {Texture?}
  42447. */
  42448. this.texture = texture;
  42449. /**
  42450. * The binding's version.
  42451. *
  42452. * @type {Number}
  42453. */
  42454. this.version = texture ? texture.version : 0;
  42455. /**
  42456. * This flag can be used for type testing.
  42457. *
  42458. * @type {Boolean}
  42459. * @readonly
  42460. * @default true
  42461. */
  42462. this.isSampler = true;
  42463. }
  42464. }
  42465. /**
  42466. * A special form of sampler binding type.
  42467. * It's texture value is managed by a node object.
  42468. *
  42469. * @private
  42470. * @augments Sampler
  42471. */
  42472. class NodeSampler extends Sampler {
  42473. /**
  42474. * Constructs a new node-based sampler.
  42475. *
  42476. * @param {String} name - The samplers's name.
  42477. * @param {TextureNode} textureNode - The texture node.
  42478. * @param {UniformGroupNode} groupNode - The uniform group node.
  42479. */
  42480. constructor( name, textureNode, groupNode ) {
  42481. super( name, textureNode ? textureNode.value : null );
  42482. /**
  42483. * The texture node.
  42484. *
  42485. * @type {TextureNode}
  42486. */
  42487. this.textureNode = textureNode;
  42488. /**
  42489. * The uniform group node.
  42490. *
  42491. * @type {UniformGroupNode}
  42492. */
  42493. this.groupNode = groupNode;
  42494. }
  42495. /**
  42496. * Updates the texture value of this sampler.
  42497. */
  42498. update() {
  42499. this.texture = this.textureNode.value;
  42500. }
  42501. }
  42502. /**
  42503. * Represents a storage buffer binding type.
  42504. *
  42505. * @private
  42506. * @augments Buffer
  42507. */
  42508. class StorageBuffer extends Buffer {
  42509. /**
  42510. * Constructs a new uniform buffer.
  42511. *
  42512. * @param {String} name - The buffer's name.
  42513. * @param {BufferAttribute} attribute - The buffer attribute.
  42514. */
  42515. constructor( name, attribute ) {
  42516. super( name, attribute ? attribute.array : null );
  42517. /**
  42518. * This flag can be used for type testing.
  42519. *
  42520. * @type {BufferAttribute}
  42521. */
  42522. this.attribute = attribute;
  42523. /**
  42524. * This flag can be used for type testing.
  42525. *
  42526. * @type {Boolean}
  42527. * @readonly
  42528. * @default true
  42529. */
  42530. this.isStorageBuffer = true;
  42531. }
  42532. }
  42533. let _id = 0;
  42534. /**
  42535. * A special form of storage buffer binding type.
  42536. * It's buffer value is managed by a node object.
  42537. *
  42538. * @private
  42539. * @augments StorageBuffer
  42540. */
  42541. class NodeStorageBuffer extends StorageBuffer {
  42542. /**
  42543. * Constructs a new node-based storage buffer.
  42544. *
  42545. * @param {StorageBufferNode} nodeUniform - The storage buffer node.
  42546. * @param {UniformGroupNode} groupNode - The uniform group node.
  42547. */
  42548. constructor( nodeUniform, groupNode ) {
  42549. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  42550. /**
  42551. * The node uniform.
  42552. *
  42553. * @type {StorageBufferNode}
  42554. */
  42555. this.nodeUniform = nodeUniform;
  42556. /**
  42557. * The access type.
  42558. *
  42559. * @type {String}
  42560. */
  42561. this.access = nodeUniform ? nodeUniform.access : NodeAccess.READ_WRITE;
  42562. /**
  42563. * The uniform group node.
  42564. *
  42565. * @type {UniformGroupNode}
  42566. */
  42567. this.groupNode = groupNode;
  42568. }
  42569. /**
  42570. * The storage buffer.
  42571. *
  42572. * @type {BufferAttribute}
  42573. */
  42574. get buffer() {
  42575. return this.nodeUniform.value;
  42576. }
  42577. }
  42578. /**
  42579. * A WebGPU backend utility module used by {@link WebGPUTextureUtils}.
  42580. *
  42581. * @private
  42582. */
  42583. class WebGPUTexturePassUtils extends DataMap {
  42584. /**
  42585. * Constructs a new utility object.
  42586. *
  42587. * @param {GPUDevice} device - The WebGPU device.
  42588. */
  42589. constructor( device ) {
  42590. super();
  42591. /**
  42592. * The WebGPU device.
  42593. *
  42594. * @type {GPUDevice}
  42595. */
  42596. this.device = device;
  42597. const mipmapVertexSource = `
  42598. struct VarysStruct {
  42599. @builtin( position ) Position: vec4<f32>,
  42600. @location( 0 ) vTex : vec2<f32>
  42601. };
  42602. @vertex
  42603. fn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {
  42604. var Varys : VarysStruct;
  42605. var pos = array< vec2<f32>, 4 >(
  42606. vec2<f32>( -1.0, 1.0 ),
  42607. vec2<f32>( 1.0, 1.0 ),
  42608. vec2<f32>( -1.0, -1.0 ),
  42609. vec2<f32>( 1.0, -1.0 )
  42610. );
  42611. var tex = array< vec2<f32>, 4 >(
  42612. vec2<f32>( 0.0, 0.0 ),
  42613. vec2<f32>( 1.0, 0.0 ),
  42614. vec2<f32>( 0.0, 1.0 ),
  42615. vec2<f32>( 1.0, 1.0 )
  42616. );
  42617. Varys.vTex = tex[ vertexIndex ];
  42618. Varys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );
  42619. return Varys;
  42620. }
  42621. `;
  42622. const mipmapFragmentSource = `
  42623. @group( 0 ) @binding( 0 )
  42624. var imgSampler : sampler;
  42625. @group( 0 ) @binding( 1 )
  42626. var img : texture_2d<f32>;
  42627. @fragment
  42628. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  42629. return textureSample( img, imgSampler, vTex );
  42630. }
  42631. `;
  42632. const flipYFragmentSource = `
  42633. @group( 0 ) @binding( 0 )
  42634. var imgSampler : sampler;
  42635. @group( 0 ) @binding( 1 )
  42636. var img : texture_2d<f32>;
  42637. @fragment
  42638. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  42639. return textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );
  42640. }
  42641. `;
  42642. /**
  42643. * The mipmap GPU sampler.
  42644. *
  42645. * @type {GPUSampler}
  42646. */
  42647. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  42648. /**
  42649. * The flipY GPU sampler.
  42650. *
  42651. * @type {GPUSampler}
  42652. */
  42653. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  42654. /**
  42655. * A cache for GPU render pipelines used for copy/transfer passes.
  42656. * Every texture format requires a unique pipeline.
  42657. *
  42658. * @type {Object<String,GPURenderPipeline>}
  42659. */
  42660. this.transferPipelines = {};
  42661. /**
  42662. * A cache for GPU render pipelines used for flipY passes.
  42663. * Every texture format requires a unique pipeline.
  42664. *
  42665. * @type {Object<String,GPURenderPipeline>}
  42666. */
  42667. this.flipYPipelines = {};
  42668. /**
  42669. * The mipmap vertex shader module.
  42670. *
  42671. * @type {GPUShaderModule}
  42672. */
  42673. this.mipmapVertexShaderModule = device.createShaderModule( {
  42674. label: 'mipmapVertex',
  42675. code: mipmapVertexSource
  42676. } );
  42677. /**
  42678. * The mipmap fragment shader module.
  42679. *
  42680. * @type {GPUShaderModule}
  42681. */
  42682. this.mipmapFragmentShaderModule = device.createShaderModule( {
  42683. label: 'mipmapFragment',
  42684. code: mipmapFragmentSource
  42685. } );
  42686. /**
  42687. * The flipY fragment shader module.
  42688. *
  42689. * @type {GPUShaderModule}
  42690. */
  42691. this.flipYFragmentShaderModule = device.createShaderModule( {
  42692. label: 'flipYFragment',
  42693. code: flipYFragmentSource
  42694. } );
  42695. }
  42696. /**
  42697. * Returns a render pipeline for the internal copy render pass. The pass
  42698. * requires a unique render pipeline for each texture format.
  42699. *
  42700. * @param {String} format - The GPU texture format
  42701. * @return {GPURenderPipeline} The GPU render pipeline.
  42702. */
  42703. getTransferPipeline( format ) {
  42704. let pipeline = this.transferPipelines[ format ];
  42705. if ( pipeline === undefined ) {
  42706. pipeline = this.device.createRenderPipeline( {
  42707. label: `mipmap-${ format }`,
  42708. vertex: {
  42709. module: this.mipmapVertexShaderModule,
  42710. entryPoint: 'main'
  42711. },
  42712. fragment: {
  42713. module: this.mipmapFragmentShaderModule,
  42714. entryPoint: 'main',
  42715. targets: [ { format } ]
  42716. },
  42717. primitive: {
  42718. topology: GPUPrimitiveTopology.TriangleStrip,
  42719. stripIndexFormat: GPUIndexFormat.Uint32
  42720. },
  42721. layout: 'auto'
  42722. } );
  42723. this.transferPipelines[ format ] = pipeline;
  42724. }
  42725. return pipeline;
  42726. }
  42727. /**
  42728. * Returns a render pipeline for the flipY render pass. The pass
  42729. * requires a unique render pipeline for each texture format.
  42730. *
  42731. * @param {String} format - The GPU texture format
  42732. * @return {GPURenderPipeline} The GPU render pipeline.
  42733. */
  42734. getFlipYPipeline( format ) {
  42735. let pipeline = this.flipYPipelines[ format ];
  42736. if ( pipeline === undefined ) {
  42737. pipeline = this.device.createRenderPipeline( {
  42738. label: `flipY-${ format }`,
  42739. vertex: {
  42740. module: this.mipmapVertexShaderModule,
  42741. entryPoint: 'main'
  42742. },
  42743. fragment: {
  42744. module: this.flipYFragmentShaderModule,
  42745. entryPoint: 'main',
  42746. targets: [ { format } ]
  42747. },
  42748. primitive: {
  42749. topology: GPUPrimitiveTopology.TriangleStrip,
  42750. stripIndexFormat: GPUIndexFormat.Uint32
  42751. },
  42752. layout: 'auto'
  42753. } );
  42754. this.flipYPipelines[ format ] = pipeline;
  42755. }
  42756. return pipeline;
  42757. }
  42758. /**
  42759. * Flip the contents of the given GPU texture along its vertical axis.
  42760. *
  42761. * @param {GPUTexture} textureGPU - The GPU texture object.
  42762. * @param {Object} textureGPUDescriptor - The texture descriptor.
  42763. * @param {Number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  42764. */
  42765. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  42766. const format = textureGPUDescriptor.format;
  42767. const { width, height } = textureGPUDescriptor.size;
  42768. const transferPipeline = this.getTransferPipeline( format );
  42769. const flipYPipeline = this.getFlipYPipeline( format );
  42770. const tempTexture = this.device.createTexture( {
  42771. size: { width, height, depthOrArrayLayers: 1 },
  42772. format,
  42773. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
  42774. } );
  42775. const srcView = textureGPU.createView( {
  42776. baseMipLevel: 0,
  42777. mipLevelCount: 1,
  42778. dimension: GPUTextureViewDimension.TwoD,
  42779. baseArrayLayer
  42780. } );
  42781. const dstView = tempTexture.createView( {
  42782. baseMipLevel: 0,
  42783. mipLevelCount: 1,
  42784. dimension: GPUTextureViewDimension.TwoD,
  42785. baseArrayLayer: 0
  42786. } );
  42787. const commandEncoder = this.device.createCommandEncoder( {} );
  42788. const pass = ( pipeline, sourceView, destinationView ) => {
  42789. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  42790. const bindGroup = this.device.createBindGroup( {
  42791. layout: bindGroupLayout,
  42792. entries: [ {
  42793. binding: 0,
  42794. resource: this.flipYSampler
  42795. }, {
  42796. binding: 1,
  42797. resource: sourceView
  42798. } ]
  42799. } );
  42800. const passEncoder = commandEncoder.beginRenderPass( {
  42801. colorAttachments: [ {
  42802. view: destinationView,
  42803. loadOp: GPULoadOp.Clear,
  42804. storeOp: GPUStoreOp.Store,
  42805. clearValue: [ 0, 0, 0, 0 ]
  42806. } ]
  42807. } );
  42808. passEncoder.setPipeline( pipeline );
  42809. passEncoder.setBindGroup( 0, bindGroup );
  42810. passEncoder.draw( 4, 1, 0, 0 );
  42811. passEncoder.end();
  42812. };
  42813. pass( transferPipeline, srcView, dstView );
  42814. pass( flipYPipeline, dstView, srcView );
  42815. this.device.queue.submit( [ commandEncoder.finish() ] );
  42816. tempTexture.destroy();
  42817. }
  42818. /**
  42819. * Generates mipmaps for the given GPU texture.
  42820. *
  42821. * @param {GPUTexture} textureGPU - The GPU texture object.
  42822. * @param {Object} textureGPUDescriptor - The texture descriptor.
  42823. * @param {Number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  42824. */
  42825. generateMipmaps( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  42826. const textureData = this.get( textureGPU );
  42827. if ( textureData.useCount === undefined ) {
  42828. textureData.useCount = 0;
  42829. textureData.layers = [];
  42830. }
  42831. const passes = textureData.layers[ baseArrayLayer ] || this._mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer );
  42832. const commandEncoder = this.device.createCommandEncoder( {} );
  42833. this._mipmapRunBundles( commandEncoder, passes );
  42834. this.device.queue.submit( [ commandEncoder.finish() ] );
  42835. if ( textureData.useCount !== 0 ) textureData.layers[ baseArrayLayer ] = passes;
  42836. textureData.useCount ++;
  42837. }
  42838. /**
  42839. * Since multiple copy render passes are required to generate mipmaps, the passes
  42840. * are managed as render bundles to improve performance.
  42841. *
  42842. * @param {GPUTexture} textureGPU - The GPU texture object.
  42843. * @param {Object} textureGPUDescriptor - The texture descriptor.
  42844. * @param {Number} baseArrayLayer - The index of the first array layer accessible to the texture view.
  42845. * @return {Array} An array of render bundles.
  42846. */
  42847. _mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer ) {
  42848. const pipeline = this.getTransferPipeline( textureGPUDescriptor.format );
  42849. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  42850. let srcView = textureGPU.createView( {
  42851. baseMipLevel: 0,
  42852. mipLevelCount: 1,
  42853. dimension: GPUTextureViewDimension.TwoD,
  42854. baseArrayLayer
  42855. } );
  42856. const passes = [];
  42857. for ( let i = 1; i < textureGPUDescriptor.mipLevelCount; i ++ ) {
  42858. const bindGroup = this.device.createBindGroup( {
  42859. layout: bindGroupLayout,
  42860. entries: [ {
  42861. binding: 0,
  42862. resource: this.mipmapSampler
  42863. }, {
  42864. binding: 1,
  42865. resource: srcView
  42866. } ]
  42867. } );
  42868. const dstView = textureGPU.createView( {
  42869. baseMipLevel: i,
  42870. mipLevelCount: 1,
  42871. dimension: GPUTextureViewDimension.TwoD,
  42872. baseArrayLayer
  42873. } );
  42874. const passDescriptor = {
  42875. colorAttachments: [ {
  42876. view: dstView,
  42877. loadOp: GPULoadOp.Clear,
  42878. storeOp: GPUStoreOp.Store,
  42879. clearValue: [ 0, 0, 0, 0 ]
  42880. } ]
  42881. };
  42882. const passEncoder = this.device.createRenderBundleEncoder( {
  42883. colorFormats: [ textureGPUDescriptor.format ]
  42884. } );
  42885. passEncoder.setPipeline( pipeline );
  42886. passEncoder.setBindGroup( 0, bindGroup );
  42887. passEncoder.draw( 4, 1, 0, 0 );
  42888. passes.push( {
  42889. renderBundles: [ passEncoder.finish() ],
  42890. passDescriptor
  42891. } );
  42892. srcView = dstView;
  42893. }
  42894. return passes;
  42895. }
  42896. /**
  42897. * Executes the render bundles.
  42898. *
  42899. * @param {GPUCommandEncoder} commandEncoder - The GPU command encoder.
  42900. * @param {Array} passes - An array of render bundles.
  42901. */
  42902. _mipmapRunBundles( commandEncoder, passes ) {
  42903. const levels = passes.length;
  42904. for ( let i = 0; i < levels; i ++ ) {
  42905. const pass = passes[ i ];
  42906. const passEncoder = commandEncoder.beginRenderPass( pass.passDescriptor );
  42907. passEncoder.executeBundles( pass.renderBundles );
  42908. passEncoder.end();
  42909. }
  42910. }
  42911. }
  42912. const _compareToWebGPU = {
  42913. [ NeverCompare ]: 'never',
  42914. [ LessCompare ]: 'less',
  42915. [ EqualCompare ]: 'equal',
  42916. [ LessEqualCompare ]: 'less-equal',
  42917. [ GreaterCompare ]: 'greater',
  42918. [ GreaterEqualCompare ]: 'greater-equal',
  42919. [ AlwaysCompare ]: 'always',
  42920. [ NotEqualCompare ]: 'not-equal'
  42921. };
  42922. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  42923. /**
  42924. * A WebGPU backend utility module for managing textures.
  42925. *
  42926. * @private
  42927. */
  42928. class WebGPUTextureUtils {
  42929. /**
  42930. * Constructs a new utility object.
  42931. *
  42932. * @param {WebGPUBackend} backend - The WebGPU backend.
  42933. */
  42934. constructor( backend ) {
  42935. /**
  42936. * A reference to the WebGPU backend.
  42937. *
  42938. * @type {WebGPUBackend}
  42939. */
  42940. this.backend = backend;
  42941. /**
  42942. * A reference to the pass utils.
  42943. *
  42944. * @type {WebGPUTexturePassUtils?}
  42945. * @default null
  42946. */
  42947. this._passUtils = null;
  42948. /**
  42949. * A dictionary for managing default textures. The key
  42950. * is the texture format, the value the texture object.
  42951. *
  42952. * @type {Object<String,Texture>}
  42953. */
  42954. this.defaultTexture = {};
  42955. /**
  42956. * A dictionary for managing default cube textures. The key
  42957. * is the texture format, the value the texture object.
  42958. *
  42959. * @type {Object<String,CubeTexture>}
  42960. */
  42961. this.defaultCubeTexture = {};
  42962. /**
  42963. * A default video frame.
  42964. *
  42965. * @type {VideoFrame?}
  42966. * @default null
  42967. */
  42968. this.defaultVideoFrame = null;
  42969. /**
  42970. * Represents the color attachment of the default framebuffer.
  42971. *
  42972. * @type {GPUTexture?}
  42973. * @default null
  42974. */
  42975. this.colorBuffer = null;
  42976. /**
  42977. * Represents the depth attachment of the default framebuffer.
  42978. *
  42979. * @type {DepthTexture}
  42980. */
  42981. this.depthTexture = new DepthTexture();
  42982. this.depthTexture.name = 'depthBuffer';
  42983. }
  42984. /**
  42985. * Creates a GPU sampler for the given texture.
  42986. *
  42987. * @param {Texture} texture - The texture to create the sampler for.
  42988. */
  42989. createSampler( texture ) {
  42990. const backend = this.backend;
  42991. const device = backend.device;
  42992. const textureGPU = backend.get( texture );
  42993. const samplerDescriptorGPU = {
  42994. addressModeU: this._convertAddressMode( texture.wrapS ),
  42995. addressModeV: this._convertAddressMode( texture.wrapT ),
  42996. addressModeW: this._convertAddressMode( texture.wrapR ),
  42997. magFilter: this._convertFilterMode( texture.magFilter ),
  42998. minFilter: this._convertFilterMode( texture.minFilter ),
  42999. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  43000. maxAnisotropy: 1
  43001. };
  43002. // anisotropy can only be used when all filter modes are set to linear.
  43003. if ( samplerDescriptorGPU.magFilter === GPUFilterMode.Linear && samplerDescriptorGPU.minFilter === GPUFilterMode.Linear && samplerDescriptorGPU.mipmapFilter === GPUFilterMode.Linear ) {
  43004. samplerDescriptorGPU.maxAnisotropy = texture.anisotropy;
  43005. }
  43006. if ( texture.isDepthTexture && texture.compareFunction !== null ) {
  43007. samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ];
  43008. }
  43009. textureGPU.sampler = device.createSampler( samplerDescriptorGPU );
  43010. }
  43011. /**
  43012. * Creates a default texture for the given texture that can be used
  43013. * as a placeholder until the actual texture is ready for usage.
  43014. *
  43015. * @param {Texture} texture - The texture to create a default texture for.
  43016. */
  43017. createDefaultTexture( texture ) {
  43018. let textureGPU;
  43019. const format = getFormat( texture );
  43020. if ( texture.isCubeTexture ) {
  43021. textureGPU = this._getDefaultCubeTextureGPU( format );
  43022. } else if ( texture.isVideoTexture ) {
  43023. this.backend.get( texture ).externalTexture = this._getDefaultVideoFrame();
  43024. } else {
  43025. textureGPU = this._getDefaultTextureGPU( format );
  43026. }
  43027. this.backend.get( texture ).texture = textureGPU;
  43028. }
  43029. /**
  43030. * Defines a texture on the GPU for the given texture object.
  43031. *
  43032. * @param {Texture} texture - The texture.
  43033. * @param {Object} [options={}] - Optional configuration parameter.
  43034. * @return {undefined}
  43035. */
  43036. createTexture( texture, options = {} ) {
  43037. const backend = this.backend;
  43038. const textureData = backend.get( texture );
  43039. if ( textureData.initialized ) {
  43040. throw new Error( 'WebGPUTextureUtils: Texture already initialized.' );
  43041. }
  43042. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  43043. if ( options.levels === undefined ) options.levels = 1;
  43044. if ( options.depth === undefined ) options.depth = 1;
  43045. const { width, height, depth, levels } = options;
  43046. if ( texture.isFramebufferTexture ) {
  43047. if ( options.renderTarget ) {
  43048. options.format = this.backend.utils.getCurrentColorFormat( options.renderTarget );
  43049. } else {
  43050. options.format = this.backend.utils.getPreferredCanvasFormat();
  43051. }
  43052. }
  43053. const dimension = this._getDimension( texture );
  43054. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  43055. textureData.format = format;
  43056. const { samples, primarySamples, isMSAA } = backend.utils.getTextureSampleData( texture );
  43057. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  43058. if ( texture.isStorageTexture === true ) {
  43059. usage |= GPUTextureUsage.STORAGE_BINDING;
  43060. }
  43061. if ( texture.isCompressedTexture !== true && texture.isCompressedArrayTexture !== true ) {
  43062. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  43063. }
  43064. const textureDescriptorGPU = {
  43065. label: texture.name,
  43066. size: {
  43067. width: width,
  43068. height: height,
  43069. depthOrArrayLayers: depth,
  43070. },
  43071. mipLevelCount: levels,
  43072. sampleCount: primarySamples,
  43073. dimension: dimension,
  43074. format: format,
  43075. usage: usage
  43076. };
  43077. // texture creation
  43078. if ( texture.isVideoTexture ) {
  43079. const video = texture.source.data;
  43080. const videoFrame = new VideoFrame( video );
  43081. textureDescriptorGPU.size.width = videoFrame.displayWidth;
  43082. textureDescriptorGPU.size.height = videoFrame.displayHeight;
  43083. videoFrame.close();
  43084. textureData.externalTexture = video;
  43085. } else {
  43086. if ( format === undefined ) {
  43087. console.warn( 'WebGPURenderer: Texture format not supported.' );
  43088. return this.createDefaultTexture( texture );
  43089. }
  43090. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  43091. }
  43092. if ( isMSAA ) {
  43093. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  43094. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  43095. msaaTextureDescriptorGPU.sampleCount = samples;
  43096. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  43097. }
  43098. textureData.initialized = true;
  43099. textureData.textureDescriptorGPU = textureDescriptorGPU;
  43100. }
  43101. /**
  43102. * Destroys the GPU data for the given texture object.
  43103. *
  43104. * @param {Texture} texture - The texture.
  43105. */
  43106. destroyTexture( texture ) {
  43107. const backend = this.backend;
  43108. const textureData = backend.get( texture );
  43109. if ( textureData.texture !== undefined ) textureData.texture.destroy();
  43110. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  43111. backend.delete( texture );
  43112. }
  43113. /**
  43114. * Destroys the GPU sampler for the given texture.
  43115. *
  43116. * @param {Texture} texture - The texture to destroy the sampler for.
  43117. */
  43118. destroySampler( texture ) {
  43119. const backend = this.backend;
  43120. const textureData = backend.get( texture );
  43121. delete textureData.sampler;
  43122. }
  43123. /**
  43124. * Generates mipmaps for the given texture.
  43125. *
  43126. * @param {Texture} texture - The texture.
  43127. */
  43128. generateMipmaps( texture ) {
  43129. const textureData = this.backend.get( texture );
  43130. if ( texture.isCubeTexture ) {
  43131. for ( let i = 0; i < 6; i ++ ) {
  43132. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  43133. }
  43134. } else {
  43135. const depth = texture.image.depth || 1;
  43136. for ( let i = 0; i < depth; i ++ ) {
  43137. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  43138. }
  43139. }
  43140. }
  43141. /**
  43142. * Returns the color buffer representing the color
  43143. * attachment of the default framebuffer.
  43144. *
  43145. * @return {GPUTexture} The color buffer.
  43146. */
  43147. getColorBuffer() {
  43148. if ( this.colorBuffer ) this.colorBuffer.destroy();
  43149. const backend = this.backend;
  43150. const { width, height } = backend.getDrawingBufferSize();
  43151. this.colorBuffer = backend.device.createTexture( {
  43152. label: 'colorBuffer',
  43153. size: {
  43154. width: width,
  43155. height: height,
  43156. depthOrArrayLayers: 1
  43157. },
  43158. sampleCount: backend.utils.getSampleCount( backend.renderer.samples ),
  43159. format: backend.utils.getPreferredCanvasFormat(),
  43160. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  43161. } );
  43162. return this.colorBuffer;
  43163. }
  43164. /**
  43165. * Returns the depth buffer representing the depth
  43166. * attachment of the default framebuffer.
  43167. *
  43168. * @param {Boolean} [depth=true] - Whether depth is enabled or not.
  43169. * @param {Boolean} [stencil=false] - Whether stencil is enabled or not.
  43170. * @return {GPUTexture} The depth buffer.
  43171. */
  43172. getDepthBuffer( depth = true, stencil = false ) {
  43173. const backend = this.backend;
  43174. const { width, height } = backend.getDrawingBufferSize();
  43175. const depthTexture = this.depthTexture;
  43176. const depthTextureGPU = backend.get( depthTexture ).texture;
  43177. let format, type;
  43178. if ( stencil ) {
  43179. format = DepthStencilFormat;
  43180. type = UnsignedInt248Type;
  43181. } else if ( depth ) {
  43182. format = DepthFormat;
  43183. type = UnsignedIntType;
  43184. }
  43185. if ( depthTextureGPU !== undefined ) {
  43186. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type ) {
  43187. return depthTextureGPU;
  43188. }
  43189. this.destroyTexture( depthTexture );
  43190. }
  43191. depthTexture.name = 'depthBuffer';
  43192. depthTexture.format = format;
  43193. depthTexture.type = type;
  43194. depthTexture.image.width = width;
  43195. depthTexture.image.height = height;
  43196. this.createTexture( depthTexture, { width, height } );
  43197. return backend.get( depthTexture ).texture;
  43198. }
  43199. /**
  43200. * Uploads the updated texture data to the GPU.
  43201. *
  43202. * @param {Texture} texture - The texture.
  43203. * @param {Object} [options={}] - Optional configuration parameter.
  43204. */
  43205. updateTexture( texture, options ) {
  43206. const textureData = this.backend.get( texture );
  43207. const { textureDescriptorGPU } = textureData;
  43208. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  43209. return;
  43210. // transfer texture data
  43211. if ( texture.isDataTexture ) {
  43212. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  43213. } else if ( texture.isDataArrayTexture || texture.isData3DTexture ) {
  43214. for ( let i = 0; i < options.image.depth; i ++ ) {
  43215. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  43216. }
  43217. } else if ( texture.isCompressedTexture || texture.isCompressedArrayTexture ) {
  43218. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  43219. } else if ( texture.isCubeTexture ) {
  43220. this._copyCubeMapToTexture( options.images, textureData.texture, textureDescriptorGPU, texture.flipY );
  43221. } else if ( texture.isVideoTexture ) {
  43222. const video = texture.source.data;
  43223. textureData.externalTexture = video;
  43224. } else {
  43225. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  43226. }
  43227. //
  43228. textureData.version = texture.version;
  43229. if ( texture.onUpdate ) texture.onUpdate( texture );
  43230. }
  43231. /**
  43232. * Returns texture data as a typed array.
  43233. *
  43234. * @async
  43235. * @param {Texture} texture - The texture to copy.
  43236. * @param {Number} x - The x coordinate of the copy origin.
  43237. * @param {Number} y - The y coordinate of the copy origin.
  43238. * @param {Number} width - The width of the copy.
  43239. * @param {Number} height - The height of the copy.
  43240. * @param {Number} faceIndex - The face index.
  43241. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  43242. */
  43243. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  43244. const device = this.backend.device;
  43245. const textureData = this.backend.get( texture );
  43246. const textureGPU = textureData.texture;
  43247. const format = textureData.textureDescriptorGPU.format;
  43248. const bytesPerTexel = this._getBytesPerTexel( format );
  43249. let bytesPerRow = width * bytesPerTexel;
  43250. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  43251. const readBuffer = device.createBuffer(
  43252. {
  43253. size: width * height * bytesPerTexel,
  43254. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  43255. }
  43256. );
  43257. const encoder = device.createCommandEncoder();
  43258. encoder.copyTextureToBuffer(
  43259. {
  43260. texture: textureGPU,
  43261. origin: { x, y, z: faceIndex },
  43262. },
  43263. {
  43264. buffer: readBuffer,
  43265. bytesPerRow: bytesPerRow
  43266. },
  43267. {
  43268. width: width,
  43269. height: height
  43270. }
  43271. );
  43272. const typedArrayType = this._getTypedArrayType( format );
  43273. device.queue.submit( [ encoder.finish() ] );
  43274. await readBuffer.mapAsync( GPUMapMode.READ );
  43275. const buffer = readBuffer.getMappedRange();
  43276. return new typedArrayType( buffer );
  43277. }
  43278. /**
  43279. * Returns `true` if the given texture is an environment map.
  43280. *
  43281. * @private
  43282. * @param {Texture} texture - The texture.
  43283. * @return {Boolean} Whether the given texture is an environment map or not.
  43284. */
  43285. _isEnvironmentTexture( texture ) {
  43286. const mapping = texture.mapping;
  43287. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  43288. }
  43289. /**
  43290. * Returns the default GPU texture for the given format.
  43291. *
  43292. * @private
  43293. * @param {String} format - The GPU format.
  43294. * @return {GPUTexture} The GPU texture.
  43295. */
  43296. _getDefaultTextureGPU( format ) {
  43297. let defaultTexture = this.defaultTexture[ format ];
  43298. if ( defaultTexture === undefined ) {
  43299. const texture = new Texture();
  43300. texture.minFilter = NearestFilter;
  43301. texture.magFilter = NearestFilter;
  43302. this.createTexture( texture, { width: 1, height: 1, format } );
  43303. this.defaultTexture[ format ] = defaultTexture = texture;
  43304. }
  43305. return this.backend.get( defaultTexture ).texture;
  43306. }
  43307. /**
  43308. * Returns the default GPU cube texture for the given format.
  43309. *
  43310. * @private
  43311. * @param {String} format - The GPU format.
  43312. * @return {GPUTexture} The GPU texture.
  43313. */
  43314. _getDefaultCubeTextureGPU( format ) {
  43315. let defaultCubeTexture = this.defaultTexture[ format ];
  43316. if ( defaultCubeTexture === undefined ) {
  43317. const texture = new CubeTexture();
  43318. texture.minFilter = NearestFilter;
  43319. texture.magFilter = NearestFilter;
  43320. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  43321. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  43322. }
  43323. return this.backend.get( defaultCubeTexture ).texture;
  43324. }
  43325. /**
  43326. * Returns the default video frame used as default data in context of video textures.
  43327. *
  43328. * @private
  43329. * @return {VideoFrame} The video frame.
  43330. */
  43331. _getDefaultVideoFrame() {
  43332. let defaultVideoFrame = this.defaultVideoFrame;
  43333. if ( defaultVideoFrame === null ) {
  43334. const init = {
  43335. timestamp: 0,
  43336. codedWidth: 1,
  43337. codedHeight: 1,
  43338. format: 'RGBA',
  43339. };
  43340. this.defaultVideoFrame = defaultVideoFrame = new VideoFrame( new Uint8Array( [ 0, 0, 0, 0xff ] ), init );
  43341. }
  43342. return defaultVideoFrame;
  43343. }
  43344. /**
  43345. * Uploads cube texture image data to the GPU memory.
  43346. *
  43347. * @private
  43348. * @param {Array} images - The cube image data.
  43349. * @param {GPUTexture} textureGPU - The GPU texture.
  43350. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  43351. * @param {Boolean} flipY - Whether to flip texture data along their vertical axis or not.
  43352. */
  43353. _copyCubeMapToTexture( images, textureGPU, textureDescriptorGPU, flipY ) {
  43354. for ( let i = 0; i < 6; i ++ ) {
  43355. const image = images[ i ];
  43356. const flipIndex = flipY === true ? _flipMap[ i ] : i;
  43357. if ( image.isDataTexture ) {
  43358. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  43359. } else {
  43360. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  43361. }
  43362. }
  43363. }
  43364. /**
  43365. * Uploads texture image data to the GPU memory.
  43366. *
  43367. * @private
  43368. * @param {HTMLImageElement|ImageBitmap|HTMLCanvasElement} image - The image data.
  43369. * @param {GPUTexture} textureGPU - The GPU texture.
  43370. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  43371. * @param {Number} originDepth - The origin depth.
  43372. * @param {Boolean} flipY - Whether to flip texture data along their vertical axis or not.
  43373. */
  43374. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY ) {
  43375. const device = this.backend.device;
  43376. device.queue.copyExternalImageToTexture(
  43377. {
  43378. source: image,
  43379. flipY: flipY
  43380. }, {
  43381. texture: textureGPU,
  43382. mipLevel: 0,
  43383. origin: { x: 0, y: 0, z: originDepth }
  43384. }, {
  43385. width: image.width,
  43386. height: image.height,
  43387. depthOrArrayLayers: 1
  43388. }
  43389. );
  43390. }
  43391. /**
  43392. * Returns the pass utils singleton.
  43393. *
  43394. * @private
  43395. * @return {WebGPUTexturePassUtils} The utils instance.
  43396. */
  43397. _getPassUtils() {
  43398. let passUtils = this._passUtils;
  43399. if ( passUtils === null ) {
  43400. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  43401. }
  43402. return passUtils;
  43403. }
  43404. /**
  43405. * Generates mipmaps for the given GPU texture.
  43406. *
  43407. * @private
  43408. * @param {GPUTexture} textureGPU - The GPU texture object.
  43409. * @param {Object} textureDescriptorGPU - The texture descriptor.
  43410. * @param {Number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  43411. */
  43412. _generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer = 0 ) {
  43413. this._getPassUtils().generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer );
  43414. }
  43415. /**
  43416. * Flip the contents of the given GPU texture along its vertical axis.
  43417. *
  43418. * @private
  43419. * @param {GPUTexture} textureGPU - The GPU texture object.
  43420. * @param {Object} textureDescriptorGPU - The texture descriptor.
  43421. * @param {Number} [originDepth=0] - The origin depth.
  43422. */
  43423. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  43424. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  43425. }
  43426. /**
  43427. * Uploads texture buffer data to the GPU memory.
  43428. *
  43429. * @private
  43430. * @param {Object} image - An object defining the image buffer data.
  43431. * @param {GPUTexture} textureGPU - The GPU texture.
  43432. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  43433. * @param {Number} originDepth - The origin depth.
  43434. * @param {Boolean} flipY - Whether to flip texture data along their vertical axis or not.
  43435. * @param {Number} [depth=0] - TODO.
  43436. */
  43437. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0 ) {
  43438. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  43439. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  43440. const device = this.backend.device;
  43441. const data = image.data;
  43442. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  43443. const bytesPerRow = image.width * bytesPerTexel;
  43444. device.queue.writeTexture(
  43445. {
  43446. texture: textureGPU,
  43447. mipLevel: 0,
  43448. origin: { x: 0, y: 0, z: originDepth }
  43449. },
  43450. data,
  43451. {
  43452. offset: image.width * image.height * bytesPerTexel * depth,
  43453. bytesPerRow
  43454. },
  43455. {
  43456. width: image.width,
  43457. height: image.height,
  43458. depthOrArrayLayers: 1
  43459. } );
  43460. if ( flipY === true ) {
  43461. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  43462. }
  43463. }
  43464. /**
  43465. * Uploads compressed texture data to the GPU memory.
  43466. *
  43467. * @private
  43468. * @param {Array<Object>} mipmaps - An array with mipmap data.
  43469. * @param {GPUTexture} textureGPU - The GPU texture.
  43470. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  43471. */
  43472. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU ) {
  43473. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  43474. const device = this.backend.device;
  43475. const blockData = this._getBlockData( textureDescriptorGPU.format );
  43476. const isTextureArray = textureDescriptorGPU.size.depthOrArrayLayers > 1;
  43477. for ( let i = 0; i < mipmaps.length; i ++ ) {
  43478. const mipmap = mipmaps[ i ];
  43479. const width = mipmap.width;
  43480. const height = mipmap.height;
  43481. const depth = isTextureArray ? textureDescriptorGPU.size.depthOrArrayLayers : 1;
  43482. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  43483. const bytesPerImage = bytesPerRow * Math.ceil( height / blockData.height );
  43484. for ( let j = 0; j < depth; j ++ ) {
  43485. device.queue.writeTexture(
  43486. {
  43487. texture: textureGPU,
  43488. mipLevel: i,
  43489. origin: { x: 0, y: 0, z: j }
  43490. },
  43491. mipmap.data,
  43492. {
  43493. offset: j * bytesPerImage,
  43494. bytesPerRow,
  43495. rowsPerImage: Math.ceil( height / blockData.height )
  43496. },
  43497. {
  43498. width: Math.ceil( width / blockData.width ) * blockData.width,
  43499. height: Math.ceil( height / blockData.height ) * blockData.height,
  43500. depthOrArrayLayers: 1
  43501. }
  43502. );
  43503. }
  43504. }
  43505. }
  43506. /**
  43507. * This method is only relevant for compressed texture formats. It returns a block
  43508. * data descriptor for the given GPU compressed texture format.
  43509. *
  43510. * @private
  43511. * @param {String} format - The GPU compressed texture format.
  43512. * @return {Object} The block data descriptor.
  43513. */
  43514. _getBlockData( format ) {
  43515. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  43516. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  43517. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  43518. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSNorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  43519. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  43520. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  43521. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  43522. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  43523. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  43524. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  43525. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  43526. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  43527. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  43528. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  43529. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  43530. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  43531. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  43532. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  43533. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  43534. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  43535. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  43536. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  43537. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  43538. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  43539. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  43540. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  43541. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  43542. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  43543. }
  43544. /**
  43545. * Converts the three.js uv wrapping constants to GPU address mode constants.
  43546. *
  43547. * @private
  43548. * @param {Number} value - The three.js constant defining a uv wrapping mode.
  43549. * @return {String} The GPU address mode.
  43550. */
  43551. _convertAddressMode( value ) {
  43552. let addressMode = GPUAddressMode.ClampToEdge;
  43553. if ( value === RepeatWrapping ) {
  43554. addressMode = GPUAddressMode.Repeat;
  43555. } else if ( value === MirroredRepeatWrapping ) {
  43556. addressMode = GPUAddressMode.MirrorRepeat;
  43557. }
  43558. return addressMode;
  43559. }
  43560. /**
  43561. * Converts the three.js filter constants to GPU filter constants.
  43562. *
  43563. * @private
  43564. * @param {Number} value - The three.js constant defining a filter mode.
  43565. * @return {String} The GPU filter mode.
  43566. */
  43567. _convertFilterMode( value ) {
  43568. let filterMode = GPUFilterMode.Linear;
  43569. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  43570. filterMode = GPUFilterMode.Nearest;
  43571. }
  43572. return filterMode;
  43573. }
  43574. /**
  43575. * Returns the bytes-per-texel value for the given GPU texture format.
  43576. *
  43577. * @private
  43578. * @param {String} format - The GPU texture format.
  43579. * @return {Number} The bytes-per-texel.
  43580. */
  43581. _getBytesPerTexel( format ) {
  43582. // 8-bit formats
  43583. if ( format === GPUTextureFormat.R8Unorm ||
  43584. format === GPUTextureFormat.R8Snorm ||
  43585. format === GPUTextureFormat.R8Uint ||
  43586. format === GPUTextureFormat.R8Sint ) return 1;
  43587. // 16-bit formats
  43588. if ( format === GPUTextureFormat.R16Uint ||
  43589. format === GPUTextureFormat.R16Sint ||
  43590. format === GPUTextureFormat.R16Float ||
  43591. format === GPUTextureFormat.RG8Unorm ||
  43592. format === GPUTextureFormat.RG8Snorm ||
  43593. format === GPUTextureFormat.RG8Uint ||
  43594. format === GPUTextureFormat.RG8Sint ) return 2;
  43595. // 32-bit formats
  43596. if ( format === GPUTextureFormat.R32Uint ||
  43597. format === GPUTextureFormat.R32Sint ||
  43598. format === GPUTextureFormat.R32Float ||
  43599. format === GPUTextureFormat.RG16Uint ||
  43600. format === GPUTextureFormat.RG16Sint ||
  43601. format === GPUTextureFormat.RG16Float ||
  43602. format === GPUTextureFormat.RGBA8Unorm ||
  43603. format === GPUTextureFormat.RGBA8UnormSRGB ||
  43604. format === GPUTextureFormat.RGBA8Snorm ||
  43605. format === GPUTextureFormat.RGBA8Uint ||
  43606. format === GPUTextureFormat.RGBA8Sint ||
  43607. format === GPUTextureFormat.BGRA8Unorm ||
  43608. format === GPUTextureFormat.BGRA8UnormSRGB ||
  43609. // Packed 32-bit formats
  43610. format === GPUTextureFormat.RGB9E5UFloat ||
  43611. format === GPUTextureFormat.RGB10A2Unorm ||
  43612. format === GPUTextureFormat.RG11B10UFloat ||
  43613. format === GPUTextureFormat.Depth32Float ||
  43614. format === GPUTextureFormat.Depth24Plus ||
  43615. format === GPUTextureFormat.Depth24PlusStencil8 ||
  43616. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  43617. // 64-bit formats
  43618. if ( format === GPUTextureFormat.RG32Uint ||
  43619. format === GPUTextureFormat.RG32Sint ||
  43620. format === GPUTextureFormat.RG32Float ||
  43621. format === GPUTextureFormat.RGBA16Uint ||
  43622. format === GPUTextureFormat.RGBA16Sint ||
  43623. format === GPUTextureFormat.RGBA16Float ) return 8;
  43624. // 128-bit formats
  43625. if ( format === GPUTextureFormat.RGBA32Uint ||
  43626. format === GPUTextureFormat.RGBA32Sint ||
  43627. format === GPUTextureFormat.RGBA32Float ) return 16;
  43628. }
  43629. /**
  43630. * Returns the corresponding typed array type for the given GPU texture format.
  43631. *
  43632. * @private
  43633. * @param {String} format - The GPU texture format.
  43634. * @return {TypedArray.constructor} The typed array type.
  43635. */
  43636. _getTypedArrayType( format ) {
  43637. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  43638. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  43639. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  43640. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  43641. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  43642. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  43643. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  43644. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  43645. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  43646. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  43647. if ( format === GPUTextureFormat.RGBA8Unorm ) return Uint8Array;
  43648. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  43649. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  43650. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  43651. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  43652. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  43653. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  43654. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  43655. if ( format === GPUTextureFormat.R16Float ) return Uint16Array;
  43656. if ( format === GPUTextureFormat.RG16Float ) return Uint16Array;
  43657. if ( format === GPUTextureFormat.RGBA16Float ) return Uint16Array;
  43658. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  43659. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  43660. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  43661. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  43662. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  43663. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  43664. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  43665. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  43666. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  43667. if ( format === GPUTextureFormat.BGRA8Unorm ) return Uint8Array;
  43668. if ( format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  43669. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  43670. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  43671. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  43672. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  43673. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  43674. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  43675. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  43676. }
  43677. /**
  43678. * Returns the GPU dimensions for the given texture.
  43679. *
  43680. * @private
  43681. * @param {Texture} texture - The texture.
  43682. * @return {String} The GPU dimension.
  43683. */
  43684. _getDimension( texture ) {
  43685. let dimension;
  43686. if ( texture.isData3DTexture ) {
  43687. dimension = GPUTextureDimension.ThreeD;
  43688. } else {
  43689. dimension = GPUTextureDimension.TwoD;
  43690. }
  43691. return dimension;
  43692. }
  43693. }
  43694. /**
  43695. * Returns the GPU format for the given texture.
  43696. *
  43697. * @param {Texture} texture - The texture.
  43698. * @param {GPUDevice?} [device=null] - The GPU device which is used for feature detection.
  43699. * It is not necessary to apply the device for most formats.
  43700. * @return {String} The GPU format.
  43701. */
  43702. function getFormat( texture, device = null ) {
  43703. const format = texture.format;
  43704. const type = texture.type;
  43705. const colorSpace = texture.colorSpace;
  43706. let formatGPU;
  43707. if ( texture.isCompressedTexture === true || texture.isCompressedArrayTexture === true ) {
  43708. switch ( format ) {
  43709. case RGBA_S3TC_DXT1_Format:
  43710. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  43711. break;
  43712. case RGBA_S3TC_DXT3_Format:
  43713. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  43714. break;
  43715. case RGBA_S3TC_DXT5_Format:
  43716. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  43717. break;
  43718. case RGB_ETC2_Format:
  43719. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  43720. break;
  43721. case RGBA_ETC2_EAC_Format:
  43722. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  43723. break;
  43724. case RGBA_ASTC_4x4_Format:
  43725. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  43726. break;
  43727. case RGBA_ASTC_5x4_Format:
  43728. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  43729. break;
  43730. case RGBA_ASTC_5x5_Format:
  43731. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  43732. break;
  43733. case RGBA_ASTC_6x5_Format:
  43734. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  43735. break;
  43736. case RGBA_ASTC_6x6_Format:
  43737. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  43738. break;
  43739. case RGBA_ASTC_8x5_Format:
  43740. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  43741. break;
  43742. case RGBA_ASTC_8x6_Format:
  43743. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  43744. break;
  43745. case RGBA_ASTC_8x8_Format:
  43746. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  43747. break;
  43748. case RGBA_ASTC_10x5_Format:
  43749. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  43750. break;
  43751. case RGBA_ASTC_10x6_Format:
  43752. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  43753. break;
  43754. case RGBA_ASTC_10x8_Format:
  43755. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  43756. break;
  43757. case RGBA_ASTC_10x10_Format:
  43758. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  43759. break;
  43760. case RGBA_ASTC_12x10_Format:
  43761. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  43762. break;
  43763. case RGBA_ASTC_12x12_Format:
  43764. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  43765. break;
  43766. case RGBAFormat:
  43767. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  43768. break;
  43769. default:
  43770. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  43771. }
  43772. } else {
  43773. switch ( format ) {
  43774. case RGBAFormat:
  43775. switch ( type ) {
  43776. case ByteType:
  43777. formatGPU = GPUTextureFormat.RGBA8Snorm;
  43778. break;
  43779. case ShortType:
  43780. formatGPU = GPUTextureFormat.RGBA16Sint;
  43781. break;
  43782. case UnsignedShortType:
  43783. formatGPU = GPUTextureFormat.RGBA16Uint;
  43784. break;
  43785. case UnsignedIntType:
  43786. formatGPU = GPUTextureFormat.RGBA32Uint;
  43787. break;
  43788. case IntType:
  43789. formatGPU = GPUTextureFormat.RGBA32Sint;
  43790. break;
  43791. case UnsignedByteType:
  43792. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  43793. break;
  43794. case HalfFloatType:
  43795. formatGPU = GPUTextureFormat.RGBA16Float;
  43796. break;
  43797. case FloatType:
  43798. formatGPU = GPUTextureFormat.RGBA32Float;
  43799. break;
  43800. default:
  43801. console.error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  43802. }
  43803. break;
  43804. case RGBFormat:
  43805. switch ( type ) {
  43806. case UnsignedInt5999Type:
  43807. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  43808. break;
  43809. default:
  43810. console.error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  43811. }
  43812. break;
  43813. case RedFormat:
  43814. switch ( type ) {
  43815. case ByteType:
  43816. formatGPU = GPUTextureFormat.R8Snorm;
  43817. break;
  43818. case ShortType:
  43819. formatGPU = GPUTextureFormat.R16Sint;
  43820. break;
  43821. case UnsignedShortType:
  43822. formatGPU = GPUTextureFormat.R16Uint;
  43823. break;
  43824. case UnsignedIntType:
  43825. formatGPU = GPUTextureFormat.R32Uint;
  43826. break;
  43827. case IntType:
  43828. formatGPU = GPUTextureFormat.R32Sint;
  43829. break;
  43830. case UnsignedByteType:
  43831. formatGPU = GPUTextureFormat.R8Unorm;
  43832. break;
  43833. case HalfFloatType:
  43834. formatGPU = GPUTextureFormat.R16Float;
  43835. break;
  43836. case FloatType:
  43837. formatGPU = GPUTextureFormat.R32Float;
  43838. break;
  43839. default:
  43840. console.error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  43841. }
  43842. break;
  43843. case RGFormat:
  43844. switch ( type ) {
  43845. case ByteType:
  43846. formatGPU = GPUTextureFormat.RG8Snorm;
  43847. break;
  43848. case ShortType:
  43849. formatGPU = GPUTextureFormat.RG16Sint;
  43850. break;
  43851. case UnsignedShortType:
  43852. formatGPU = GPUTextureFormat.RG16Uint;
  43853. break;
  43854. case UnsignedIntType:
  43855. formatGPU = GPUTextureFormat.RG32Uint;
  43856. break;
  43857. case IntType:
  43858. formatGPU = GPUTextureFormat.RG32Sint;
  43859. break;
  43860. case UnsignedByteType:
  43861. formatGPU = GPUTextureFormat.RG8Unorm;
  43862. break;
  43863. case HalfFloatType:
  43864. formatGPU = GPUTextureFormat.RG16Float;
  43865. break;
  43866. case FloatType:
  43867. formatGPU = GPUTextureFormat.RG32Float;
  43868. break;
  43869. default:
  43870. console.error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  43871. }
  43872. break;
  43873. case DepthFormat:
  43874. switch ( type ) {
  43875. case UnsignedShortType:
  43876. formatGPU = GPUTextureFormat.Depth16Unorm;
  43877. break;
  43878. case UnsignedIntType:
  43879. formatGPU = GPUTextureFormat.Depth24Plus;
  43880. break;
  43881. case FloatType:
  43882. formatGPU = GPUTextureFormat.Depth32Float;
  43883. break;
  43884. default:
  43885. console.error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  43886. }
  43887. break;
  43888. case DepthStencilFormat:
  43889. switch ( type ) {
  43890. case UnsignedInt248Type:
  43891. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  43892. break;
  43893. case FloatType:
  43894. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  43895. console.error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  43896. }
  43897. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  43898. break;
  43899. default:
  43900. console.error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  43901. }
  43902. break;
  43903. case RedIntegerFormat:
  43904. switch ( type ) {
  43905. case IntType:
  43906. formatGPU = GPUTextureFormat.R32Sint;
  43907. break;
  43908. case UnsignedIntType:
  43909. formatGPU = GPUTextureFormat.R32Uint;
  43910. break;
  43911. default:
  43912. console.error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  43913. }
  43914. break;
  43915. case RGIntegerFormat:
  43916. switch ( type ) {
  43917. case IntType:
  43918. formatGPU = GPUTextureFormat.RG32Sint;
  43919. break;
  43920. case UnsignedIntType:
  43921. formatGPU = GPUTextureFormat.RG32Uint;
  43922. break;
  43923. default:
  43924. console.error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  43925. }
  43926. break;
  43927. case RGBAIntegerFormat:
  43928. switch ( type ) {
  43929. case IntType:
  43930. formatGPU = GPUTextureFormat.RGBA32Sint;
  43931. break;
  43932. case UnsignedIntType:
  43933. formatGPU = GPUTextureFormat.RGBA32Uint;
  43934. break;
  43935. default:
  43936. console.error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  43937. }
  43938. break;
  43939. default:
  43940. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  43941. }
  43942. }
  43943. return formatGPU;
  43944. }
  43945. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  43946. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  43947. const wgslTypeLib$1 = {
  43948. 'f32': 'float',
  43949. 'i32': 'int',
  43950. 'u32': 'uint',
  43951. 'bool': 'bool',
  43952. 'vec2<f32>': 'vec2',
  43953. 'vec2<i32>': 'ivec2',
  43954. 'vec2<u32>': 'uvec2',
  43955. 'vec2<bool>': 'bvec2',
  43956. 'vec2f': 'vec2',
  43957. 'vec2i': 'ivec2',
  43958. 'vec2u': 'uvec2',
  43959. 'vec2b': 'bvec2',
  43960. 'vec3<f32>': 'vec3',
  43961. 'vec3<i32>': 'ivec3',
  43962. 'vec3<u32>': 'uvec3',
  43963. 'vec3<bool>': 'bvec3',
  43964. 'vec3f': 'vec3',
  43965. 'vec3i': 'ivec3',
  43966. 'vec3u': 'uvec3',
  43967. 'vec3b': 'bvec3',
  43968. 'vec4<f32>': 'vec4',
  43969. 'vec4<i32>': 'ivec4',
  43970. 'vec4<u32>': 'uvec4',
  43971. 'vec4<bool>': 'bvec4',
  43972. 'vec4f': 'vec4',
  43973. 'vec4i': 'ivec4',
  43974. 'vec4u': 'uvec4',
  43975. 'vec4b': 'bvec4',
  43976. 'mat2x2<f32>': 'mat2',
  43977. 'mat2x2f': 'mat2',
  43978. 'mat3x3<f32>': 'mat3',
  43979. 'mat3x3f': 'mat3',
  43980. 'mat4x4<f32>': 'mat4',
  43981. 'mat4x4f': 'mat4',
  43982. 'sampler': 'sampler',
  43983. 'texture_1d': 'texture',
  43984. 'texture_2d': 'texture',
  43985. 'texture_2d_array': 'texture',
  43986. 'texture_multisampled_2d': 'cubeTexture',
  43987. 'texture_depth_2d': 'depthTexture',
  43988. 'texture_depth_multisampled_2d': 'depthTexture',
  43989. 'texture_3d': 'texture3D',
  43990. 'texture_cube': 'cubeTexture',
  43991. 'texture_cube_array': 'cubeTexture',
  43992. 'texture_storage_1d': 'storageTexture',
  43993. 'texture_storage_2d': 'storageTexture',
  43994. 'texture_storage_2d_array': 'storageTexture',
  43995. 'texture_storage_3d': 'storageTexture'
  43996. };
  43997. const parse = ( source ) => {
  43998. source = source.trim();
  43999. const declaration = source.match( declarationRegexp );
  44000. if ( declaration !== null && declaration.length === 4 ) {
  44001. const inputsCode = declaration[ 2 ];
  44002. const propsMatches = [];
  44003. let match = null;
  44004. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  44005. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  44006. }
  44007. // Process matches to correctly pair names and types
  44008. const inputs = [];
  44009. for ( let i = 0; i < propsMatches.length; i ++ ) {
  44010. const { name, type } = propsMatches[ i ];
  44011. let resolvedType = type;
  44012. if ( resolvedType.startsWith( 'ptr' ) ) {
  44013. resolvedType = 'pointer';
  44014. } else {
  44015. if ( resolvedType.startsWith( 'texture' ) ) {
  44016. resolvedType = type.split( '<' )[ 0 ];
  44017. }
  44018. resolvedType = wgslTypeLib$1[ resolvedType ];
  44019. }
  44020. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  44021. }
  44022. const blockCode = source.substring( declaration[ 0 ].length );
  44023. const outputType = declaration[ 3 ] || 'void';
  44024. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  44025. const type = wgslTypeLib$1[ outputType ] || outputType;
  44026. return {
  44027. type,
  44028. inputs,
  44029. name,
  44030. inputsCode,
  44031. blockCode,
  44032. outputType
  44033. };
  44034. } else {
  44035. throw new Error( 'FunctionNode: Function is not a WGSL code.' );
  44036. }
  44037. };
  44038. /**
  44039. * This class represents a WSL node function.
  44040. *
  44041. * @augments NodeFunction
  44042. */
  44043. class WGSLNodeFunction extends NodeFunction {
  44044. /**
  44045. * Constructs a new WGSL node function.
  44046. *
  44047. * @param {String} source - The WGSL source.
  44048. */
  44049. constructor( source ) {
  44050. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  44051. super( type, inputs, name );
  44052. this.inputsCode = inputsCode;
  44053. this.blockCode = blockCode;
  44054. this.outputType = outputType;
  44055. }
  44056. /**
  44057. * This method returns the WGSL code of the node function.
  44058. *
  44059. * @param {String} [name=this.name] - The function's name.
  44060. * @return {String} The shader code.
  44061. */
  44062. getCode( name = this.name ) {
  44063. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  44064. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  44065. }
  44066. }
  44067. /**
  44068. * A WGSL node parser.
  44069. *
  44070. * @augments NodeParser
  44071. */
  44072. class WGSLNodeParser extends NodeParser {
  44073. /**
  44074. * The method parses the given WGSL code an returns a node function.
  44075. *
  44076. * @param {String} source - The WGSL code.
  44077. * @return {WGSLNodeFunction} A node function.
  44078. */
  44079. parseFunction( source ) {
  44080. return new WGSLNodeFunction( source );
  44081. }
  44082. }
  44083. // GPUShaderStage is not defined in browsers not supporting WebGPU
  44084. const GPUShaderStage = ( typeof self !== 'undefined' ) ? self.GPUShaderStage : { VERTEX: 1, FRAGMENT: 2, COMPUTE: 4 };
  44085. const accessNames = {
  44086. [ NodeAccess.READ_ONLY ]: 'read',
  44087. [ NodeAccess.WRITE_ONLY ]: 'write',
  44088. [ NodeAccess.READ_WRITE ]: 'read_write'
  44089. };
  44090. const wrapNames = {
  44091. [ RepeatWrapping ]: 'repeat',
  44092. [ ClampToEdgeWrapping ]: 'clamp',
  44093. [ MirroredRepeatWrapping ]: 'mirror'
  44094. };
  44095. const gpuShaderStageLib = {
  44096. 'vertex': GPUShaderStage ? GPUShaderStage.VERTEX : 1,
  44097. 'fragment': GPUShaderStage ? GPUShaderStage.FRAGMENT : 2,
  44098. 'compute': GPUShaderStage ? GPUShaderStage.COMPUTE : 4
  44099. };
  44100. const supports = {
  44101. instance: true,
  44102. swizzleAssign: false,
  44103. storageBuffer: true
  44104. };
  44105. const wgslFnOpLib = {
  44106. '^^': 'tsl_xor'
  44107. };
  44108. const wgslTypeLib = {
  44109. float: 'f32',
  44110. int: 'i32',
  44111. uint: 'u32',
  44112. bool: 'bool',
  44113. color: 'vec3<f32>',
  44114. vec2: 'vec2<f32>',
  44115. ivec2: 'vec2<i32>',
  44116. uvec2: 'vec2<u32>',
  44117. bvec2: 'vec2<bool>',
  44118. vec3: 'vec3<f32>',
  44119. ivec3: 'vec3<i32>',
  44120. uvec3: 'vec3<u32>',
  44121. bvec3: 'vec3<bool>',
  44122. vec4: 'vec4<f32>',
  44123. ivec4: 'vec4<i32>',
  44124. uvec4: 'vec4<u32>',
  44125. bvec4: 'vec4<bool>',
  44126. mat2: 'mat2x2<f32>',
  44127. mat3: 'mat3x3<f32>',
  44128. mat4: 'mat4x4<f32>'
  44129. };
  44130. const wgslCodeCache = {};
  44131. const wgslPolyfill = {
  44132. tsl_xor: new CodeNode( 'fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }' ),
  44133. mod_float: new CodeNode( 'fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  44134. mod_vec2: new CodeNode( 'fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  44135. mod_vec3: new CodeNode( 'fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  44136. mod_vec4: new CodeNode( 'fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  44137. equals_bool: new CodeNode( 'fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  44138. 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 ); }' ),
  44139. 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 ); }' ),
  44140. 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 ); }' ),
  44141. repeatWrapping_float: new CodeNode( 'fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }' ),
  44142. 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 ); }' ),
  44143. clampWrapping_float: new CodeNode( 'fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }' ),
  44144. biquadraticTexture: new CodeNode( /* wgsl */`
  44145. fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {
  44146. let res = vec2f( iRes );
  44147. let uvScaled = coord * res;
  44148. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  44149. // https://www.shadertoy.com/view/WtyXRy
  44150. let uv = uvWrapping - 0.5;
  44151. let iuv = floor( uv );
  44152. let f = fract( uv );
  44153. let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );
  44154. let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );
  44155. let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );
  44156. let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );
  44157. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  44158. }
  44159. ` )
  44160. };
  44161. const wgslMethods = {
  44162. dFdx: 'dpdx',
  44163. dFdy: '- dpdy',
  44164. mod_float: 'tsl_mod_float',
  44165. mod_vec2: 'tsl_mod_vec2',
  44166. mod_vec3: 'tsl_mod_vec3',
  44167. mod_vec4: 'tsl_mod_vec4',
  44168. equals_bool: 'tsl_equals_bool',
  44169. equals_bvec2: 'tsl_equals_bvec2',
  44170. equals_bvec3: 'tsl_equals_bvec3',
  44171. equals_bvec4: 'tsl_equals_bvec4',
  44172. inversesqrt: 'inverseSqrt',
  44173. bitcast: 'bitcast<f32>'
  44174. };
  44175. // WebGPU issue: does not support pow() with negative base on Windows
  44176. if ( typeof navigator !== 'undefined' && /Windows/g.test( navigator.userAgent ) ) {
  44177. 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 ); }' );
  44178. 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 ] );
  44179. 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 ] );
  44180. 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 ] );
  44181. wgslMethods.pow_float = 'tsl_pow_float';
  44182. wgslMethods.pow_vec2 = 'tsl_pow_vec2';
  44183. wgslMethods.pow_vec3 = 'tsl_pow_vec3';
  44184. wgslMethods.pow_vec4 = 'tsl_pow_vec4';
  44185. }
  44186. //
  44187. let diagnostics = '';
  44188. if ( ( typeof navigator !== 'undefined' && /Firefox|Deno/g.test( navigator.userAgent ) ) !== true ) {
  44189. diagnostics += 'diagnostic( off, derivative_uniformity );\n';
  44190. }
  44191. /**
  44192. * A node builder targeting WGSL.
  44193. *
  44194. * This module generates WGSL shader code from node materials and also
  44195. * generates the respective bindings and vertex buffer definitions. These
  44196. * data are later used by the renderer to create render and compute pipelines
  44197. * for render objects.
  44198. *
  44199. * @augments NodeBuilder
  44200. */
  44201. class WGSLNodeBuilder extends NodeBuilder {
  44202. /**
  44203. * Constructs a new WGSL node builder renderer.
  44204. *
  44205. * @param {Object3D} object - The 3D object.
  44206. * @param {Renderer} renderer - The renderer.
  44207. */
  44208. constructor( object, renderer ) {
  44209. super( object, renderer, new WGSLNodeParser() );
  44210. /**
  44211. * A dictionary that holds for each shader stage ('vertex', 'fragment', 'compute')
  44212. * another dictionary which manages UBOs per group ('render','frame','object').
  44213. *
  44214. * @type {Object<String,Object<String,NodeUniformsGroup>>}
  44215. */
  44216. this.uniformGroups = {};
  44217. /**
  44218. * A dictionary that holds for each shader stage a Map of builtins.
  44219. *
  44220. * @type {Object<String,Map<String,Object>>}
  44221. */
  44222. this.builtins = {};
  44223. /**
  44224. * A dictionary that holds for each shader stage a Set of directives.
  44225. *
  44226. * @type {Object<String,Set<String>>}
  44227. */
  44228. this.directives = {};
  44229. /**
  44230. * A map for managing scope arrays. Only relevant for when using
  44231. * {@link module:WorkgroupInfoNode} in context of compute shaders.
  44232. *
  44233. * @type {Map<String,Object>}
  44234. */
  44235. this.scopedArrays = new Map();
  44236. }
  44237. /**
  44238. * Checks if the given texture requires a manual conversion to the working color space.
  44239. *
  44240. * @param {Texture} texture - The texture to check.
  44241. * @return {Boolean} Whether the given texture requires a conversion to working color space or not.
  44242. */
  44243. needsToWorkingColorSpace( texture ) {
  44244. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  44245. }
  44246. /**
  44247. * Generates the WGSL snippet for sampled textures.
  44248. *
  44249. * @private
  44250. * @param {Texture} texture - The texture.
  44251. * @param {String} textureProperty - The name of the texture uniform in the shader.
  44252. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  44253. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  44254. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  44255. * @return {String} The WGSL snippet.
  44256. */
  44257. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  44258. if ( shaderStage === 'fragment' ) {
  44259. if ( depthSnippet ) {
  44260. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  44261. } else {
  44262. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  44263. }
  44264. } else if ( this.isFilteredTexture( texture ) ) {
  44265. return this.generateFilteredTexture( texture, textureProperty, uvSnippet );
  44266. } else {
  44267. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, '0' );
  44268. }
  44269. }
  44270. /**
  44271. * Generates the WGSL snippet when sampling video textures.
  44272. *
  44273. * @private
  44274. * @param {String} textureProperty - The name of the video texture uniform in the shader.
  44275. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  44276. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  44277. * @return {String} The WGSL snippet.
  44278. */
  44279. _generateVideoSample( textureProperty, uvSnippet, shaderStage = this.shaderStage ) {
  44280. if ( shaderStage === 'fragment' ) {
  44281. return `textureSampleBaseClampToEdge( ${ textureProperty }, ${ textureProperty }_sampler, vec2<f32>( ${ uvSnippet }.x, 1.0 - ${ uvSnippet }.y ) )`;
  44282. } else {
  44283. console.error( `WebGPURenderer: THREE.VideoTexture does not support ${ shaderStage } shader.` );
  44284. }
  44285. }
  44286. /**
  44287. * Generates the WGSL snippet when sampling textures with explicit mip level.
  44288. *
  44289. * @private
  44290. * @param {Texture} texture - The texture.
  44291. * @param {String} textureProperty - The name of the texture uniform in the shader.
  44292. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  44293. * @param {String} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  44294. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  44295. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  44296. * @return {String} The WGSL snippet.
  44297. */
  44298. _generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  44299. if ( ( shaderStage === 'fragment' || shaderStage === 'compute' ) && this.isUnfilterable( texture ) === false ) {
  44300. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  44301. } else if ( this.isFilteredTexture( texture ) ) {
  44302. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet );
  44303. } else {
  44304. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet );
  44305. }
  44306. }
  44307. /**
  44308. * Generates a wrap function used in context of textures.
  44309. *
  44310. * @param {Texture} texture - The texture to generate the function for.
  44311. * @return {String} The name of the generated function.
  44312. */
  44313. generateWrapFunction( texture ) {
  44314. const functionName = `tsl_coord_${ wrapNames[ texture.wrapS ] }S_${ wrapNames[ texture.wrapT ] }_${texture.isData3DTexture ? '3d' : '2d'}T`;
  44315. let nodeCode = wgslCodeCache[ functionName ];
  44316. if ( nodeCode === undefined ) {
  44317. const includes = [];
  44318. // For 3D textures, use vec3f; for texture arrays, keep vec2f since array index is separate
  44319. const coordType = texture.isData3DTexture ? 'vec3f' : 'vec2f';
  44320. let code = `fn ${functionName}( coord : ${coordType} ) -> ${coordType} {\n\n\treturn ${coordType}(\n`;
  44321. const addWrapSnippet = ( wrap, axis ) => {
  44322. if ( wrap === RepeatWrapping ) {
  44323. includes.push( wgslPolyfill.repeatWrapping_float );
  44324. code += `\t\ttsl_repeatWrapping_float( coord.${ axis } )`;
  44325. } else if ( wrap === ClampToEdgeWrapping ) {
  44326. includes.push( wgslPolyfill.clampWrapping_float );
  44327. code += `\t\ttsl_clampWrapping_float( coord.${ axis } )`;
  44328. } else if ( wrap === MirroredRepeatWrapping ) {
  44329. includes.push( wgslPolyfill.mirrorWrapping_float );
  44330. code += `\t\ttsl_mirrorWrapping_float( coord.${ axis } )`;
  44331. } else {
  44332. code += `\t\tcoord.${ axis }`;
  44333. console.warn( `WebGPURenderer: Unsupported texture wrap type "${ wrap }" for vertex shader.` );
  44334. }
  44335. };
  44336. addWrapSnippet( texture.wrapS, 'x' );
  44337. code += ',\n';
  44338. addWrapSnippet( texture.wrapT, 'y' );
  44339. if ( texture.isData3DTexture ) {
  44340. code += ',\n';
  44341. addWrapSnippet( texture.wrapR, 'z' );
  44342. }
  44343. code += '\n\t);\n\n}\n';
  44344. wgslCodeCache[ functionName ] = nodeCode = new CodeNode( code, includes );
  44345. }
  44346. nodeCode.build( this );
  44347. return functionName;
  44348. }
  44349. /**
  44350. * Generates the array declaration string.
  44351. *
  44352. * @param {String} type - The type.
  44353. * @param {Number?} [count] - The count.
  44354. * @return {String} The generated value as a shader string.
  44355. */
  44356. generateArrayDeclaration( type, count ) {
  44357. return `array< ${ this.getType( type ) }, ${ count } >`;
  44358. }
  44359. /**
  44360. * Generates a WGSL variable that holds the texture dimension of the given texture.
  44361. * It also returns information about the the number of layers (elements) of an arrayed
  44362. * texture as well as the cube face count of cube textures.
  44363. *
  44364. * @param {Texture} texture - The texture to generate the function for.
  44365. * @param {String} textureProperty - The name of the video texture uniform in the shader.
  44366. * @param {String} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  44367. * @return {String} The name of the dimension variable.
  44368. */
  44369. generateTextureDimension( texture, textureProperty, levelSnippet ) {
  44370. const textureData = this.getDataFromNode( texture, this.shaderStage, this.globalCache );
  44371. if ( textureData.dimensionsSnippet === undefined ) textureData.dimensionsSnippet = {};
  44372. let textureDimensionNode = textureData.dimensionsSnippet[ levelSnippet ];
  44373. if ( textureData.dimensionsSnippet[ levelSnippet ] === undefined ) {
  44374. let textureDimensionsParams;
  44375. let dimensionType;
  44376. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  44377. const isMultisampled = primarySamples > 1;
  44378. if ( texture.isData3DTexture ) {
  44379. dimensionType = 'vec3<u32>';
  44380. } else {
  44381. // Regular 2D textures, depth textures, etc.
  44382. dimensionType = 'vec2<u32>';
  44383. }
  44384. // Build parameters string based on texture type and multisampling
  44385. if ( isMultisampled || texture.isVideoTexture || texture.isStorageTexture ) {
  44386. textureDimensionsParams = textureProperty;
  44387. } else {
  44388. textureDimensionsParams = `${textureProperty}${levelSnippet ? `, u32( ${ levelSnippet } )` : ''}`;
  44389. }
  44390. textureDimensionNode = new VarNode( new ExpressionNode( `textureDimensions( ${ textureDimensionsParams } )`, dimensionType ) );
  44391. textureData.dimensionsSnippet[ levelSnippet ] = textureDimensionNode;
  44392. if ( texture.isDataArrayTexture || texture.isData3DTexture ) {
  44393. textureData.arrayLayerCount = new VarNode(
  44394. new ExpressionNode(
  44395. `textureNumLayers(${textureProperty})`,
  44396. 'u32'
  44397. )
  44398. );
  44399. }
  44400. // For cube textures, we know it's always 6 faces
  44401. if ( texture.isTextureCube ) {
  44402. textureData.cubeFaceCount = new VarNode(
  44403. new ExpressionNode( '6u', 'u32' )
  44404. );
  44405. }
  44406. }
  44407. return textureDimensionNode.build( this );
  44408. }
  44409. /**
  44410. * Generates the WGSL snippet for a manual filtered texture.
  44411. *
  44412. * @param {Texture} texture - The texture.
  44413. * @param {String} textureProperty - The name of the texture uniform in the shader.
  44414. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  44415. * @param {String} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  44416. * @return {String} The WGSL snippet.
  44417. */
  44418. generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet = '0u' ) {
  44419. this._include( 'biquadraticTexture' );
  44420. const wrapFunction = this.generateWrapFunction( texture );
  44421. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  44422. return `tsl_biquadraticTexture( ${ textureProperty }, ${ wrapFunction }( ${ uvSnippet } ), ${ textureDimension }, u32( ${ levelSnippet } ) )`;
  44423. }
  44424. /**
  44425. * Generates the WGSL snippet for a texture lookup with explicit level-of-detail.
  44426. * Since it's a lookup, no sampling or filtering is applied.
  44427. *
  44428. * @param {Texture} texture - The texture.
  44429. * @param {String} textureProperty - The name of the texture uniform in the shader.
  44430. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  44431. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  44432. * @param {String} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  44433. * @return {String} The WGSL snippet.
  44434. */
  44435. generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet = '0u' ) {
  44436. const wrapFunction = this.generateWrapFunction( texture );
  44437. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  44438. const vecType = texture.isData3DTexture ? 'vec3' : 'vec2';
  44439. const coordSnippet = `${vecType}<u32>(${wrapFunction}(${uvSnippet}) * ${vecType}<f32>(${textureDimension}))`;
  44440. return this.generateTextureLoad( texture, textureProperty, coordSnippet, depthSnippet, levelSnippet );
  44441. }
  44442. /**
  44443. * Generates the WGSL snippet that reads a single texel from a texture without sampling or filtering.
  44444. *
  44445. * @param {Texture} texture - The texture.
  44446. * @param {String} textureProperty - The name of the texture uniform in the shader.
  44447. * @param {String} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  44448. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  44449. * @param {String} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  44450. * @return {String} The WGSL snippet.
  44451. */
  44452. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0u' ) {
  44453. if ( texture.isVideoTexture === true || texture.isStorageTexture === true ) {
  44454. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet } )`;
  44455. } else if ( depthSnippet ) {
  44456. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, u32( ${ levelSnippet } ) )`;
  44457. } else {
  44458. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, u32( ${ levelSnippet } ) )`;
  44459. }
  44460. }
  44461. /**
  44462. * Generates the WGSL snippet that writes a single texel to a texture.
  44463. *
  44464. * @param {Texture} texture - The texture.
  44465. * @param {String} textureProperty - The name of the texture uniform in the shader.
  44466. * @param {String} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  44467. * @param {String} valueSnippet - A WGSL snippet that represent the new texel value.
  44468. * @return {String} The WGSL snippet.
  44469. */
  44470. generateTextureStore( texture, textureProperty, uvIndexSnippet, valueSnippet ) {
  44471. return `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  44472. }
  44473. /**
  44474. * Returns `true` if the sampled values of the given texture should be compared against a reference value.
  44475. *
  44476. * @param {Texture} texture - The texture.
  44477. * @return {Boolean} Whether the sampled values of the given texture should be compared against a reference value or not.
  44478. */
  44479. isSampleCompare( texture ) {
  44480. return texture.isDepthTexture === true && texture.compareFunction !== null;
  44481. }
  44482. /**
  44483. * Returns `true` if the given texture is unfilterable.
  44484. *
  44485. * @param {Texture} texture - The texture.
  44486. * @return {Boolean} Whether the given texture is unfilterable or not.
  44487. */
  44488. isUnfilterable( texture ) {
  44489. return this.getComponentTypeFromTexture( texture ) !== 'float' ||
  44490. ( ! this.isAvailable( 'float32Filterable' ) && texture.isDataTexture === true && texture.type === FloatType ) ||
  44491. ( this.isSampleCompare( texture ) === false && texture.minFilter === NearestFilter && texture.magFilter === NearestFilter ) ||
  44492. this.renderer.backend.utils.getTextureSampleData( texture ).primarySamples > 1;
  44493. }
  44494. /**
  44495. * Generates the WGSL snippet for sampling/loading the given texture.
  44496. *
  44497. * @param {Texture} texture - The texture.
  44498. * @param {String} textureProperty - The name of the texture uniform in the shader.
  44499. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  44500. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  44501. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  44502. * @return {String} The WGSL snippet.
  44503. */
  44504. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  44505. let snippet = null;
  44506. if ( texture.isVideoTexture === true ) {
  44507. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  44508. } else if ( this.isUnfilterable( texture ) ) {
  44509. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, '0', shaderStage );
  44510. } else {
  44511. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage );
  44512. }
  44513. return snippet;
  44514. }
  44515. /**
  44516. * Generates the WGSL snippet for sampling/loading the given texture using explicit gradients.
  44517. *
  44518. * @param {Texture} texture - The texture.
  44519. * @param {String} textureProperty - The name of the texture uniform in the shader.
  44520. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  44521. * @param {Array<String>} gradSnippet - An array holding both gradient WGSL snippets.
  44522. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  44523. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  44524. * @return {String} The WGSL snippet.
  44525. */
  44526. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  44527. if ( shaderStage === 'fragment' ) {
  44528. // TODO handle i32 or u32 --> uvSnippet, array_index: A, ddx, ddy
  44529. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  44530. } else {
  44531. console.error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  44532. }
  44533. }
  44534. /**
  44535. * Generates the WGSL snippet for sampling a depth texture and comparing the sampled depth values
  44536. * against a reference value.
  44537. *
  44538. * @param {Texture} texture - The texture.
  44539. * @param {String} textureProperty - The name of the texture uniform in the shader.
  44540. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  44541. * @param {String} compareSnippet - A WGSL snippet that represents the reference value.
  44542. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  44543. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  44544. * @return {String} The WGSL snippet.
  44545. */
  44546. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  44547. if ( shaderStage === 'fragment' ) {
  44548. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  44549. } else {
  44550. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  44551. }
  44552. }
  44553. /**
  44554. * Generates the WGSL snippet when sampling textures with explicit mip level.
  44555. *
  44556. * @param {Texture} texture - The texture.
  44557. * @param {String} textureProperty - The name of the texture uniform in the shader.
  44558. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  44559. * @param {String} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  44560. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  44561. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  44562. * @return {String} The WGSL snippet.
  44563. */
  44564. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  44565. let snippet = null;
  44566. if ( texture.isVideoTexture === true ) {
  44567. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  44568. } else {
  44569. snippet = this._generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage );
  44570. }
  44571. return snippet;
  44572. }
  44573. /**
  44574. * Generates the WGSL snippet when sampling textures with a bias to the mip level.
  44575. *
  44576. * @param {Texture} texture - The texture.
  44577. * @param {String} textureProperty - The name of the texture uniform in the shader.
  44578. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  44579. * @param {String} biasSnippet - A WGSL snippet that represents the bias to apply to the mip level before sampling.
  44580. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  44581. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  44582. * @return {String} The WGSL snippet.
  44583. */
  44584. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  44585. if ( shaderStage === 'fragment' ) {
  44586. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  44587. } else {
  44588. console.error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  44589. }
  44590. }
  44591. /**
  44592. * Returns a WGSL snippet that represents the property name of the given node.
  44593. *
  44594. * @param {Node} node - The node.
  44595. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  44596. * @return {String} The property name.
  44597. */
  44598. getPropertyName( node, shaderStage = this.shaderStage ) {
  44599. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  44600. if ( shaderStage === 'vertex' ) {
  44601. return `varyings.${ node.name }`;
  44602. }
  44603. } else if ( node.isNodeUniform === true ) {
  44604. const name = node.name;
  44605. const type = node.type;
  44606. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  44607. return name;
  44608. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  44609. return `NodeBuffer_${ node.id }.${name}`;
  44610. } else {
  44611. return node.groupNode.name + '.' + name;
  44612. }
  44613. }
  44614. return super.getPropertyName( node );
  44615. }
  44616. /**
  44617. * Returns the output struct name.
  44618. *
  44619. * @return {String} The name of the output struct.
  44620. */
  44621. getOutputStructName() {
  44622. return 'output';
  44623. }
  44624. /**
  44625. * Returns uniforms group count for the given shader stage.
  44626. *
  44627. * @private
  44628. * @param {String} shaderStage - The shader stage.
  44629. * @return {Number} The uniforms group count for the given shader stage.
  44630. */
  44631. _getUniformGroupCount( shaderStage ) {
  44632. return Object.keys( this.uniforms[ shaderStage ] ).length;
  44633. }
  44634. /**
  44635. * Returns the native shader operator name for a given generic name.
  44636. *
  44637. * @param {String} op - The operator name to resolve.
  44638. * @return {String} The resolved operator name.
  44639. */
  44640. getFunctionOperator( op ) {
  44641. const fnOp = wgslFnOpLib[ op ];
  44642. if ( fnOp !== undefined ) {
  44643. this._include( fnOp );
  44644. return fnOp;
  44645. }
  44646. return null;
  44647. }
  44648. /**
  44649. * Returns the node access for the given node and shader stage.
  44650. *
  44651. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  44652. * @param {String} shaderStage - The shader stage.
  44653. * @return {String} The node access.
  44654. */
  44655. getNodeAccess( node, shaderStage ) {
  44656. if ( shaderStage !== 'compute' )
  44657. return NodeAccess.READ_ONLY;
  44658. return node.access;
  44659. }
  44660. /**
  44661. * Returns A WGSL snippet representing the storage access.
  44662. *
  44663. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  44664. * @param {String} shaderStage - The shader stage.
  44665. * @return {String} The WGSL snippet representing the storage access.
  44666. */
  44667. getStorageAccess( node, shaderStage ) {
  44668. return accessNames[ this.getNodeAccess( node, shaderStage ) ];
  44669. }
  44670. /**
  44671. * This method is one of the more important ones since it's responsible
  44672. * for generating a matching binding instance for the given uniform node.
  44673. *
  44674. * These bindings are later used in the renderer to create bind groups
  44675. * and layouts.
  44676. *
  44677. * @param {UniformNode} node - The uniform node.
  44678. * @param {String} type - The node data type.
  44679. * @param {String} shaderStage - The shader stage.
  44680. * @param {String?} [name=null] - An optional uniform name.
  44681. * @return {NodeUniform} The node uniform object.
  44682. */
  44683. getUniformFromNode( node, type, shaderStage, name = null ) {
  44684. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  44685. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  44686. if ( nodeData.uniformGPU === undefined ) {
  44687. let uniformGPU;
  44688. const group = node.groupNode;
  44689. const groupName = group.name;
  44690. const bindings = this.getBindGroupArray( groupName, shaderStage );
  44691. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  44692. let texture = null;
  44693. const access = this.getNodeAccess( node, shaderStage );
  44694. if ( type === 'texture' || type === 'storageTexture' ) {
  44695. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, access );
  44696. } else if ( type === 'cubeTexture' ) {
  44697. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, access );
  44698. } else if ( type === 'texture3D' ) {
  44699. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  44700. }
  44701. texture.store = node.isStorageTextureNode === true;
  44702. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  44703. if ( ( shaderStage === 'fragment' || shaderStage === 'compute' ) && this.isUnfilterable( node.value ) === false && texture.store === false ) {
  44704. const sampler = new NodeSampler( `${uniformNode.name}_sampler`, uniformNode.node, group );
  44705. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  44706. bindings.push( sampler, texture );
  44707. uniformGPU = [ sampler, texture ];
  44708. } else {
  44709. bindings.push( texture );
  44710. uniformGPU = [ texture ];
  44711. }
  44712. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  44713. const bufferClass = type === 'buffer' ? NodeUniformBuffer : NodeStorageBuffer;
  44714. const buffer = new bufferClass( node, group );
  44715. buffer.setVisibility( gpuShaderStageLib[ shaderStage ] );
  44716. bindings.push( buffer );
  44717. uniformGPU = buffer;
  44718. } else {
  44719. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  44720. let uniformsGroup = uniformsStage[ groupName ];
  44721. if ( uniformsGroup === undefined ) {
  44722. uniformsGroup = new NodeUniformsGroup( groupName, group );
  44723. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  44724. uniformsStage[ groupName ] = uniformsGroup;
  44725. bindings.push( uniformsGroup );
  44726. }
  44727. uniformGPU = this.getNodeUniform( uniformNode, type );
  44728. uniformsGroup.addUniform( uniformGPU );
  44729. }
  44730. nodeData.uniformGPU = uniformGPU;
  44731. }
  44732. return uniformNode;
  44733. }
  44734. /**
  44735. * This method should be used whenever builtins are required in nodes.
  44736. * The internal builtins data structure will make sure builtins are
  44737. * defined in the WGSL source.
  44738. *
  44739. * @param {String} name - The builtin name.
  44740. * @param {String} property - The property name.
  44741. * @param {String} type - The node data type.
  44742. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  44743. * @return {String} The property name.
  44744. */
  44745. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  44746. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  44747. if ( map.has( name ) === false ) {
  44748. map.set( name, {
  44749. name,
  44750. property,
  44751. type
  44752. } );
  44753. }
  44754. return property;
  44755. }
  44756. /**
  44757. * Returns `true` if the given builtin is defined in the given shader stage.
  44758. *
  44759. * @param {String} name - The builtin name.
  44760. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  44761. * @return {String} Whether the given builtin is defined in the given shader stage or not.
  44762. */
  44763. hasBuiltin( name, shaderStage = this.shaderStage ) {
  44764. return ( this.builtins[ shaderStage ] !== undefined && this.builtins[ shaderStage ].has( name ) );
  44765. }
  44766. /**
  44767. * Returns the vertex index builtin.
  44768. *
  44769. * @return {String} The vertex index.
  44770. */
  44771. getVertexIndex() {
  44772. if ( this.shaderStage === 'vertex' ) {
  44773. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  44774. }
  44775. return 'vertexIndex';
  44776. }
  44777. /**
  44778. * Builds the given shader node.
  44779. *
  44780. * @param {ShaderNodeInternal} shaderNode - The shader node.
  44781. * @return {String} The WGSL function code.
  44782. */
  44783. buildFunctionCode( shaderNode ) {
  44784. const layout = shaderNode.layout;
  44785. const flowData = this.flowShaderNode( shaderNode );
  44786. const parameters = [];
  44787. for ( const input of layout.inputs ) {
  44788. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  44789. }
  44790. //
  44791. let code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  44792. ${ flowData.vars }
  44793. ${ flowData.code }
  44794. `;
  44795. if ( flowData.result ) {
  44796. code += `\treturn ${ flowData.result };\n`;
  44797. }
  44798. code += '\n}\n';
  44799. //
  44800. return code;
  44801. }
  44802. /**
  44803. * Returns the instance index builtin.
  44804. *
  44805. * @return {String} The instance index.
  44806. */
  44807. getInstanceIndex() {
  44808. if ( this.shaderStage === 'vertex' ) {
  44809. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  44810. }
  44811. return 'instanceIndex';
  44812. }
  44813. /**
  44814. * Returns the invocation local index builtin.
  44815. *
  44816. * @return {String} The invocation local index.
  44817. */
  44818. getInvocationLocalIndex() {
  44819. return this.getBuiltin( 'local_invocation_index', 'invocationLocalIndex', 'u32', 'attribute' );
  44820. }
  44821. /**
  44822. * Returns the subgroup size builtin.
  44823. *
  44824. * @return {String} The subgroup size.
  44825. */
  44826. getSubgroupSize() {
  44827. this.enableSubGroups();
  44828. return this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  44829. }
  44830. /**
  44831. * Returns the invocation subgroup index builtin.
  44832. *
  44833. * @return {String} The invocation subgroup index.
  44834. */
  44835. getInvocationSubgroupIndex() {
  44836. this.enableSubGroups();
  44837. return this.getBuiltin( 'subgroup_invocation_id', 'invocationSubgroupIndex', 'u32', 'attribute' );
  44838. }
  44839. /**
  44840. * Returns the subgroup index builtin.
  44841. *
  44842. * @return {String} The subgroup index.
  44843. */
  44844. getSubgroupIndex() {
  44845. this.enableSubGroups();
  44846. return this.getBuiltin( 'subgroup_id', 'subgroupIndex', 'u32', 'attribute' );
  44847. }
  44848. /**
  44849. * Overwritten as a NOP since this method is intended for the WebGL 2 backend.
  44850. *
  44851. * @return {null} Null.
  44852. */
  44853. getDrawIndex() {
  44854. return null;
  44855. }
  44856. /**
  44857. * Returns the front facing builtin.
  44858. *
  44859. * @return {String} The front facing builtin.
  44860. */
  44861. getFrontFacing() {
  44862. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  44863. }
  44864. /**
  44865. * Returns the frag coord builtin.
  44866. *
  44867. * @return {String} The frag coord builtin.
  44868. */
  44869. getFragCoord() {
  44870. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xy';
  44871. }
  44872. /**
  44873. * Returns the frag depth builtin.
  44874. *
  44875. * @return {String} The frag depth builtin.
  44876. */
  44877. getFragDepth() {
  44878. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  44879. }
  44880. /**
  44881. * Returns the clip distances builtin.
  44882. *
  44883. * @return {String} The clip distances builtin.
  44884. */
  44885. getClipDistance() {
  44886. return 'varyings.hw_clip_distances';
  44887. }
  44888. /**
  44889. * Whether to flip texture data along its vertical axis or not.
  44890. *
  44891. * @return {Boolean} Returns always `false` in context of WGSL.
  44892. */
  44893. isFlipY() {
  44894. return false;
  44895. }
  44896. /**
  44897. * Enables the given directive for the given shader stage.
  44898. *
  44899. * @param {String} name - The directive name.
  44900. * @param {String} [shaderStage=this.shaderStage] - The shader stage to enable the directive for.
  44901. */
  44902. enableDirective( name, shaderStage = this.shaderStage ) {
  44903. const stage = this.directives[ shaderStage ] || ( this.directives[ shaderStage ] = new Set() );
  44904. stage.add( name );
  44905. }
  44906. /**
  44907. * Returns the directives of the given shader stage as a WGSL string.
  44908. *
  44909. * @param {String} shaderStage - The shader stage.
  44910. * @return {String} A WGSL snippet that enables the directives of the given stage.
  44911. */
  44912. getDirectives( shaderStage ) {
  44913. const snippets = [];
  44914. const directives = this.directives[ shaderStage ];
  44915. if ( directives !== undefined ) {
  44916. for ( const directive of directives ) {
  44917. snippets.push( `enable ${directive};` );
  44918. }
  44919. }
  44920. return snippets.join( '\n' );
  44921. }
  44922. /**
  44923. * Enables the 'subgroups' directive.
  44924. */
  44925. enableSubGroups() {
  44926. this.enableDirective( 'subgroups' );
  44927. }
  44928. /**
  44929. * Enables the 'subgroups-f16' directive.
  44930. */
  44931. enableSubgroupsF16() {
  44932. this.enableDirective( 'subgroups-f16' );
  44933. }
  44934. /**
  44935. * Enables the 'clip_distances' directive.
  44936. */
  44937. enableClipDistances() {
  44938. this.enableDirective( 'clip_distances' );
  44939. }
  44940. /**
  44941. * Enables the 'f16' directive.
  44942. */
  44943. enableShaderF16() {
  44944. this.enableDirective( 'f16' );
  44945. }
  44946. /**
  44947. * Enables the 'dual_source_blending' directive.
  44948. */
  44949. enableDualSourceBlending() {
  44950. this.enableDirective( 'dual_source_blending' );
  44951. }
  44952. /**
  44953. * Enables hardware clipping.
  44954. *
  44955. * @param {String} planeCount - The clipping plane count.
  44956. */
  44957. enableHardwareClipping( planeCount ) {
  44958. this.enableClipDistances();
  44959. this.getBuiltin( 'clip_distances', 'hw_clip_distances', `array<f32, ${ planeCount } >`, 'vertex' );
  44960. }
  44961. /**
  44962. * Returns the builtins of the given shader stage as a WGSL string.
  44963. *
  44964. * @param {String} shaderStage - The shader stage.
  44965. * @return {String} A WGSL snippet that represents the builtins of the given stage.
  44966. */
  44967. getBuiltins( shaderStage ) {
  44968. const snippets = [];
  44969. const builtins = this.builtins[ shaderStage ];
  44970. if ( builtins !== undefined ) {
  44971. for ( const { name, property, type } of builtins.values() ) {
  44972. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  44973. }
  44974. }
  44975. return snippets.join( ',\n\t' );
  44976. }
  44977. /**
  44978. * This method should be used when a new scoped buffer is used in context of
  44979. * compute shaders. It adds the array to the internal data structure which is
  44980. * later used to generate the respective WGSL.
  44981. *
  44982. * @param {String} name - The array name.
  44983. * @param {String} scope - The scope.
  44984. * @param {String} bufferType - The buffer type.
  44985. * @param {String} bufferCount - The buffer count.
  44986. * @return {String} The array name.
  44987. */
  44988. getScopedArray( name, scope, bufferType, bufferCount ) {
  44989. if ( this.scopedArrays.has( name ) === false ) {
  44990. this.scopedArrays.set( name, {
  44991. name,
  44992. scope,
  44993. bufferType,
  44994. bufferCount
  44995. } );
  44996. }
  44997. return name;
  44998. }
  44999. /**
  45000. * Returns the scoped arrays of the given shader stage as a WGSL string.
  45001. *
  45002. * @param {String} shaderStage - The shader stage.
  45003. * @return {String|undefined} The WGSL snippet that defines the scoped arrays.
  45004. * Returns `undefined` when used in the vertex or fragment stage.
  45005. */
  45006. getScopedArrays( shaderStage ) {
  45007. if ( shaderStage !== 'compute' ) {
  45008. return;
  45009. }
  45010. const snippets = [];
  45011. for ( const { name, scope, bufferType, bufferCount } of this.scopedArrays.values() ) {
  45012. const type = this.getType( bufferType );
  45013. snippets.push( `var<${scope}> ${name}: array< ${type}, ${bufferCount} >;` );
  45014. }
  45015. return snippets.join( '\n' );
  45016. }
  45017. /**
  45018. * Returns the shader attributes of the given shader stage as a WGSL string.
  45019. *
  45020. * @param {String} shaderStage - The shader stage.
  45021. * @return {String} The WGSL snippet that defines the shader attributes.
  45022. */
  45023. getAttributes( shaderStage ) {
  45024. const snippets = [];
  45025. if ( shaderStage === 'compute' ) {
  45026. this.getBuiltin( 'global_invocation_id', 'globalId', 'vec3<u32>', 'attribute' );
  45027. this.getBuiltin( 'workgroup_id', 'workgroupId', 'vec3<u32>', 'attribute' );
  45028. this.getBuiltin( 'local_invocation_id', 'localId', 'vec3<u32>', 'attribute' );
  45029. this.getBuiltin( 'num_workgroups', 'numWorkgroups', 'vec3<u32>', 'attribute' );
  45030. if ( this.renderer.hasFeature( 'subgroups' ) ) {
  45031. this.enableDirective( 'subgroups', shaderStage );
  45032. this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  45033. }
  45034. }
  45035. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  45036. const builtins = this.getBuiltins( 'attribute' );
  45037. if ( builtins ) snippets.push( builtins );
  45038. const attributes = this.getAttributesArray();
  45039. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  45040. const attribute = attributes[ index ];
  45041. const name = attribute.name;
  45042. const type = this.getType( attribute.type );
  45043. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  45044. }
  45045. }
  45046. return snippets.join( ',\n\t' );
  45047. }
  45048. /**
  45049. * Returns the members of the given struct type node as a WGSL string.
  45050. *
  45051. * @param {StructTypeNode} struct - The struct type node.
  45052. * @return {String} The WGSL snippet that defines the struct members.
  45053. */
  45054. getStructMembers( struct ) {
  45055. const snippets = [];
  45056. const members = struct.getMemberTypes();
  45057. for ( let i = 0; i < members.length; i ++ ) {
  45058. const member = members[ i ];
  45059. snippets.push( `\t@location( ${i} ) m${i} : ${ member }<f32>` );
  45060. }
  45061. const builtins = this.getBuiltins( 'output' );
  45062. if ( builtins ) snippets.push( '\t' + builtins );
  45063. return snippets.join( ',\n' );
  45064. }
  45065. /**
  45066. * Returns the structs of the given shader stage as a WGSL string.
  45067. *
  45068. * @param {String} shaderStage - The shader stage.
  45069. * @return {String} The WGSL snippet that defines the structs.
  45070. */
  45071. getStructs( shaderStage ) {
  45072. const snippets = [];
  45073. const structs = this.structs[ shaderStage ];
  45074. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  45075. const struct = structs[ index ];
  45076. const name = struct.name;
  45077. let snippet = `\struct ${ name } {\n`;
  45078. snippet += this.getStructMembers( struct );
  45079. snippet += '\n}';
  45080. snippets.push( snippet );
  45081. snippets.push( `\nvar<private> output : ${ name };\n\n` );
  45082. }
  45083. return snippets.join( '\n\n' );
  45084. }
  45085. /**
  45086. * Returns a WGSL string representing a variable.
  45087. *
  45088. * @param {String} type - The variable's type.
  45089. * @param {String} name - The variable's name.
  45090. * @param {Number?} [count=null] - The array length.
  45091. * @return {String} The WGSL snippet that defines a variable.
  45092. */
  45093. getVar( type, name, count = null ) {
  45094. let snippet = `var ${ name } : `;
  45095. if ( count !== null ) {
  45096. snippet += this.generateArrayDeclaration( type, count );
  45097. } else {
  45098. snippet += this.getType( type );
  45099. }
  45100. return snippet;
  45101. }
  45102. /**
  45103. * Returns the variables of the given shader stage as a WGSL string.
  45104. *
  45105. * @param {String} shaderStage - The shader stage.
  45106. * @return {String} The WGSL snippet that defines the variables.
  45107. */
  45108. getVars( shaderStage ) {
  45109. const snippets = [];
  45110. const vars = this.vars[ shaderStage ];
  45111. if ( vars !== undefined ) {
  45112. for ( const variable of vars ) {
  45113. snippets.push( `\t${ this.getVar( variable.type, variable.name, variable.count ) };` );
  45114. }
  45115. }
  45116. return `\n${ snippets.join( '\n' ) }\n`;
  45117. }
  45118. /**
  45119. * Returns the varyings of the given shader stage as a WGSL string.
  45120. *
  45121. * @param {String} shaderStage - The shader stage.
  45122. * @return {String} The WGSL snippet that defines the varyings.
  45123. */
  45124. getVaryings( shaderStage ) {
  45125. const snippets = [];
  45126. if ( shaderStage === 'vertex' ) {
  45127. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  45128. }
  45129. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  45130. const varyings = this.varyings;
  45131. const vars = this.vars[ shaderStage ];
  45132. for ( let index = 0; index < varyings.length; index ++ ) {
  45133. const varying = varyings[ index ];
  45134. if ( varying.needsInterpolation ) {
  45135. let attributesSnippet = `@location( ${index} )`;
  45136. if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  45137. attributesSnippet += ' @interpolate( flat )';
  45138. }
  45139. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  45140. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  45141. vars.push( varying );
  45142. }
  45143. }
  45144. }
  45145. const builtins = this.getBuiltins( shaderStage );
  45146. if ( builtins ) snippets.push( builtins );
  45147. const code = snippets.join( ',\n\t' );
  45148. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  45149. }
  45150. /**
  45151. * Returns the uniforms of the given shader stage as a WGSL string.
  45152. *
  45153. * @param {String} shaderStage - The shader stage.
  45154. * @return {String} The WGSL snippet that defines the uniforms.
  45155. */
  45156. getUniforms( shaderStage ) {
  45157. const uniforms = this.uniforms[ shaderStage ];
  45158. const bindingSnippets = [];
  45159. const bufferSnippets = [];
  45160. const structSnippets = [];
  45161. const uniformGroups = {};
  45162. for ( const uniform of uniforms ) {
  45163. const groupName = uniform.groupNode.name;
  45164. const uniformIndexes = this.bindingsIndexes[ groupName ];
  45165. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  45166. const texture = uniform.node.value;
  45167. if ( ( shaderStage === 'fragment' || shaderStage === 'compute' ) && this.isUnfilterable( texture ) === false && uniform.node.isStorageTextureNode !== true ) {
  45168. if ( this.isSampleCompare( texture ) ) {
  45169. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  45170. } else {
  45171. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  45172. }
  45173. }
  45174. let textureType;
  45175. let multisampled = '';
  45176. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  45177. if ( primarySamples > 1 ) {
  45178. multisampled = '_multisampled';
  45179. }
  45180. if ( texture.isCubeTexture === true ) {
  45181. textureType = 'texture_cube<f32>';
  45182. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  45183. textureType = 'texture_2d_array<f32>';
  45184. } else if ( texture.isDepthTexture === true ) {
  45185. textureType = `texture_depth${multisampled}_2d`;
  45186. } else if ( texture.isVideoTexture === true ) {
  45187. textureType = 'texture_external';
  45188. } else if ( texture.isData3DTexture === true ) {
  45189. textureType = 'texture_3d<f32>';
  45190. } else if ( uniform.node.isStorageTextureNode === true ) {
  45191. const format = getFormat( texture );
  45192. const access = this.getStorageAccess( uniform.node, shaderStage );
  45193. textureType = `texture_storage_2d<${ format }, ${ access }>`;
  45194. } else {
  45195. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  45196. textureType = `texture${multisampled}_2d<${ componentPrefix }32>`;
  45197. }
  45198. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  45199. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' || uniform.type === 'indirectStorageBuffer' ) {
  45200. const bufferNode = uniform.node;
  45201. const bufferType = this.getType( bufferNode.bufferType );
  45202. const bufferCount = bufferNode.bufferCount;
  45203. const bufferCountSnippet = bufferCount > 0 && uniform.type === 'buffer' ? ', ' + bufferCount : '';
  45204. const bufferTypeSnippet = bufferNode.isAtomic ? `atomic<${bufferType}>` : `${bufferType}`;
  45205. const bufferSnippet = `\t${ uniform.name } : array< ${ bufferTypeSnippet }${ bufferCountSnippet } >\n`;
  45206. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode, shaderStage ) }` : 'uniform';
  45207. bufferSnippets.push( this._getWGSLStructBinding( 'NodeBuffer_' + bufferNode.id, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  45208. } else {
  45209. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  45210. const groupName = uniform.groupNode.name;
  45211. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  45212. index: uniformIndexes.binding ++,
  45213. id: uniformIndexes.group,
  45214. snippets: []
  45215. } );
  45216. group.snippets.push( `\t${ uniform.name } : ${ vectorType }` );
  45217. }
  45218. }
  45219. for ( const name in uniformGroups ) {
  45220. const group = uniformGroups[ name ];
  45221. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  45222. }
  45223. let code = bindingSnippets.join( '\n' );
  45224. code += bufferSnippets.join( '\n' );
  45225. code += structSnippets.join( '\n' );
  45226. return code;
  45227. }
  45228. /**
  45229. * Controls the code build of the shader stages.
  45230. */
  45231. buildCode() {
  45232. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  45233. this.sortBindingGroups();
  45234. for ( const shaderStage in shadersData ) {
  45235. const stageData = shadersData[ shaderStage ];
  45236. stageData.uniforms = this.getUniforms( shaderStage );
  45237. stageData.attributes = this.getAttributes( shaderStage );
  45238. stageData.varyings = this.getVaryings( shaderStage );
  45239. stageData.structs = this.getStructs( shaderStage );
  45240. stageData.vars = this.getVars( shaderStage );
  45241. stageData.codes = this.getCodes( shaderStage );
  45242. stageData.directives = this.getDirectives( shaderStage );
  45243. stageData.scopedArrays = this.getScopedArrays( shaderStage );
  45244. //
  45245. let flow = '// code\n\n';
  45246. flow += this.flowCode[ shaderStage ];
  45247. const flowNodes = this.flowNodes[ shaderStage ];
  45248. const mainNode = flowNodes[ flowNodes.length - 1 ];
  45249. const outputNode = mainNode.outputNode;
  45250. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  45251. for ( const node of flowNodes ) {
  45252. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  45253. const slotName = node.name;
  45254. if ( slotName ) {
  45255. if ( flow.length > 0 ) flow += '\n';
  45256. flow += `\t// flow -> ${ slotName }\n`;
  45257. }
  45258. flow += `${ flowSlotData.code }\n\t`;
  45259. if ( node === mainNode && shaderStage !== 'compute' ) {
  45260. flow += '// result\n\n\t';
  45261. if ( shaderStage === 'vertex' ) {
  45262. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  45263. } else if ( shaderStage === 'fragment' ) {
  45264. if ( isOutputStruct ) {
  45265. stageData.returnType = outputNode.nodeType;
  45266. flow += `return ${ flowSlotData.result };`;
  45267. } else {
  45268. let structSnippet = '\t@location(0) color: vec4<f32>';
  45269. const builtins = this.getBuiltins( 'output' );
  45270. if ( builtins ) structSnippet += ',\n\t' + builtins;
  45271. stageData.returnType = 'OutputStruct';
  45272. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  45273. stageData.structs += '\nvar<private> output : OutputStruct;\n\n';
  45274. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  45275. }
  45276. }
  45277. }
  45278. }
  45279. stageData.flow = flow;
  45280. }
  45281. if ( this.material !== null ) {
  45282. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  45283. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  45284. } else {
  45285. this.computeShader = this._getWGSLComputeCode( shadersData.compute, ( this.object.workgroupSize || [ 64 ] ).join( ', ' ) );
  45286. }
  45287. }
  45288. /**
  45289. * Returns the native shader method name for a given generic name.
  45290. *
  45291. * @param {String} method - The method name to resolve.
  45292. * @param {String} [output=null] - An optional output.
  45293. * @return {String} The resolved WGSL method name.
  45294. */
  45295. getMethod( method, output = null ) {
  45296. let wgslMethod;
  45297. if ( output !== null ) {
  45298. wgslMethod = this._getWGSLMethod( method + '_' + output );
  45299. }
  45300. if ( wgslMethod === undefined ) {
  45301. wgslMethod = this._getWGSLMethod( method );
  45302. }
  45303. return wgslMethod || method;
  45304. }
  45305. /**
  45306. * Returns the WGSL type of the given node data type.
  45307. *
  45308. * @param {String} type - The node data type.
  45309. * @return {String} The WGSL type.
  45310. */
  45311. getType( type ) {
  45312. return wgslTypeLib[ type ] || type;
  45313. }
  45314. /**
  45315. * Whether the requested feature is available or not.
  45316. *
  45317. * @param {String} name - The requested feature.
  45318. * @return {Boolean} Whether the requested feature is supported or not.
  45319. */
  45320. isAvailable( name ) {
  45321. let result = supports[ name ];
  45322. if ( result === undefined ) {
  45323. if ( name === 'float32Filterable' ) {
  45324. result = this.renderer.hasFeature( 'float32-filterable' );
  45325. } else if ( name === 'clipDistance' ) {
  45326. result = this.renderer.hasFeature( 'clip-distances' );
  45327. }
  45328. supports[ name ] = result;
  45329. }
  45330. return result;
  45331. }
  45332. /**
  45333. * Returns the native shader method name for a given generic name.
  45334. *
  45335. * @private
  45336. * @param {String} method - The method name to resolve.
  45337. * @return {String} The resolved WGSL method name.
  45338. */
  45339. _getWGSLMethod( method ) {
  45340. if ( wgslPolyfill[ method ] !== undefined ) {
  45341. this._include( method );
  45342. }
  45343. return wgslMethods[ method ];
  45344. }
  45345. /**
  45346. * Includes the given method name into the current
  45347. * function node.
  45348. *
  45349. * @private
  45350. * @param {String} name - The method name to include.
  45351. * @return {CodeNode} The respective code node.
  45352. */
  45353. _include( name ) {
  45354. const codeNode = wgslPolyfill[ name ];
  45355. codeNode.build( this );
  45356. if ( this.currentFunctionNode !== null ) {
  45357. this.currentFunctionNode.includes.push( codeNode );
  45358. }
  45359. return codeNode;
  45360. }
  45361. /**
  45362. * Returns a WGSL vertex shader based on the given shader data.
  45363. *
  45364. * @private
  45365. * @param {Object} shaderData - The shader data.
  45366. * @return {String} The vertex shader.
  45367. */
  45368. _getWGSLVertexCode( shaderData ) {
  45369. return `${ this.getSignature() }
  45370. // directives
  45371. ${shaderData.directives}
  45372. // uniforms
  45373. ${shaderData.uniforms}
  45374. // varyings
  45375. ${shaderData.varyings}
  45376. var<private> varyings : VaryingsStruct;
  45377. // codes
  45378. ${shaderData.codes}
  45379. @vertex
  45380. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  45381. // vars
  45382. ${shaderData.vars}
  45383. // flow
  45384. ${shaderData.flow}
  45385. return varyings;
  45386. }
  45387. `;
  45388. }
  45389. /**
  45390. * Returns a WGSL fragment shader based on the given shader data.
  45391. *
  45392. * @private
  45393. * @param {Object} shaderData - The shader data.
  45394. * @return {String} The vertex shader.
  45395. */
  45396. _getWGSLFragmentCode( shaderData ) {
  45397. return `${ this.getSignature() }
  45398. // global
  45399. ${ diagnostics }
  45400. // uniforms
  45401. ${shaderData.uniforms}
  45402. // structs
  45403. ${shaderData.structs}
  45404. // codes
  45405. ${shaderData.codes}
  45406. @fragment
  45407. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  45408. // vars
  45409. ${shaderData.vars}
  45410. // flow
  45411. ${shaderData.flow}
  45412. }
  45413. `;
  45414. }
  45415. /**
  45416. * Returns a WGSL compute shader based on the given shader data.
  45417. *
  45418. * @private
  45419. * @param {Object} shaderData - The shader data.
  45420. * @param {String} workgroupSize - The workgroup size.
  45421. * @return {String} The vertex shader.
  45422. */
  45423. _getWGSLComputeCode( shaderData, workgroupSize ) {
  45424. return `${ this.getSignature() }
  45425. // directives
  45426. ${shaderData.directives}
  45427. // system
  45428. var<private> instanceIndex : u32;
  45429. // locals
  45430. ${shaderData.scopedArrays}
  45431. // uniforms
  45432. ${shaderData.uniforms}
  45433. // codes
  45434. ${shaderData.codes}
  45435. @compute @workgroup_size( ${workgroupSize} )
  45436. fn main( ${shaderData.attributes} ) {
  45437. // system
  45438. instanceIndex = globalId.x + globalId.y * numWorkgroups.x * u32(${workgroupSize}) + globalId.z * numWorkgroups.x * numWorkgroups.y * u32(${workgroupSize});
  45439. // vars
  45440. ${shaderData.vars}
  45441. // flow
  45442. ${shaderData.flow}
  45443. }
  45444. `;
  45445. }
  45446. /**
  45447. * Returns a WGSL struct based on the given name and variables.
  45448. *
  45449. * @private
  45450. * @param {String} name - The struct name.
  45451. * @param {String} vars - The struct variables.
  45452. * @return {String} The WGSL snippet representing a struct.
  45453. */
  45454. _getWGSLStruct( name, vars ) {
  45455. return `
  45456. struct ${name} {
  45457. ${vars}
  45458. };`;
  45459. }
  45460. /**
  45461. * Returns a WGSL struct binding.
  45462. *
  45463. * @private
  45464. * @param {String} name - The struct name.
  45465. * @param {String} vars - The struct variables.
  45466. * @param {String} access - The access.
  45467. * @param {Number} [binding=0] - The binding index.
  45468. * @param {Number} [group=0] - The group index.
  45469. * @return {String} The WGSL snippet representing a struct binding.
  45470. */
  45471. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  45472. const structName = name + 'Struct';
  45473. const structSnippet = this._getWGSLStruct( structName, vars );
  45474. return `${structSnippet}
  45475. @binding( ${binding} ) @group( ${group} )
  45476. var<${access}> ${name} : ${structName};`;
  45477. }
  45478. }
  45479. /**
  45480. * A WebGPU backend utility module with common helpers.
  45481. *
  45482. * @private
  45483. */
  45484. class WebGPUUtils {
  45485. /**
  45486. * Constructs a new utility object.
  45487. *
  45488. * @param {WebGPUBackend} backend - The WebGPU backend.
  45489. */
  45490. constructor( backend ) {
  45491. /**
  45492. * A reference to the WebGPU backend.
  45493. *
  45494. * @type {WebGPUBackend}
  45495. */
  45496. this.backend = backend;
  45497. }
  45498. /**
  45499. * Returns the depth/stencil GPU format for the given render context.
  45500. *
  45501. * @param {RenderContext} renderContext - The render context.
  45502. * @return {String} The depth/stencil GPU texture format.
  45503. */
  45504. getCurrentDepthStencilFormat( renderContext ) {
  45505. let format;
  45506. if ( renderContext.depthTexture !== null ) {
  45507. format = this.getTextureFormatGPU( renderContext.depthTexture );
  45508. } else if ( renderContext.depth && renderContext.stencil ) {
  45509. format = GPUTextureFormat.Depth24PlusStencil8;
  45510. } else if ( renderContext.depth ) {
  45511. format = GPUTextureFormat.Depth24Plus;
  45512. }
  45513. return format;
  45514. }
  45515. /**
  45516. * Returns the GPU format for the given texture.
  45517. *
  45518. * @param {Texture} texture - The texture.
  45519. * @return {String} The GPU texture format.
  45520. */
  45521. getTextureFormatGPU( texture ) {
  45522. return this.backend.get( texture ).format;
  45523. }
  45524. /**
  45525. * Returns an object that defines the multi-sampling state of the given texture.
  45526. *
  45527. * @param {Texture} texture - The texture.
  45528. * @return {Object} The multi-sampling state.
  45529. */
  45530. getTextureSampleData( texture ) {
  45531. let samples;
  45532. if ( texture.isFramebufferTexture ) {
  45533. samples = 1;
  45534. } else if ( texture.isDepthTexture && ! texture.renderTarget ) {
  45535. const renderer = this.backend.renderer;
  45536. const renderTarget = renderer.getRenderTarget();
  45537. samples = renderTarget ? renderTarget.samples : renderer.samples;
  45538. } else if ( texture.renderTarget ) {
  45539. samples = texture.renderTarget.samples;
  45540. }
  45541. samples = samples || 1;
  45542. const isMSAA = samples > 1 && texture.renderTarget !== null && ( texture.isDepthTexture !== true && texture.isFramebufferTexture !== true );
  45543. const primarySamples = isMSAA ? 1 : samples;
  45544. return { samples, primarySamples, isMSAA };
  45545. }
  45546. /**
  45547. * Returns the default color attachment's GPU format of the current render context.
  45548. *
  45549. * @param {RenderContext} renderContext - The render context.
  45550. * @return {String} The GPU texture format of the default color attachment.
  45551. */
  45552. getCurrentColorFormat( renderContext ) {
  45553. let format;
  45554. if ( renderContext.textures !== null ) {
  45555. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  45556. } else {
  45557. format = this.getPreferredCanvasFormat(); // default context format
  45558. }
  45559. return format;
  45560. }
  45561. /**
  45562. * Returns the output color space of the current render context.
  45563. *
  45564. * @param {RenderContext} renderContext - The render context.
  45565. * @return {String} The output color space.
  45566. */
  45567. getCurrentColorSpace( renderContext ) {
  45568. if ( renderContext.textures !== null ) {
  45569. return renderContext.textures[ 0 ].colorSpace;
  45570. }
  45571. return this.backend.renderer.outputColorSpace;
  45572. }
  45573. /**
  45574. * Returns GPU primitive topology for the given object and material.
  45575. *
  45576. * @param {Object3D} object - The 3D object.
  45577. * @param {Material} material - The material.
  45578. * @return {String} The GPU primitive topology.
  45579. */
  45580. getPrimitiveTopology( object, material ) {
  45581. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  45582. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  45583. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  45584. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  45585. }
  45586. /**
  45587. * Returns a modified sample count from the given sample count value.
  45588. *
  45589. * That is required since WebGPU does not support arbitrary sample counts.
  45590. *
  45591. * @param {Number} sampleCount - The input sample count.
  45592. * @return {Number} The (potentially updated) output sample count.
  45593. */
  45594. getSampleCount( sampleCount ) {
  45595. let count = 1;
  45596. if ( sampleCount > 1 ) {
  45597. // WebGPU only supports power-of-two sample counts and 2 is not a valid value
  45598. count = Math.pow( 2, Math.floor( Math.log2( sampleCount ) ) );
  45599. if ( count === 2 ) {
  45600. count = 4;
  45601. }
  45602. }
  45603. return count;
  45604. }
  45605. /**
  45606. * Returns the sample count of the given render context.
  45607. *
  45608. * @param {RenderContext} renderContext - The render context.
  45609. * @return {Number} The sample count.
  45610. */
  45611. getSampleCountRenderContext( renderContext ) {
  45612. if ( renderContext.textures !== null ) {
  45613. return this.getSampleCount( renderContext.sampleCount );
  45614. }
  45615. return this.getSampleCount( this.backend.renderer.samples );
  45616. }
  45617. /**
  45618. * Returns the preferred canvas format.
  45619. *
  45620. * There is a separate method for this so it's possible to
  45621. * honor edge cases for specific devices.
  45622. *
  45623. * @return {String} The GPU texture format of the canvas.
  45624. */
  45625. getPreferredCanvasFormat() {
  45626. const outputType = this.backend.parameters.outputType;
  45627. if ( outputType === undefined ) {
  45628. return navigator.gpu.getPreferredCanvasFormat();
  45629. } else if ( outputType === UnsignedByteType ) {
  45630. return GPUTextureFormat.BGRA8Unorm;
  45631. } else if ( outputType === HalfFloatType ) {
  45632. return GPUTextureFormat.RGBA16Float;
  45633. } else {
  45634. throw new Error( 'Unsupported outputType' );
  45635. }
  45636. }
  45637. }
  45638. const typedArraysToVertexFormatPrefix = new Map( [
  45639. [ Int8Array, [ 'sint8', 'snorm8' ]],
  45640. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  45641. [ Int16Array, [ 'sint16', 'snorm16' ]],
  45642. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  45643. [ Int32Array, [ 'sint32', 'snorm32' ]],
  45644. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  45645. [ Float32Array, [ 'float32', ]],
  45646. ] );
  45647. const typedAttributeToVertexFormatPrefix = new Map( [
  45648. [ Float16BufferAttribute, [ 'float16', ]],
  45649. ] );
  45650. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  45651. [ Int32Array, 'sint32' ],
  45652. [ Int16Array, 'sint32' ], // patch for INT16
  45653. [ Uint32Array, 'uint32' ],
  45654. [ Uint16Array, 'uint32' ], // patch for UINT16
  45655. [ Float32Array, 'float32' ]
  45656. ] );
  45657. /**
  45658. * A WebGPU backend utility module for managing shader attributes.
  45659. *
  45660. * @private
  45661. */
  45662. class WebGPUAttributeUtils {
  45663. /**
  45664. * Constructs a new utility object.
  45665. *
  45666. * @param {WebGPUBackend} backend - The WebGPU backend.
  45667. */
  45668. constructor( backend ) {
  45669. /**
  45670. * A reference to the WebGPU backend.
  45671. *
  45672. * @type {WebGPUBackend}
  45673. */
  45674. this.backend = backend;
  45675. }
  45676. /**
  45677. * Creates the GPU buffer for the given buffer attribute.
  45678. *
  45679. * @param {BufferAttribute} attribute - The buffer attribute.
  45680. * @param {GPUBufferUsage} usage - A flag that indicates how the buffer may be used after its creation.
  45681. */
  45682. createAttribute( attribute, usage ) {
  45683. const bufferAttribute = this._getBufferAttribute( attribute );
  45684. const backend = this.backend;
  45685. const bufferData = backend.get( bufferAttribute );
  45686. let buffer = bufferData.buffer;
  45687. if ( buffer === undefined ) {
  45688. const device = backend.device;
  45689. let array = bufferAttribute.array;
  45690. // patch for INT16 and UINT16
  45691. if ( attribute.normalized === false ) {
  45692. if ( array.constructor === Int16Array ) {
  45693. array = new Int32Array( array );
  45694. } else if ( array.constructor === Uint16Array ) {
  45695. array = new Uint32Array( array );
  45696. if ( usage & GPUBufferUsage.INDEX ) {
  45697. for ( let i = 0; i < array.length; i ++ ) {
  45698. if ( array[ i ] === 0xffff ) array[ i ] = 0xffffffff; // use correct primitive restart index
  45699. }
  45700. }
  45701. }
  45702. }
  45703. bufferAttribute.array = array;
  45704. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  45705. array = new array.constructor( bufferAttribute.count * 4 );
  45706. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  45707. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  45708. }
  45709. // Update BufferAttribute
  45710. bufferAttribute.itemSize = 4;
  45711. bufferAttribute.array = array;
  45712. }
  45713. const size = array.byteLength + ( ( 4 - ( array.byteLength % 4 ) ) % 4 ); // ensure 4 byte alignment, see #20441
  45714. buffer = device.createBuffer( {
  45715. label: bufferAttribute.name,
  45716. size: size,
  45717. usage: usage,
  45718. mappedAtCreation: true
  45719. } );
  45720. new array.constructor( buffer.getMappedRange() ).set( array );
  45721. buffer.unmap();
  45722. bufferData.buffer = buffer;
  45723. }
  45724. }
  45725. /**
  45726. * Updates the GPU buffer of the given buffer attribute.
  45727. *
  45728. * @param {BufferAttribute} attribute - The buffer attribute.
  45729. */
  45730. updateAttribute( attribute ) {
  45731. const bufferAttribute = this._getBufferAttribute( attribute );
  45732. const backend = this.backend;
  45733. const device = backend.device;
  45734. const buffer = backend.get( bufferAttribute ).buffer;
  45735. const array = bufferAttribute.array;
  45736. const isTypedArray = this._isTypedArray( array );
  45737. const updateRanges = bufferAttribute.updateRanges;
  45738. if ( updateRanges.length === 0 ) {
  45739. // Not using update ranges
  45740. device.queue.writeBuffer(
  45741. buffer,
  45742. 0,
  45743. array,
  45744. 0
  45745. );
  45746. } else {
  45747. const byteOffsetFactor = isTypedArray ? 1 : array.BYTES_PER_ELEMENT;
  45748. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  45749. const range = updateRanges[ i ];
  45750. const dataOffset = range.start * byteOffsetFactor;
  45751. const size = range.count * byteOffsetFactor;
  45752. device.queue.writeBuffer(
  45753. buffer,
  45754. 0,
  45755. array,
  45756. dataOffset,
  45757. size
  45758. );
  45759. }
  45760. bufferAttribute.clearUpdateRanges();
  45761. }
  45762. }
  45763. /**
  45764. * This method creates the vertex buffer layout data which are
  45765. * require when creating a render pipeline for the given render object.
  45766. *
  45767. * @param {RenderObject} renderObject - The render object.
  45768. * @return {Array<Object>} An array holding objects which describe the vertex buffer layout.
  45769. */
  45770. createShaderVertexBuffers( renderObject ) {
  45771. const attributes = renderObject.getAttributes();
  45772. const vertexBuffers = new Map();
  45773. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  45774. const geometryAttribute = attributes[ slot ];
  45775. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  45776. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  45777. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  45778. if ( vertexBufferLayout === undefined ) {
  45779. let arrayStride, stepMode;
  45780. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  45781. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  45782. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  45783. } else {
  45784. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  45785. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  45786. }
  45787. // patch for INT16 and UINT16
  45788. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  45789. arrayStride = 4;
  45790. }
  45791. vertexBufferLayout = {
  45792. arrayStride,
  45793. attributes: [],
  45794. stepMode
  45795. };
  45796. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  45797. }
  45798. const format = this._getVertexFormat( geometryAttribute );
  45799. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  45800. vertexBufferLayout.attributes.push( {
  45801. shaderLocation: slot,
  45802. offset,
  45803. format
  45804. } );
  45805. }
  45806. return Array.from( vertexBuffers.values() );
  45807. }
  45808. /**
  45809. * Destroys the GPU buffer of the given buffer attribute.
  45810. *
  45811. * @param {BufferAttribute} attribute - The buffer attribute.
  45812. */
  45813. destroyAttribute( attribute ) {
  45814. const backend = this.backend;
  45815. const data = backend.get( this._getBufferAttribute( attribute ) );
  45816. data.buffer.destroy();
  45817. backend.delete( attribute );
  45818. }
  45819. /**
  45820. * This method performs a readback operation by moving buffer data from
  45821. * a storage buffer attribute from the GPU to the CPU.
  45822. *
  45823. * @async
  45824. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  45825. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  45826. */
  45827. async getArrayBufferAsync( attribute ) {
  45828. const backend = this.backend;
  45829. const device = backend.device;
  45830. const data = backend.get( this._getBufferAttribute( attribute ) );
  45831. const bufferGPU = data.buffer;
  45832. const size = bufferGPU.size;
  45833. const readBufferGPU = device.createBuffer( {
  45834. label: `${ attribute.name }_readback`,
  45835. size,
  45836. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  45837. } );
  45838. const cmdEncoder = device.createCommandEncoder( {
  45839. label: `readback_encoder_${ attribute.name }`
  45840. } );
  45841. cmdEncoder.copyBufferToBuffer(
  45842. bufferGPU,
  45843. 0,
  45844. readBufferGPU,
  45845. 0,
  45846. size
  45847. );
  45848. const gpuCommands = cmdEncoder.finish();
  45849. device.queue.submit( [ gpuCommands ] );
  45850. await readBufferGPU.mapAsync( GPUMapMode.READ );
  45851. const arrayBuffer = readBufferGPU.getMappedRange();
  45852. const dstBuffer = new attribute.array.constructor( arrayBuffer.slice( 0 ) );
  45853. readBufferGPU.unmap();
  45854. return dstBuffer.buffer;
  45855. }
  45856. /**
  45857. * Returns the vertex format of the given buffer attribute.
  45858. *
  45859. * @private
  45860. * @param {BufferAttribute} geometryAttribute - The buffer attribute.
  45861. * @return {String} The vertex format (e.g. 'float32x3').
  45862. */
  45863. _getVertexFormat( geometryAttribute ) {
  45864. const { itemSize, normalized } = geometryAttribute;
  45865. const ArrayType = geometryAttribute.array.constructor;
  45866. const AttributeType = geometryAttribute.constructor;
  45867. let format;
  45868. if ( itemSize === 1 ) {
  45869. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  45870. } else {
  45871. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  45872. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  45873. if ( prefix ) {
  45874. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  45875. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  45876. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  45877. if ( paddedItemSize % 1 ) {
  45878. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  45879. }
  45880. format = `${prefix}x${paddedItemSize}`;
  45881. }
  45882. }
  45883. if ( ! format ) {
  45884. console.error( 'THREE.WebGPUAttributeUtils: Vertex format not supported yet.' );
  45885. }
  45886. return format;
  45887. }
  45888. /**
  45889. * Returns `true` if the given array is a typed array.
  45890. *
  45891. * @private
  45892. * @param {Any} array - The array.
  45893. * @return {Boolean} Whether the given array is a typed array or not.
  45894. */
  45895. _isTypedArray( array ) {
  45896. return ArrayBuffer.isView( array ) && ! ( array instanceof DataView );
  45897. }
  45898. /**
  45899. * Utility method for handling interleaved buffer attributes correctly.
  45900. * To process them, their `InterleavedBuffer` is returned.
  45901. *
  45902. * @private
  45903. * @param {BufferAttribute} attribute - The attribute.
  45904. * @return {BufferAttribute|InterleavedBuffer}
  45905. */
  45906. _getBufferAttribute( attribute ) {
  45907. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  45908. return attribute;
  45909. }
  45910. }
  45911. /**
  45912. * A WebGPU backend utility module for managing bindings.
  45913. *
  45914. * When reading the documentation it's helpful to keep in mind that
  45915. * all class definitions starting with 'GPU*' are modules from the
  45916. * WebGPU API. So for example `BindGroup` is a class from the engine
  45917. * whereas `GPUBindGroup` is a class from WebGPU.
  45918. *
  45919. * @private
  45920. */
  45921. class WebGPUBindingUtils {
  45922. /**
  45923. * Constructs a new utility object.
  45924. *
  45925. * @param {WebGPUBackend} backend - The WebGPU backend.
  45926. */
  45927. constructor( backend ) {
  45928. /**
  45929. * A reference to the WebGPU backend.
  45930. *
  45931. * @type {WebGPUBackend}
  45932. */
  45933. this.backend = backend;
  45934. /**
  45935. * A cache for managing bind group layouts.
  45936. *
  45937. * @type {WeakMap<Array<Binding>,GPUBindGroupLayout>}
  45938. */
  45939. this.bindGroupLayoutCache = new WeakMap();
  45940. }
  45941. /**
  45942. * Creates a GPU bind group layout for the given bind group.
  45943. *
  45944. * @param {BindGroup} bindGroup - The bind group.
  45945. * @return {GPUBindGroupLayout} The GPU bind group layout.
  45946. */
  45947. createBindingsLayout( bindGroup ) {
  45948. const backend = this.backend;
  45949. const device = backend.device;
  45950. const entries = [];
  45951. let index = 0;
  45952. for ( const binding of bindGroup.bindings ) {
  45953. const bindingGPU = {
  45954. binding: index ++,
  45955. visibility: binding.visibility
  45956. };
  45957. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  45958. const buffer = {}; // GPUBufferBindingLayout
  45959. if ( binding.isStorageBuffer ) {
  45960. if ( binding.visibility & 4 ) {
  45961. // compute
  45962. if ( binding.access === NodeAccess.READ_WRITE || binding.access === NodeAccess.WRITE_ONLY ) {
  45963. buffer.type = GPUBufferBindingType.Storage;
  45964. } else {
  45965. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  45966. }
  45967. } else {
  45968. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  45969. }
  45970. }
  45971. bindingGPU.buffer = buffer;
  45972. } else if ( binding.isSampler ) {
  45973. const sampler = {}; // GPUSamplerBindingLayout
  45974. if ( binding.texture.isDepthTexture ) {
  45975. if ( binding.texture.compareFunction !== null ) {
  45976. sampler.type = 'comparison';
  45977. }
  45978. }
  45979. bindingGPU.sampler = sampler;
  45980. } else if ( binding.isSampledTexture && binding.texture.isVideoTexture ) {
  45981. bindingGPU.externalTexture = {}; // GPUExternalTextureBindingLayout
  45982. } else if ( binding.isSampledTexture && binding.store ) {
  45983. const storageTexture = {}; // GPUStorageTextureBindingLayout
  45984. storageTexture.format = this.backend.get( binding.texture ).texture.format;
  45985. const access = binding.access;
  45986. if ( access === NodeAccess.READ_WRITE ) {
  45987. storageTexture.access = GPUStorageTextureAccess.ReadWrite;
  45988. } else if ( access === NodeAccess.WRITE_ONLY ) {
  45989. storageTexture.access = GPUStorageTextureAccess.WriteOnly;
  45990. } else {
  45991. storageTexture.access = GPUStorageTextureAccess.ReadOnly;
  45992. }
  45993. bindingGPU.storageTexture = storageTexture;
  45994. } else if ( binding.isSampledTexture ) {
  45995. const texture = {}; // GPUTextureBindingLayout
  45996. const { primarySamples } = backend.utils.getTextureSampleData( binding.texture );
  45997. if ( primarySamples > 1 ) {
  45998. texture.multisampled = true;
  45999. if ( ! binding.texture.isDepthTexture ) {
  46000. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  46001. }
  46002. }
  46003. if ( binding.texture.isDepthTexture ) {
  46004. texture.sampleType = GPUTextureSampleType.Depth;
  46005. } else if ( binding.texture.isDataTexture || binding.texture.isDataArrayTexture || binding.texture.isData3DTexture ) {
  46006. const type = binding.texture.type;
  46007. if ( type === IntType ) {
  46008. texture.sampleType = GPUTextureSampleType.SInt;
  46009. } else if ( type === UnsignedIntType ) {
  46010. texture.sampleType = GPUTextureSampleType.UInt;
  46011. } else if ( type === FloatType ) {
  46012. if ( this.backend.hasFeature( 'float32-filterable' ) ) {
  46013. texture.sampleType = GPUTextureSampleType.Float;
  46014. } else {
  46015. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  46016. }
  46017. }
  46018. }
  46019. if ( binding.isSampledCubeTexture ) {
  46020. texture.viewDimension = GPUTextureViewDimension.Cube;
  46021. } else if ( binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  46022. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  46023. } else if ( binding.isSampledTexture3D ) {
  46024. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  46025. }
  46026. bindingGPU.texture = texture;
  46027. } else {
  46028. console.error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  46029. }
  46030. entries.push( bindingGPU );
  46031. }
  46032. return device.createBindGroupLayout( { entries } );
  46033. }
  46034. /**
  46035. * Creates bindings from the given bind group definition.
  46036. *
  46037. * @param {BindGroup} bindGroup - The bind group.
  46038. * @param {Array<BindGroup>} bindings - Array of bind groups.
  46039. * @param {Number} cacheIndex - The cache index.
  46040. * @param {Number} version - The version.
  46041. */
  46042. createBindings( bindGroup, bindings, cacheIndex, version = 0 ) {
  46043. const { backend, bindGroupLayoutCache } = this;
  46044. const bindingsData = backend.get( bindGroup );
  46045. // setup (static) binding layout and (dynamic) binding group
  46046. let bindLayoutGPU = bindGroupLayoutCache.get( bindGroup.bindingsReference );
  46047. if ( bindLayoutGPU === undefined ) {
  46048. bindLayoutGPU = this.createBindingsLayout( bindGroup );
  46049. bindGroupLayoutCache.set( bindGroup.bindingsReference, bindLayoutGPU );
  46050. }
  46051. let bindGroupGPU;
  46052. if ( cacheIndex > 0 ) {
  46053. if ( bindingsData.groups === undefined ) {
  46054. bindingsData.groups = [];
  46055. bindingsData.versions = [];
  46056. }
  46057. if ( bindingsData.versions[ cacheIndex ] === version ) {
  46058. bindGroupGPU = bindingsData.groups[ cacheIndex ];
  46059. }
  46060. }
  46061. if ( bindGroupGPU === undefined ) {
  46062. bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  46063. if ( cacheIndex > 0 ) {
  46064. bindingsData.groups[ cacheIndex ] = bindGroupGPU;
  46065. bindingsData.versions[ cacheIndex ] = version;
  46066. }
  46067. }
  46068. bindingsData.group = bindGroupGPU;
  46069. bindingsData.layout = bindLayoutGPU;
  46070. }
  46071. /**
  46072. * Updates a buffer binding.
  46073. *
  46074. * @param {Buffer} binding - The buffer binding to update.
  46075. */
  46076. updateBinding( binding ) {
  46077. const backend = this.backend;
  46078. const device = backend.device;
  46079. const buffer = binding.buffer;
  46080. const bufferGPU = backend.get( binding ).buffer;
  46081. device.queue.writeBuffer( bufferGPU, 0, buffer, 0 );
  46082. }
  46083. /**
  46084. * Creates a GPU bind group for the camera index.
  46085. *
  46086. * @param {Uint32Array} data - The index data.
  46087. * @param {GPUBindGroupLayout} layout - The GPU bind group layout.
  46088. * @return {GPUBindGroup} The GPU bind group.
  46089. */
  46090. createBindGroupIndex( data, layout ) {
  46091. const backend = this.backend;
  46092. const device = backend.device;
  46093. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  46094. const index = data[ 0 ];
  46095. const buffer = device.createBuffer( {
  46096. label: 'bindingCameraIndex_' + index,
  46097. size: 16, // uint(4) * 4
  46098. usage: usage
  46099. } );
  46100. device.queue.writeBuffer( buffer, 0, data, 0 );
  46101. const entries = [ { binding: 0, resource: { buffer } } ];
  46102. return device.createBindGroup( {
  46103. label: 'bindGroupCameraIndex_' + index,
  46104. layout,
  46105. entries
  46106. } );
  46107. }
  46108. /**
  46109. * Creates a GPU bind group for the given bind group and GPU layout.
  46110. *
  46111. * @param {BindGroup} bindGroup - The bind group.
  46112. * @param {GPUBindGroupLayout} layoutGPU - The GPU bind group layout.
  46113. * @return {GPUBindGroup} The GPU bind group.
  46114. */
  46115. createBindGroup( bindGroup, layoutGPU ) {
  46116. const backend = this.backend;
  46117. const device = backend.device;
  46118. let bindingPoint = 0;
  46119. const entriesGPU = [];
  46120. for ( const binding of bindGroup.bindings ) {
  46121. if ( binding.isUniformBuffer ) {
  46122. const bindingData = backend.get( binding );
  46123. if ( bindingData.buffer === undefined ) {
  46124. const byteLength = binding.byteLength;
  46125. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  46126. const bufferGPU = device.createBuffer( {
  46127. label: 'bindingBuffer_' + binding.name,
  46128. size: byteLength,
  46129. usage: usage
  46130. } );
  46131. bindingData.buffer = bufferGPU;
  46132. }
  46133. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  46134. } else if ( binding.isStorageBuffer ) {
  46135. const bindingData = backend.get( binding );
  46136. if ( bindingData.buffer === undefined ) {
  46137. const attribute = binding.attribute;
  46138. //const usage = GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | /*GPUBufferUsage.COPY_SRC |*/ GPUBufferUsage.COPY_DST;
  46139. //backend.attributeUtils.createAttribute( attribute, usage ); // @TODO: Move it to universal renderer
  46140. bindingData.buffer = backend.get( attribute ).buffer;
  46141. }
  46142. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  46143. } else if ( binding.isSampler ) {
  46144. const textureGPU = backend.get( binding.texture );
  46145. entriesGPU.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  46146. } else if ( binding.isSampledTexture ) {
  46147. const textureData = backend.get( binding.texture );
  46148. let resourceGPU;
  46149. if ( textureData.externalTexture !== undefined ) {
  46150. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  46151. } else {
  46152. const mipLevelCount = binding.store ? 1 : textureData.texture.mipLevelCount;
  46153. const propertyName = `view-${ textureData.texture.width }-${ textureData.texture.height }-${ mipLevelCount }`;
  46154. resourceGPU = textureData[ propertyName ];
  46155. if ( resourceGPU === undefined ) {
  46156. const aspectGPU = GPUTextureAspect.All;
  46157. let dimensionViewGPU;
  46158. if ( binding.isSampledCubeTexture ) {
  46159. dimensionViewGPU = GPUTextureViewDimension.Cube;
  46160. } else if ( binding.isSampledTexture3D ) {
  46161. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  46162. } else if ( binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  46163. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  46164. } else {
  46165. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  46166. }
  46167. resourceGPU = textureData[ propertyName ] = textureData.texture.createView( { aspect: aspectGPU, dimension: dimensionViewGPU, mipLevelCount } );
  46168. }
  46169. }
  46170. entriesGPU.push( { binding: bindingPoint, resource: resourceGPU } );
  46171. }
  46172. bindingPoint ++;
  46173. }
  46174. return device.createBindGroup( {
  46175. label: 'bindGroup_' + bindGroup.name,
  46176. layout: layoutGPU,
  46177. entries: entriesGPU
  46178. } );
  46179. }
  46180. }
  46181. /**
  46182. * A WebGPU backend utility module for managing pipelines.
  46183. *
  46184. * @private
  46185. */
  46186. class WebGPUPipelineUtils {
  46187. /**
  46188. * Constructs a new utility object.
  46189. *
  46190. * @param {WebGPUBackend} backend - The WebGPU backend.
  46191. */
  46192. constructor( backend ) {
  46193. /**
  46194. * A reference to the WebGPU backend.
  46195. *
  46196. * @type {WebGPUBackend}
  46197. */
  46198. this.backend = backend;
  46199. }
  46200. /**
  46201. * Returns the sample count derived from the given render context.
  46202. *
  46203. * @private
  46204. * @param {RenderContext} renderContext - The render context.
  46205. * @return {Number} The sample count.
  46206. */
  46207. _getSampleCount( renderContext ) {
  46208. return this.backend.utils.getSampleCountRenderContext( renderContext );
  46209. }
  46210. /**
  46211. * Creates a render pipeline for the given render object.
  46212. *
  46213. * @param {RenderObject} renderObject - The render object.
  46214. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  46215. */
  46216. createRenderPipeline( renderObject, promises ) {
  46217. const { object, material, geometry, pipeline } = renderObject;
  46218. const { vertexProgram, fragmentProgram } = pipeline;
  46219. const backend = this.backend;
  46220. const device = backend.device;
  46221. const utils = backend.utils;
  46222. const pipelineData = backend.get( pipeline );
  46223. // bind group layouts
  46224. const bindGroupLayouts = [];
  46225. for ( const bindGroup of renderObject.getBindings() ) {
  46226. const bindingsData = backend.get( bindGroup );
  46227. bindGroupLayouts.push( bindingsData.layout );
  46228. }
  46229. // vertex buffers
  46230. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  46231. // blending
  46232. let blending;
  46233. if ( material.transparent === true && material.blending !== NoBlending ) {
  46234. blending = this._getBlending( material );
  46235. }
  46236. // stencil
  46237. let stencilFront = {};
  46238. if ( material.stencilWrite === true ) {
  46239. stencilFront = {
  46240. compare: this._getStencilCompare( material ),
  46241. failOp: this._getStencilOperation( material.stencilFail ),
  46242. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  46243. passOp: this._getStencilOperation( material.stencilZPass )
  46244. };
  46245. }
  46246. const colorWriteMask = this._getColorWriteMask( material );
  46247. const targets = [];
  46248. if ( renderObject.context.textures !== null ) {
  46249. const textures = renderObject.context.textures;
  46250. for ( let i = 0; i < textures.length; i ++ ) {
  46251. const colorFormat = utils.getTextureFormatGPU( textures[ i ] );
  46252. targets.push( {
  46253. format: colorFormat,
  46254. blend: blending,
  46255. writeMask: colorWriteMask
  46256. } );
  46257. }
  46258. } else {
  46259. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  46260. targets.push( {
  46261. format: colorFormat,
  46262. blend: blending,
  46263. writeMask: colorWriteMask
  46264. } );
  46265. }
  46266. const vertexModule = backend.get( vertexProgram ).module;
  46267. const fragmentModule = backend.get( fragmentProgram ).module;
  46268. const primitiveState = this._getPrimitiveState( object, geometry, material );
  46269. const depthCompare = this._getDepthCompare( material );
  46270. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  46271. const sampleCount = this._getSampleCount( renderObject.context );
  46272. const pipelineDescriptor = {
  46273. label: `renderPipeline_${ material.name || material.type }_${ material.id }`,
  46274. vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ),
  46275. fragment: Object.assign( {}, fragmentModule, { targets } ),
  46276. primitive: primitiveState,
  46277. multisample: {
  46278. count: sampleCount,
  46279. alphaToCoverageEnabled: material.alphaToCoverage && sampleCount > 1
  46280. },
  46281. layout: device.createPipelineLayout( {
  46282. bindGroupLayouts
  46283. } )
  46284. };
  46285. const depthStencil = {};
  46286. const renderDepth = renderObject.context.depth;
  46287. const renderStencil = renderObject.context.stencil;
  46288. if ( renderDepth === true || renderStencil === true ) {
  46289. if ( renderDepth === true ) {
  46290. depthStencil.format = depthStencilFormat;
  46291. depthStencil.depthWriteEnabled = material.depthWrite;
  46292. depthStencil.depthCompare = depthCompare;
  46293. }
  46294. if ( renderStencil === true ) {
  46295. depthStencil.stencilFront = stencilFront;
  46296. depthStencil.stencilBack = {}; // three.js does not provide an API to configure the back function (gl.stencilFuncSeparate() was never used)
  46297. depthStencil.stencilReadMask = material.stencilFuncMask;
  46298. depthStencil.stencilWriteMask = material.stencilWriteMask;
  46299. }
  46300. pipelineDescriptor.depthStencil = depthStencil;
  46301. }
  46302. if ( promises === null ) {
  46303. pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor );
  46304. } else {
  46305. const p = new Promise( ( resolve /*, reject*/ ) => {
  46306. device.createRenderPipelineAsync( pipelineDescriptor ).then( pipeline => {
  46307. pipelineData.pipeline = pipeline;
  46308. resolve();
  46309. } );
  46310. } );
  46311. promises.push( p );
  46312. }
  46313. }
  46314. /**
  46315. * Creates GPU render bundle encoder for the given render context.
  46316. *
  46317. * @param {RenderContext} renderContext - The render context.
  46318. * @return {GPURenderBundleEncoder} The GPU render bundle encoder.
  46319. */
  46320. createBundleEncoder( renderContext ) {
  46321. const backend = this.backend;
  46322. const { utils, device } = backend;
  46323. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  46324. const colorFormat = utils.getCurrentColorFormat( renderContext );
  46325. const sampleCount = this._getSampleCount( renderContext );
  46326. const descriptor = {
  46327. label: 'renderBundleEncoder',
  46328. colorFormats: [ colorFormat ],
  46329. depthStencilFormat,
  46330. sampleCount
  46331. };
  46332. return device.createRenderBundleEncoder( descriptor );
  46333. }
  46334. /**
  46335. * Creates a compute pipeline for the given compute node.
  46336. *
  46337. * @param {ComputePipeline} pipeline - The compute pipeline.
  46338. * @param {Array<BindGroup>} bindings - The bindings.
  46339. */
  46340. createComputePipeline( pipeline, bindings ) {
  46341. const backend = this.backend;
  46342. const device = backend.device;
  46343. const computeProgram = backend.get( pipeline.computeProgram ).module;
  46344. const pipelineGPU = backend.get( pipeline );
  46345. // bind group layouts
  46346. const bindGroupLayouts = [];
  46347. for ( const bindingsGroup of bindings ) {
  46348. const bindingsData = backend.get( bindingsGroup );
  46349. bindGroupLayouts.push( bindingsData.layout );
  46350. }
  46351. pipelineGPU.pipeline = device.createComputePipeline( {
  46352. compute: computeProgram,
  46353. layout: device.createPipelineLayout( {
  46354. bindGroupLayouts
  46355. } )
  46356. } );
  46357. }
  46358. /**
  46359. * Returns the blending state as a descriptor object required
  46360. * for the pipeline creation.
  46361. *
  46362. * @private
  46363. * @param {Material} material - The material.
  46364. * @return {Object} The blending state.
  46365. */
  46366. _getBlending( material ) {
  46367. let color, alpha;
  46368. const blending = material.blending;
  46369. const blendSrc = material.blendSrc;
  46370. const blendDst = material.blendDst;
  46371. const blendEquation = material.blendEquation;
  46372. if ( blending === CustomBlending ) {
  46373. const blendSrcAlpha = material.blendSrcAlpha !== null ? material.blendSrcAlpha : blendSrc;
  46374. const blendDstAlpha = material.blendDstAlpha !== null ? material.blendDstAlpha : blendDst;
  46375. const blendEquationAlpha = material.blendEquationAlpha !== null ? material.blendEquationAlpha : blendEquation;
  46376. color = {
  46377. srcFactor: this._getBlendFactor( blendSrc ),
  46378. dstFactor: this._getBlendFactor( blendDst ),
  46379. operation: this._getBlendOperation( blendEquation )
  46380. };
  46381. alpha = {
  46382. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  46383. dstFactor: this._getBlendFactor( blendDstAlpha ),
  46384. operation: this._getBlendOperation( blendEquationAlpha )
  46385. };
  46386. } else {
  46387. const premultipliedAlpha = material.premultipliedAlpha;
  46388. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  46389. color = {
  46390. srcFactor: srcRGB,
  46391. dstFactor: dstRGB,
  46392. operation: GPUBlendOperation.Add
  46393. };
  46394. alpha = {
  46395. srcFactor: srcAlpha,
  46396. dstFactor: dstAlpha,
  46397. operation: GPUBlendOperation.Add
  46398. };
  46399. };
  46400. if ( premultipliedAlpha ) {
  46401. switch ( blending ) {
  46402. case NormalBlending:
  46403. setBlend( GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  46404. break;
  46405. case AdditiveBlending:
  46406. setBlend( GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  46407. break;
  46408. case SubtractiveBlending:
  46409. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  46410. break;
  46411. case MultiplyBlending:
  46412. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.SrcAlpha );
  46413. break;
  46414. }
  46415. } else {
  46416. switch ( blending ) {
  46417. case NormalBlending:
  46418. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  46419. break;
  46420. case AdditiveBlending:
  46421. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.SrcAlpha, GPUBlendFactor.One );
  46422. break;
  46423. case SubtractiveBlending:
  46424. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  46425. break;
  46426. case MultiplyBlending:
  46427. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.Src );
  46428. break;
  46429. }
  46430. }
  46431. }
  46432. if ( color !== undefined && alpha !== undefined ) {
  46433. return { color, alpha };
  46434. } else {
  46435. console.error( 'THREE.WebGPURenderer: Invalid blending: ', blending );
  46436. }
  46437. }
  46438. /**
  46439. * Returns the GPU blend factor which is required for the pipeline creation.
  46440. *
  46441. * @private
  46442. * @param {Number} blend - The blend factor as a three.js constant.
  46443. * @return {String} The GPU blend factor.
  46444. */
  46445. _getBlendFactor( blend ) {
  46446. let blendFactor;
  46447. switch ( blend ) {
  46448. case ZeroFactor:
  46449. blendFactor = GPUBlendFactor.Zero;
  46450. break;
  46451. case OneFactor:
  46452. blendFactor = GPUBlendFactor.One;
  46453. break;
  46454. case SrcColorFactor:
  46455. blendFactor = GPUBlendFactor.Src;
  46456. break;
  46457. case OneMinusSrcColorFactor:
  46458. blendFactor = GPUBlendFactor.OneMinusSrc;
  46459. break;
  46460. case SrcAlphaFactor:
  46461. blendFactor = GPUBlendFactor.SrcAlpha;
  46462. break;
  46463. case OneMinusSrcAlphaFactor:
  46464. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  46465. break;
  46466. case DstColorFactor:
  46467. blendFactor = GPUBlendFactor.Dst;
  46468. break;
  46469. case OneMinusDstColorFactor:
  46470. blendFactor = GPUBlendFactor.OneMinusDstColor;
  46471. break;
  46472. case DstAlphaFactor:
  46473. blendFactor = GPUBlendFactor.DstAlpha;
  46474. break;
  46475. case OneMinusDstAlphaFactor:
  46476. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  46477. break;
  46478. case SrcAlphaSaturateFactor:
  46479. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  46480. break;
  46481. case BlendColorFactor:
  46482. blendFactor = GPUBlendFactor.Constant;
  46483. break;
  46484. case OneMinusBlendColorFactor:
  46485. blendFactor = GPUBlendFactor.OneMinusConstant;
  46486. break;
  46487. default:
  46488. console.error( 'THREE.WebGPURenderer: Blend factor not supported.', blend );
  46489. }
  46490. return blendFactor;
  46491. }
  46492. /**
  46493. * Returns the GPU stencil compare function which is required for the pipeline creation.
  46494. *
  46495. * @private
  46496. * @param {Material} material - The material.
  46497. * @return {String} The GPU stencil compare function.
  46498. */
  46499. _getStencilCompare( material ) {
  46500. let stencilCompare;
  46501. const stencilFunc = material.stencilFunc;
  46502. switch ( stencilFunc ) {
  46503. case NeverStencilFunc:
  46504. stencilCompare = GPUCompareFunction.Never;
  46505. break;
  46506. case AlwaysStencilFunc:
  46507. stencilCompare = GPUCompareFunction.Always;
  46508. break;
  46509. case LessStencilFunc:
  46510. stencilCompare = GPUCompareFunction.Less;
  46511. break;
  46512. case LessEqualStencilFunc:
  46513. stencilCompare = GPUCompareFunction.LessEqual;
  46514. break;
  46515. case EqualStencilFunc:
  46516. stencilCompare = GPUCompareFunction.Equal;
  46517. break;
  46518. case GreaterEqualStencilFunc:
  46519. stencilCompare = GPUCompareFunction.GreaterEqual;
  46520. break;
  46521. case GreaterStencilFunc:
  46522. stencilCompare = GPUCompareFunction.Greater;
  46523. break;
  46524. case NotEqualStencilFunc:
  46525. stencilCompare = GPUCompareFunction.NotEqual;
  46526. break;
  46527. default:
  46528. console.error( 'THREE.WebGPURenderer: Invalid stencil function.', stencilFunc );
  46529. }
  46530. return stencilCompare;
  46531. }
  46532. /**
  46533. * Returns the GPU stencil operation which is required for the pipeline creation.
  46534. *
  46535. * @private
  46536. * @param {Number} op - A three.js constant defining the stencil operation.
  46537. * @return {String} The GPU stencil operation.
  46538. */
  46539. _getStencilOperation( op ) {
  46540. let stencilOperation;
  46541. switch ( op ) {
  46542. case KeepStencilOp:
  46543. stencilOperation = GPUStencilOperation.Keep;
  46544. break;
  46545. case ZeroStencilOp:
  46546. stencilOperation = GPUStencilOperation.Zero;
  46547. break;
  46548. case ReplaceStencilOp:
  46549. stencilOperation = GPUStencilOperation.Replace;
  46550. break;
  46551. case InvertStencilOp:
  46552. stencilOperation = GPUStencilOperation.Invert;
  46553. break;
  46554. case IncrementStencilOp:
  46555. stencilOperation = GPUStencilOperation.IncrementClamp;
  46556. break;
  46557. case DecrementStencilOp:
  46558. stencilOperation = GPUStencilOperation.DecrementClamp;
  46559. break;
  46560. case IncrementWrapStencilOp:
  46561. stencilOperation = GPUStencilOperation.IncrementWrap;
  46562. break;
  46563. case DecrementWrapStencilOp:
  46564. stencilOperation = GPUStencilOperation.DecrementWrap;
  46565. break;
  46566. default:
  46567. console.error( 'THREE.WebGPURenderer: Invalid stencil operation.', stencilOperation );
  46568. }
  46569. return stencilOperation;
  46570. }
  46571. /**
  46572. * Returns the GPU blend operation which is required for the pipeline creation.
  46573. *
  46574. * @private
  46575. * @param {Number} blendEquation - A three.js constant defining the blend equation.
  46576. * @return {String} The GPU blend operation.
  46577. */
  46578. _getBlendOperation( blendEquation ) {
  46579. let blendOperation;
  46580. switch ( blendEquation ) {
  46581. case AddEquation:
  46582. blendOperation = GPUBlendOperation.Add;
  46583. break;
  46584. case SubtractEquation:
  46585. blendOperation = GPUBlendOperation.Subtract;
  46586. break;
  46587. case ReverseSubtractEquation:
  46588. blendOperation = GPUBlendOperation.ReverseSubtract;
  46589. break;
  46590. case MinEquation:
  46591. blendOperation = GPUBlendOperation.Min;
  46592. break;
  46593. case MaxEquation:
  46594. blendOperation = GPUBlendOperation.Max;
  46595. break;
  46596. default:
  46597. console.error( 'THREE.WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  46598. }
  46599. return blendOperation;
  46600. }
  46601. /**
  46602. * Returns the primitive state as a descriptor object required
  46603. * for the pipeline creation.
  46604. *
  46605. * @private
  46606. * @param {Object3D} object - The 3D object.
  46607. * @param {BufferGeometry} geometry - The geometry.
  46608. * @param {Material} material - The material.
  46609. * @return {Object} The primitive state.
  46610. */
  46611. _getPrimitiveState( object, geometry, material ) {
  46612. const descriptor = {};
  46613. const utils = this.backend.utils;
  46614. descriptor.topology = utils.getPrimitiveTopology( object, material );
  46615. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  46616. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  46617. }
  46618. switch ( material.side ) {
  46619. case FrontSide:
  46620. descriptor.frontFace = GPUFrontFace.CCW;
  46621. descriptor.cullMode = GPUCullMode.Back;
  46622. break;
  46623. case BackSide:
  46624. descriptor.frontFace = GPUFrontFace.CCW;
  46625. descriptor.cullMode = GPUCullMode.Front;
  46626. break;
  46627. case DoubleSide:
  46628. descriptor.frontFace = GPUFrontFace.CCW;
  46629. descriptor.cullMode = GPUCullMode.None;
  46630. break;
  46631. default:
  46632. console.error( 'THREE.WebGPUPipelineUtils: Unknown material.side value.', material.side );
  46633. break;
  46634. }
  46635. return descriptor;
  46636. }
  46637. /**
  46638. * Returns the GPU color write mask which is required for the pipeline creation.
  46639. *
  46640. * @private
  46641. * @param {Material} material - The material.
  46642. * @return {String} The GPU color write mask.
  46643. */
  46644. _getColorWriteMask( material ) {
  46645. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  46646. }
  46647. /**
  46648. * Returns the GPU depth compare function which is required for the pipeline creation.
  46649. *
  46650. * @private
  46651. * @param {Material} material - The material.
  46652. * @return {String} The GPU depth compare function.
  46653. */
  46654. _getDepthCompare( material ) {
  46655. let depthCompare;
  46656. if ( material.depthTest === false ) {
  46657. depthCompare = GPUCompareFunction.Always;
  46658. } else {
  46659. const depthFunc = material.depthFunc;
  46660. switch ( depthFunc ) {
  46661. case NeverDepth:
  46662. depthCompare = GPUCompareFunction.Never;
  46663. break;
  46664. case AlwaysDepth:
  46665. depthCompare = GPUCompareFunction.Always;
  46666. break;
  46667. case LessDepth:
  46668. depthCompare = GPUCompareFunction.Less;
  46669. break;
  46670. case LessEqualDepth:
  46671. depthCompare = GPUCompareFunction.LessEqual;
  46672. break;
  46673. case EqualDepth:
  46674. depthCompare = GPUCompareFunction.Equal;
  46675. break;
  46676. case GreaterEqualDepth:
  46677. depthCompare = GPUCompareFunction.GreaterEqual;
  46678. break;
  46679. case GreaterDepth:
  46680. depthCompare = GPUCompareFunction.Greater;
  46681. break;
  46682. case NotEqualDepth:
  46683. depthCompare = GPUCompareFunction.NotEqual;
  46684. break;
  46685. default:
  46686. console.error( 'THREE.WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  46687. }
  46688. }
  46689. return depthCompare;
  46690. }
  46691. }
  46692. /**
  46693. * Manages a pool of WebGPU timestamp queries for performance measurement.
  46694. * Extends the base TimestampQueryPool to provide WebGPU-specific implementation.
  46695. * @extends TimestampQueryPool
  46696. */
  46697. class WebGPUTimestampQueryPool extends TimestampQueryPool {
  46698. /**
  46699. * Creates a new WebGPU timestamp query pool.
  46700. * @param {GPUDevice} device - The WebGPU device to create queries on.
  46701. * @param {string} type - The type identifier for this query pool.
  46702. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  46703. */
  46704. constructor( device, type, maxQueries = 2048 ) {
  46705. super( maxQueries );
  46706. this.device = device;
  46707. this.type = type;
  46708. this.querySet = this.device.createQuerySet( {
  46709. type: 'timestamp',
  46710. count: this.maxQueries,
  46711. label: `queryset_global_timestamp_${type}`
  46712. } );
  46713. const bufferSize = this.maxQueries * 8;
  46714. this.resolveBuffer = this.device.createBuffer( {
  46715. label: `buffer_timestamp_resolve_${type}`,
  46716. size: bufferSize,
  46717. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  46718. } );
  46719. this.resultBuffer = this.device.createBuffer( {
  46720. label: `buffer_timestamp_result_${type}`,
  46721. size: bufferSize,
  46722. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  46723. } );
  46724. }
  46725. /**
  46726. * Allocates a pair of queries for a given render context.
  46727. * @param {Object} renderContext - The render context to allocate queries for.
  46728. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  46729. */
  46730. allocateQueriesForContext( renderContext ) {
  46731. if ( ! this.trackTimestamp || this.isDisposed ) return null;
  46732. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  46733. 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() } ).` );
  46734. return null;
  46735. }
  46736. const baseOffset = this.currentQueryIndex;
  46737. this.currentQueryIndex += 2;
  46738. this.queryOffsets.set( renderContext.id, baseOffset );
  46739. return baseOffset;
  46740. }
  46741. /**
  46742. * Asynchronously resolves all pending queries and returns the total duration.
  46743. * If there's already a pending resolve operation, returns that promise instead.
  46744. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  46745. */
  46746. async resolveQueriesAsync() {
  46747. if ( ! this.trackTimestamp || this.currentQueryIndex === 0 || this.isDisposed ) {
  46748. return this.lastValue;
  46749. }
  46750. if ( this.pendingResolve ) {
  46751. return this.pendingResolve;
  46752. }
  46753. this.pendingResolve = this._resolveQueries();
  46754. try {
  46755. const result = await this.pendingResolve;
  46756. return result;
  46757. } finally {
  46758. this.pendingResolve = null;
  46759. }
  46760. }
  46761. /**
  46762. * Internal method to resolve queries and calculate total duration.
  46763. * @private
  46764. * @returns {Promise<number>} The total duration in milliseconds.
  46765. */
  46766. async _resolveQueries() {
  46767. if ( this.isDisposed ) {
  46768. return this.lastValue;
  46769. }
  46770. try {
  46771. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  46772. return this.lastValue;
  46773. }
  46774. const currentOffsets = new Map( this.queryOffsets );
  46775. const queryCount = this.currentQueryIndex;
  46776. const bytesUsed = queryCount * 8;
  46777. // Reset state before GPU work
  46778. this.currentQueryIndex = 0;
  46779. this.queryOffsets.clear();
  46780. const commandEncoder = this.device.createCommandEncoder();
  46781. commandEncoder.resolveQuerySet(
  46782. this.querySet,
  46783. 0,
  46784. queryCount,
  46785. this.resolveBuffer,
  46786. 0
  46787. );
  46788. commandEncoder.copyBufferToBuffer(
  46789. this.resolveBuffer,
  46790. 0,
  46791. this.resultBuffer,
  46792. 0,
  46793. bytesUsed
  46794. );
  46795. const commandBuffer = commandEncoder.finish();
  46796. this.device.queue.submit( [ commandBuffer ] );
  46797. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  46798. return this.lastValue;
  46799. }
  46800. // Create and track the mapping operation
  46801. await this.resultBuffer.mapAsync( GPUMapMode.READ, 0, bytesUsed );
  46802. if ( this.isDisposed ) {
  46803. if ( this.resultBuffer.mapState === 'mapped' ) {
  46804. this.resultBuffer.unmap();
  46805. }
  46806. return this.lastValue;
  46807. }
  46808. const times = new BigUint64Array( this.resultBuffer.getMappedRange( 0, bytesUsed ) );
  46809. let totalDuration = 0;
  46810. for ( const [ , baseOffset ] of currentOffsets ) {
  46811. const startTime = times[ baseOffset ];
  46812. const endTime = times[ baseOffset + 1 ];
  46813. const duration = Number( endTime - startTime ) / 1e6;
  46814. totalDuration += duration;
  46815. }
  46816. this.resultBuffer.unmap();
  46817. this.lastValue = totalDuration;
  46818. return totalDuration;
  46819. } catch ( error ) {
  46820. console.error( 'Error resolving queries:', error );
  46821. if ( this.resultBuffer.mapState === 'mapped' ) {
  46822. this.resultBuffer.unmap();
  46823. }
  46824. return this.lastValue;
  46825. }
  46826. }
  46827. async dispose() {
  46828. if ( this.isDisposed ) {
  46829. return;
  46830. }
  46831. this.isDisposed = true;
  46832. // Wait for pending resolve operation
  46833. if ( this.pendingResolve ) {
  46834. try {
  46835. await this.pendingResolve;
  46836. } catch ( error ) {
  46837. console.error( 'Error waiting for pending resolve:', error );
  46838. }
  46839. }
  46840. // Ensure buffer is unmapped before destroying
  46841. if ( this.resultBuffer && this.resultBuffer.mapState === 'mapped' ) {
  46842. try {
  46843. this.resultBuffer.unmap();
  46844. } catch ( error ) {
  46845. console.error( 'Error unmapping buffer:', error );
  46846. }
  46847. }
  46848. // Destroy resources
  46849. if ( this.querySet ) {
  46850. this.querySet.destroy();
  46851. this.querySet = null;
  46852. }
  46853. if ( this.resolveBuffer ) {
  46854. this.resolveBuffer.destroy();
  46855. this.resolveBuffer = null;
  46856. }
  46857. if ( this.resultBuffer ) {
  46858. this.resultBuffer.destroy();
  46859. this.resultBuffer = null;
  46860. }
  46861. this.queryOffsets.clear();
  46862. this.pendingResolve = null;
  46863. }
  46864. }
  46865. /*// debugger tools
  46866. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  46867. //*/
  46868. /**
  46869. * A backend implementation targeting WebGPU.
  46870. *
  46871. * @private
  46872. * @augments Backend
  46873. */
  46874. class WebGPUBackend extends Backend {
  46875. /**
  46876. * Constructs a new WebGPU backend.
  46877. *
  46878. * @param {Object} parameters - The configuration parameter.
  46879. * @param {Boolean} [parameters.logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  46880. * @param {Boolean} [parameters.alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  46881. * @param {Boolean} [parameters.depth=true] - Whether the default framebuffer should have a depth buffer or not.
  46882. * @param {Boolean} [parameters.stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  46883. * @param {Boolean} [parameters.antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  46884. * @param {Number} [parameters.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.
  46885. * @param {Boolean} [parameters.forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  46886. * @param {Boolean} [parameters.trackTimestamp=false] - Whether to track timestamps with a Timestamp Query API or not.
  46887. * @param {String} [parameters.powerPreference=undefined] - The power preference.
  46888. * @param {Object} [parameters.requiredLimits=undefined] - Specifies the limits that are required by the device request. The request will fail if the adapter cannot provide these limits.
  46889. * @param {GPUDevice} [parameters.device=undefined] - If there is an existing GPU device on app level, it can be passed to the renderer as a parameter.
  46890. * @param {Number} [parameters.outputType=undefined] - Texture type for output to canvas. By default, device's preferred format is used; other formats may incur overhead.
  46891. */
  46892. constructor( parameters = {} ) {
  46893. super( parameters );
  46894. /**
  46895. * This flag can be used for type testing.
  46896. *
  46897. * @type {Boolean}
  46898. * @readonly
  46899. * @default true
  46900. */
  46901. this.isWebGPUBackend = true;
  46902. // some parameters require default values other than "undefined"
  46903. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  46904. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  46905. /**
  46906. * Whether to track timestamps with a Timestamp Query API or not.
  46907. *
  46908. * @type {Boolean}
  46909. * @default false
  46910. */
  46911. this.trackTimestamp = ( parameters.trackTimestamp === true );
  46912. /**
  46913. * A reference to the device.
  46914. *
  46915. * @type {GPUDevice?}
  46916. * @default null
  46917. */
  46918. this.device = null;
  46919. /**
  46920. * A reference to the context.
  46921. *
  46922. * @type {GPUCanvasContext?}
  46923. * @default null
  46924. */
  46925. this.context = null;
  46926. /**
  46927. * A reference to the color attachment of the default framebuffer.
  46928. *
  46929. * @type {GPUTexture?}
  46930. * @default null
  46931. */
  46932. this.colorBuffer = null;
  46933. /**
  46934. * A reference to the default render pass descriptor.
  46935. *
  46936. * @type {Object?}
  46937. * @default null
  46938. */
  46939. this.defaultRenderPassdescriptor = null;
  46940. /**
  46941. * A reference to a backend module holding common utility functions.
  46942. *
  46943. * @type {WebGPUUtils}
  46944. */
  46945. this.utils = new WebGPUUtils( this );
  46946. /**
  46947. * A reference to a backend module holding shader attribute-related
  46948. * utility functions.
  46949. *
  46950. * @type {WebGPUAttributeUtils}
  46951. */
  46952. this.attributeUtils = new WebGPUAttributeUtils( this );
  46953. /**
  46954. * A reference to a backend module holding shader binding-related
  46955. * utility functions.
  46956. *
  46957. * @type {WebGPUBindingUtils}
  46958. */
  46959. this.bindingUtils = new WebGPUBindingUtils( this );
  46960. /**
  46961. * A reference to a backend module holding shader pipeline-related
  46962. * utility functions.
  46963. *
  46964. * @type {WebGPUPipelineUtils}
  46965. */
  46966. this.pipelineUtils = new WebGPUPipelineUtils( this );
  46967. /**
  46968. * A reference to a backend module holding shader texture-related
  46969. * utility functions.
  46970. *
  46971. * @type {WebGPUTextureUtils}
  46972. */
  46973. this.textureUtils = new WebGPUTextureUtils( this );
  46974. /**
  46975. * A map that manages the resolve buffers for occlusion queries.
  46976. *
  46977. * @type {Map<Number,GPUBuffer>}
  46978. */
  46979. this.occludedResolveCache = new Map();
  46980. }
  46981. /**
  46982. * Initializes the backend so it is ready for usage.
  46983. *
  46984. * @async
  46985. * @param {Renderer} renderer - The renderer.
  46986. * @return {Promise} A Promise that resolves when the backend has been initialized.
  46987. */
  46988. async init( renderer ) {
  46989. await super.init( renderer );
  46990. //
  46991. const parameters = this.parameters;
  46992. // create the device if it is not passed with parameters
  46993. let device;
  46994. if ( parameters.device === undefined ) {
  46995. const adapterOptions = {
  46996. powerPreference: parameters.powerPreference
  46997. };
  46998. const adapter = ( typeof navigator !== 'undefined' ) ? await navigator.gpu.requestAdapter( adapterOptions ) : null;
  46999. if ( adapter === null ) {
  47000. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  47001. }
  47002. // feature support
  47003. const features = Object.values( GPUFeatureName );
  47004. const supportedFeatures = [];
  47005. for ( const name of features ) {
  47006. if ( adapter.features.has( name ) ) {
  47007. supportedFeatures.push( name );
  47008. }
  47009. }
  47010. const deviceDescriptor = {
  47011. requiredFeatures: supportedFeatures,
  47012. requiredLimits: parameters.requiredLimits
  47013. };
  47014. device = await adapter.requestDevice( deviceDescriptor );
  47015. } else {
  47016. device = parameters.device;
  47017. }
  47018. device.lost.then( ( info ) => {
  47019. const deviceLossInfo = {
  47020. api: 'WebGPU',
  47021. message: info.message || 'Unknown reason',
  47022. reason: info.reason || null,
  47023. originalEvent: info
  47024. };
  47025. renderer.onDeviceLost( deviceLossInfo );
  47026. } );
  47027. const context = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgpu' );
  47028. this.device = device;
  47029. this.context = context;
  47030. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  47031. this.trackTimestamp = this.trackTimestamp && this.hasFeature( GPUFeatureName.TimestampQuery );
  47032. this.context.configure( {
  47033. device: this.device,
  47034. format: this.utils.getPreferredCanvasFormat(),
  47035. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  47036. alphaMode: alphaMode
  47037. } );
  47038. this.updateSize();
  47039. }
  47040. /**
  47041. * The coordinate system of the backend.
  47042. *
  47043. * @type {Number}
  47044. * @readonly
  47045. */
  47046. get coordinateSystem() {
  47047. return WebGPUCoordinateSystem;
  47048. }
  47049. /**
  47050. * This method performs a readback operation by moving buffer data from
  47051. * a storage buffer attribute from the GPU to the CPU.
  47052. *
  47053. * @async
  47054. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  47055. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  47056. */
  47057. async getArrayBufferAsync( attribute ) {
  47058. return await this.attributeUtils.getArrayBufferAsync( attribute );
  47059. }
  47060. /**
  47061. * Returns the backend's rendering context.
  47062. *
  47063. * @return {GPUCanvasContext} The rendering context.
  47064. */
  47065. getContext() {
  47066. return this.context;
  47067. }
  47068. /**
  47069. * Returns the default render pass descriptor.
  47070. *
  47071. * In WebGPU, the default framebuffer must be configured
  47072. * like custom framebuffers so the backend needs a render
  47073. * pass descriptor even when rendering directly to screen.
  47074. *
  47075. * @private
  47076. * @return {Object} The render pass descriptor.
  47077. */
  47078. _getDefaultRenderPassDescriptor() {
  47079. let descriptor = this.defaultRenderPassdescriptor;
  47080. if ( descriptor === null ) {
  47081. const renderer = this.renderer;
  47082. descriptor = {
  47083. colorAttachments: [ {
  47084. view: null
  47085. } ],
  47086. };
  47087. if ( this.renderer.depth === true || this.renderer.stencil === true ) {
  47088. descriptor.depthStencilAttachment = {
  47089. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  47090. };
  47091. }
  47092. const colorAttachment = descriptor.colorAttachments[ 0 ];
  47093. if ( this.renderer.samples > 0 ) {
  47094. colorAttachment.view = this.colorBuffer.createView();
  47095. } else {
  47096. colorAttachment.resolveTarget = undefined;
  47097. }
  47098. this.defaultRenderPassdescriptor = descriptor;
  47099. }
  47100. const colorAttachment = descriptor.colorAttachments[ 0 ];
  47101. if ( this.renderer.samples > 0 ) {
  47102. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  47103. } else {
  47104. colorAttachment.view = this.context.getCurrentTexture().createView();
  47105. }
  47106. return descriptor;
  47107. }
  47108. /**
  47109. * Returns the render pass descriptor for the given render context.
  47110. *
  47111. * @private
  47112. * @param {RenderContext} renderContext - The render context.
  47113. * @param {Object} colorAttachmentsConfig - Configuration object for the color attachments.
  47114. * @return {Object} The render pass descriptor.
  47115. */
  47116. _getRenderPassDescriptor( renderContext, colorAttachmentsConfig = {} ) {
  47117. const renderTarget = renderContext.renderTarget;
  47118. const renderTargetData = this.get( renderTarget );
  47119. let descriptors = renderTargetData.descriptors;
  47120. if ( descriptors === undefined ||
  47121. renderTargetData.width !== renderTarget.width ||
  47122. renderTargetData.height !== renderTarget.height ||
  47123. renderTargetData.dimensions !== renderTarget.dimensions ||
  47124. renderTargetData.activeMipmapLevel !== renderTarget.activeMipmapLevel ||
  47125. renderTargetData.activeCubeFace !== renderContext.activeCubeFace ||
  47126. renderTargetData.samples !== renderTarget.samples ||
  47127. renderTargetData.loadOp !== colorAttachmentsConfig.loadOp
  47128. ) {
  47129. descriptors = {};
  47130. renderTargetData.descriptors = descriptors;
  47131. // dispose
  47132. const onDispose = () => {
  47133. renderTarget.removeEventListener( 'dispose', onDispose );
  47134. this.delete( renderTarget );
  47135. };
  47136. renderTarget.addEventListener( 'dispose', onDispose );
  47137. }
  47138. const cacheKey = renderContext.getCacheKey();
  47139. let descriptor = descriptors[ cacheKey ];
  47140. if ( descriptor === undefined ) {
  47141. const textures = renderContext.textures;
  47142. const colorAttachments = [];
  47143. let sliceIndex;
  47144. for ( let i = 0; i < textures.length; i ++ ) {
  47145. const textureData = this.get( textures[ i ] );
  47146. const viewDescriptor = {
  47147. label: `colorAttachment_${ i }`,
  47148. baseMipLevel: renderContext.activeMipmapLevel,
  47149. mipLevelCount: 1,
  47150. baseArrayLayer: renderContext.activeCubeFace,
  47151. arrayLayerCount: 1,
  47152. dimension: GPUTextureViewDimension.TwoD
  47153. };
  47154. if ( renderTarget.isRenderTarget3D ) {
  47155. sliceIndex = renderContext.activeCubeFace;
  47156. viewDescriptor.baseArrayLayer = 0;
  47157. viewDescriptor.dimension = GPUTextureViewDimension.ThreeD;
  47158. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  47159. } else if ( renderTarget.isRenderTargetArray ) {
  47160. viewDescriptor.dimension = GPUTextureViewDimension.TwoDArray;
  47161. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  47162. }
  47163. const textureView = textureData.texture.createView( viewDescriptor );
  47164. let view, resolveTarget;
  47165. if ( textureData.msaaTexture !== undefined ) {
  47166. view = textureData.msaaTexture.createView();
  47167. resolveTarget = textureView;
  47168. } else {
  47169. view = textureView;
  47170. resolveTarget = undefined;
  47171. }
  47172. colorAttachments.push( {
  47173. view,
  47174. depthSlice: sliceIndex,
  47175. resolveTarget,
  47176. loadOp: GPULoadOp.Load,
  47177. storeOp: GPUStoreOp.Store,
  47178. ...colorAttachmentsConfig
  47179. } );
  47180. }
  47181. descriptor = {
  47182. colorAttachments,
  47183. };
  47184. if ( renderContext.depth ) {
  47185. const depthTextureData = this.get( renderContext.depthTexture );
  47186. const depthStencilAttachment = {
  47187. view: depthTextureData.texture.createView()
  47188. };
  47189. descriptor.depthStencilAttachment = depthStencilAttachment;
  47190. }
  47191. descriptors[ cacheKey ] = descriptor;
  47192. renderTargetData.width = renderTarget.width;
  47193. renderTargetData.height = renderTarget.height;
  47194. renderTargetData.samples = renderTarget.samples;
  47195. renderTargetData.activeMipmapLevel = renderContext.activeMipmapLevel;
  47196. renderTargetData.activeCubeFace = renderContext.activeCubeFace;
  47197. renderTargetData.dimensions = renderTarget.dimensions;
  47198. renderTargetData.depthSlice = sliceIndex;
  47199. renderTargetData.loadOp = colorAttachments[ 0 ].loadOp;
  47200. }
  47201. return descriptor;
  47202. }
  47203. /**
  47204. * This method is executed at the beginning of a render call and prepares
  47205. * the WebGPU state for upcoming render calls
  47206. *
  47207. * @param {RenderContext} renderContext - The render context.
  47208. */
  47209. beginRender( renderContext ) {
  47210. const renderContextData = this.get( renderContext );
  47211. const device = this.device;
  47212. const occlusionQueryCount = renderContext.occlusionQueryCount;
  47213. let occlusionQuerySet;
  47214. if ( occlusionQueryCount > 0 ) {
  47215. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  47216. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  47217. // Get a reference to the array of objects with queries. The renderContextData property
  47218. // can be changed by another render pass before the buffer.mapAsyc() completes.
  47219. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  47220. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  47221. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  47222. //
  47223. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount, label: `occlusionQuerySet_${ renderContext.id }` } );
  47224. renderContextData.occlusionQuerySet = occlusionQuerySet;
  47225. renderContextData.occlusionQueryIndex = 0;
  47226. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  47227. renderContextData.lastOcclusionObject = null;
  47228. }
  47229. let descriptor;
  47230. if ( renderContext.textures === null ) {
  47231. descriptor = this._getDefaultRenderPassDescriptor();
  47232. } else {
  47233. descriptor = this._getRenderPassDescriptor( renderContext, { loadOp: GPULoadOp.Load } );
  47234. }
  47235. this.initTimestampQuery( renderContext, descriptor );
  47236. descriptor.occlusionQuerySet = occlusionQuerySet;
  47237. const depthStencilAttachment = descriptor.depthStencilAttachment;
  47238. if ( renderContext.textures !== null ) {
  47239. const colorAttachments = descriptor.colorAttachments;
  47240. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  47241. const colorAttachment = colorAttachments[ i ];
  47242. if ( renderContext.clearColor ) {
  47243. colorAttachment.clearValue = i === 0 ? renderContext.clearColorValue : { r: 0, g: 0, b: 0, a: 1 };
  47244. colorAttachment.loadOp = GPULoadOp.Clear;
  47245. colorAttachment.storeOp = GPUStoreOp.Store;
  47246. } else {
  47247. colorAttachment.loadOp = GPULoadOp.Load;
  47248. colorAttachment.storeOp = GPUStoreOp.Store;
  47249. }
  47250. }
  47251. } else {
  47252. const colorAttachment = descriptor.colorAttachments[ 0 ];
  47253. if ( renderContext.clearColor ) {
  47254. colorAttachment.clearValue = renderContext.clearColorValue;
  47255. colorAttachment.loadOp = GPULoadOp.Clear;
  47256. colorAttachment.storeOp = GPUStoreOp.Store;
  47257. } else {
  47258. colorAttachment.loadOp = GPULoadOp.Load;
  47259. colorAttachment.storeOp = GPUStoreOp.Store;
  47260. }
  47261. }
  47262. //
  47263. if ( renderContext.depth ) {
  47264. if ( renderContext.clearDepth ) {
  47265. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  47266. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  47267. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  47268. } else {
  47269. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  47270. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  47271. }
  47272. }
  47273. if ( renderContext.stencil ) {
  47274. if ( renderContext.clearStencil ) {
  47275. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  47276. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  47277. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  47278. } else {
  47279. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  47280. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  47281. }
  47282. }
  47283. //
  47284. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  47285. const currentPass = encoder.beginRenderPass( descriptor );
  47286. //
  47287. renderContextData.descriptor = descriptor;
  47288. renderContextData.encoder = encoder;
  47289. renderContextData.currentPass = currentPass;
  47290. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  47291. renderContextData.renderBundles = [];
  47292. //
  47293. if ( renderContext.viewport ) {
  47294. this.updateViewport( renderContext );
  47295. }
  47296. if ( renderContext.scissor ) {
  47297. const { x, y, width, height } = renderContext.scissorValue;
  47298. currentPass.setScissorRect( x, y, width, height );
  47299. }
  47300. }
  47301. /**
  47302. * This method is executed at the end of a render call and finalizes work
  47303. * after draw calls.
  47304. *
  47305. * @param {RenderContext} renderContext - The render context.
  47306. */
  47307. finishRender( renderContext ) {
  47308. const renderContextData = this.get( renderContext );
  47309. const occlusionQueryCount = renderContext.occlusionQueryCount;
  47310. if ( renderContextData.renderBundles.length > 0 ) {
  47311. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  47312. }
  47313. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  47314. renderContextData.currentPass.endOcclusionQuery();
  47315. }
  47316. renderContextData.currentPass.end();
  47317. if ( occlusionQueryCount > 0 ) {
  47318. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  47319. //
  47320. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  47321. if ( queryResolveBuffer === undefined ) {
  47322. queryResolveBuffer = this.device.createBuffer(
  47323. {
  47324. size: bufferSize,
  47325. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  47326. }
  47327. );
  47328. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  47329. }
  47330. //
  47331. const readBuffer = this.device.createBuffer(
  47332. {
  47333. size: bufferSize,
  47334. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  47335. }
  47336. );
  47337. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  47338. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  47339. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  47340. renderContextData.occlusionQueryBuffer = readBuffer;
  47341. //
  47342. this.resolveOccludedAsync( renderContext );
  47343. }
  47344. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  47345. //
  47346. if ( renderContext.textures !== null ) {
  47347. const textures = renderContext.textures;
  47348. for ( let i = 0; i < textures.length; i ++ ) {
  47349. const texture = textures[ i ];
  47350. if ( texture.generateMipmaps === true ) {
  47351. this.textureUtils.generateMipmaps( texture );
  47352. }
  47353. }
  47354. }
  47355. }
  47356. /**
  47357. * Returns `true` if the given 3D object is fully occluded by other
  47358. * 3D objects in the scene.
  47359. *
  47360. * @param {RenderContext} renderContext - The render context.
  47361. * @param {Object3D} object - The 3D object to test.
  47362. * @return {Boolean} Whether the 3D object is fully occluded or not.
  47363. */
  47364. isOccluded( renderContext, object ) {
  47365. const renderContextData = this.get( renderContext );
  47366. return renderContextData.occluded && renderContextData.occluded.has( object );
  47367. }
  47368. /**
  47369. * This method processes the result of occlusion queries and writes it
  47370. * into render context data.
  47371. *
  47372. * @async
  47373. * @param {RenderContext} renderContext - The render context.
  47374. * @return {Promise} A Promise that resolves when the occlusion query results have been processed.
  47375. */
  47376. async resolveOccludedAsync( renderContext ) {
  47377. const renderContextData = this.get( renderContext );
  47378. // handle occlusion query results
  47379. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  47380. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  47381. const occluded = new WeakSet();
  47382. renderContextData.currentOcclusionQueryObjects = null;
  47383. renderContextData.currentOcclusionQueryBuffer = null;
  47384. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  47385. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  47386. const results = new BigUint64Array( buffer );
  47387. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  47388. if ( results[ i ] === BigInt( 0 ) ) {
  47389. occluded.add( currentOcclusionQueryObjects[ i ] );
  47390. }
  47391. }
  47392. currentOcclusionQueryBuffer.destroy();
  47393. renderContextData.occluded = occluded;
  47394. }
  47395. }
  47396. /**
  47397. * Updates the viewport with the values from the given render context.
  47398. *
  47399. * @param {RenderContext} renderContext - The render context.
  47400. */
  47401. updateViewport( renderContext ) {
  47402. const { currentPass } = this.get( renderContext );
  47403. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  47404. currentPass.setViewport( x, y, width, height, minDepth, maxDepth );
  47405. }
  47406. /**
  47407. * Performs a clear operation.
  47408. *
  47409. * @param {Boolean} color - Whether the color buffer should be cleared or not.
  47410. * @param {Boolean} depth - Whether the depth buffer should be cleared or not.
  47411. * @param {Boolean} stencil - Whether the stencil buffer should be cleared or not.
  47412. * @param {RenderContext?} [renderTargetContext=null] - The render context of the current set render target.
  47413. */
  47414. clear( color, depth, stencil, renderTargetContext = null ) {
  47415. const device = this.device;
  47416. const renderer = this.renderer;
  47417. let colorAttachments = [];
  47418. let depthStencilAttachment;
  47419. let clearValue;
  47420. let supportsDepth;
  47421. let supportsStencil;
  47422. if ( color ) {
  47423. const clearColor = this.getClearColor();
  47424. if ( this.renderer.alpha === true ) {
  47425. // premultiply alpha
  47426. const a = clearColor.a;
  47427. clearValue = { r: clearColor.r * a, g: clearColor.g * a, b: clearColor.b * a, a: a };
  47428. } else {
  47429. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  47430. }
  47431. }
  47432. if ( renderTargetContext === null ) {
  47433. supportsDepth = renderer.depth;
  47434. supportsStencil = renderer.stencil;
  47435. const descriptor = this._getDefaultRenderPassDescriptor();
  47436. if ( color ) {
  47437. colorAttachments = descriptor.colorAttachments;
  47438. const colorAttachment = colorAttachments[ 0 ];
  47439. colorAttachment.clearValue = clearValue;
  47440. colorAttachment.loadOp = GPULoadOp.Clear;
  47441. colorAttachment.storeOp = GPUStoreOp.Store;
  47442. }
  47443. if ( supportsDepth || supportsStencil ) {
  47444. depthStencilAttachment = descriptor.depthStencilAttachment;
  47445. }
  47446. } else {
  47447. supportsDepth = renderTargetContext.depth;
  47448. supportsStencil = renderTargetContext.stencil;
  47449. if ( color ) {
  47450. const descriptor = this._getRenderPassDescriptor( renderTargetContext, { loadOp: GPULoadOp.Clear, clearValue } );
  47451. colorAttachments = descriptor.colorAttachments;
  47452. }
  47453. if ( supportsDepth || supportsStencil ) {
  47454. const depthTextureData = this.get( renderTargetContext.depthTexture );
  47455. depthStencilAttachment = {
  47456. view: depthTextureData.texture.createView()
  47457. };
  47458. }
  47459. }
  47460. //
  47461. if ( supportsDepth ) {
  47462. if ( depth ) {
  47463. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  47464. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  47465. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  47466. } else {
  47467. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  47468. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  47469. }
  47470. }
  47471. //
  47472. if ( supportsStencil ) {
  47473. if ( stencil ) {
  47474. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  47475. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  47476. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  47477. } else {
  47478. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  47479. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  47480. }
  47481. }
  47482. //
  47483. const encoder = device.createCommandEncoder( { label: 'clear' } );
  47484. const currentPass = encoder.beginRenderPass( {
  47485. colorAttachments,
  47486. depthStencilAttachment
  47487. } );
  47488. currentPass.end();
  47489. device.queue.submit( [ encoder.finish() ] );
  47490. }
  47491. // compute
  47492. /**
  47493. * This method is executed at the beginning of a compute call and
  47494. * prepares the state for upcoming compute tasks.
  47495. *
  47496. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  47497. */
  47498. beginCompute( computeGroup ) {
  47499. const groupGPU = this.get( computeGroup );
  47500. const descriptor = {
  47501. label: 'computeGroup_' + computeGroup.id
  47502. };
  47503. this.initTimestampQuery( computeGroup, descriptor );
  47504. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder( { label: 'computeGroup_' + computeGroup.id } );
  47505. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  47506. }
  47507. /**
  47508. * Executes a compute command for the given compute node.
  47509. *
  47510. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  47511. * @param {Node} computeNode - The compute node.
  47512. * @param {Array<BindGroup>} bindings - The bindings.
  47513. * @param {ComputePipeline} pipeline - The compute pipeline.
  47514. */
  47515. compute( computeGroup, computeNode, bindings, pipeline ) {
  47516. const { passEncoderGPU } = this.get( computeGroup );
  47517. // pipeline
  47518. const pipelineGPU = this.get( pipeline ).pipeline;
  47519. passEncoderGPU.setPipeline( pipelineGPU );
  47520. // bind groups
  47521. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  47522. const bindGroup = bindings[ i ];
  47523. const bindingsData = this.get( bindGroup );
  47524. passEncoderGPU.setBindGroup( i, bindingsData.group );
  47525. }
  47526. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  47527. const computeNodeData = this.get( computeNode );
  47528. if ( computeNodeData.dispatchSize === undefined ) computeNodeData.dispatchSize = { x: 0, y: 1, z: 1 };
  47529. const { dispatchSize } = computeNodeData;
  47530. if ( computeNode.dispatchCount > maxComputeWorkgroupsPerDimension ) {
  47531. dispatchSize.x = Math.min( computeNode.dispatchCount, maxComputeWorkgroupsPerDimension );
  47532. dispatchSize.y = Math.ceil( computeNode.dispatchCount / maxComputeWorkgroupsPerDimension );
  47533. } else {
  47534. dispatchSize.x = computeNode.dispatchCount;
  47535. }
  47536. passEncoderGPU.dispatchWorkgroups(
  47537. dispatchSize.x,
  47538. dispatchSize.y,
  47539. dispatchSize.z
  47540. );
  47541. }
  47542. /**
  47543. * This method is executed at the end of a compute call and
  47544. * finalizes work after compute tasks.
  47545. *
  47546. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  47547. */
  47548. finishCompute( computeGroup ) {
  47549. const groupData = this.get( computeGroup );
  47550. groupData.passEncoderGPU.end();
  47551. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  47552. }
  47553. /**
  47554. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  47555. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  47556. *
  47557. * @async
  47558. * @return {Promise} A Promise that resolves when synchronization has been finished.
  47559. */
  47560. async waitForGPU() {
  47561. await this.device.queue.onSubmittedWorkDone();
  47562. }
  47563. // render object
  47564. /**
  47565. * Executes a draw command for the given render object.
  47566. *
  47567. * @param {RenderObject} renderObject - The render object to draw.
  47568. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  47569. */
  47570. draw( renderObject, info ) {
  47571. const { object, context, pipeline } = renderObject;
  47572. const bindings = renderObject.getBindings();
  47573. const renderContextData = this.get( context );
  47574. const pipelineGPU = this.get( pipeline ).pipeline;
  47575. const currentSets = renderContextData.currentSets;
  47576. const passEncoderGPU = renderContextData.currentPass;
  47577. const drawParams = renderObject.getDrawParameters();
  47578. if ( drawParams === null ) return;
  47579. // pipeline
  47580. if ( currentSets.pipeline !== pipelineGPU ) {
  47581. passEncoderGPU.setPipeline( pipelineGPU );
  47582. currentSets.pipeline = pipelineGPU;
  47583. }
  47584. // bind groups
  47585. const currentBindingGroups = currentSets.bindingGroups;
  47586. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  47587. const bindGroup = bindings[ i ];
  47588. const bindingsData = this.get( bindGroup );
  47589. if ( currentBindingGroups[ bindGroup.index ] !== bindGroup.id ) {
  47590. passEncoderGPU.setBindGroup( bindGroup.index, bindingsData.group );
  47591. currentBindingGroups[ bindGroup.index ] = bindGroup.id;
  47592. }
  47593. }
  47594. // attributes
  47595. const index = renderObject.getIndex();
  47596. const hasIndex = ( index !== null );
  47597. // index
  47598. if ( hasIndex === true ) {
  47599. if ( currentSets.index !== index ) {
  47600. const buffer = this.get( index ).buffer;
  47601. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  47602. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  47603. currentSets.index = index;
  47604. }
  47605. }
  47606. // vertex buffers
  47607. const vertexBuffers = renderObject.getVertexBuffers();
  47608. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  47609. const vertexBuffer = vertexBuffers[ i ];
  47610. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  47611. const buffer = this.get( vertexBuffer ).buffer;
  47612. passEncoderGPU.setVertexBuffer( i, buffer );
  47613. currentSets.attributes[ i ] = vertexBuffer;
  47614. }
  47615. }
  47616. // occlusion queries - handle multiple consecutive draw calls for an object
  47617. if ( renderContextData.occlusionQuerySet !== undefined ) {
  47618. const lastObject = renderContextData.lastOcclusionObject;
  47619. if ( lastObject !== object ) {
  47620. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  47621. passEncoderGPU.endOcclusionQuery();
  47622. renderContextData.occlusionQueryIndex ++;
  47623. }
  47624. if ( object.occlusionTest === true ) {
  47625. passEncoderGPU.beginOcclusionQuery( renderContextData.occlusionQueryIndex );
  47626. renderContextData.occlusionQueryObjects[ renderContextData.occlusionQueryIndex ] = object;
  47627. }
  47628. renderContextData.lastOcclusionObject = object;
  47629. }
  47630. }
  47631. // draw
  47632. const draw = () => {
  47633. if ( object.isBatchedMesh === true ) {
  47634. const starts = object._multiDrawStarts;
  47635. const counts = object._multiDrawCounts;
  47636. const drawCount = object._multiDrawCount;
  47637. const drawInstances = object._multiDrawInstances;
  47638. for ( let i = 0; i < drawCount; i ++ ) {
  47639. const count = drawInstances ? drawInstances[ i ] : 1;
  47640. const firstInstance = count > 1 ? 0 : i;
  47641. if ( hasIndex === true ) {
  47642. passEncoderGPU.drawIndexed( counts[ i ], count, starts[ i ] / index.array.BYTES_PER_ELEMENT, 0, firstInstance );
  47643. } else {
  47644. passEncoderGPU.draw( counts[ i ], count, starts[ i ], firstInstance );
  47645. }
  47646. }
  47647. } else if ( hasIndex === true ) {
  47648. const { vertexCount: indexCount, instanceCount, firstVertex: firstIndex } = drawParams;
  47649. const indirect = renderObject.getIndirect();
  47650. if ( indirect !== null ) {
  47651. const buffer = this.get( indirect ).buffer;
  47652. passEncoderGPU.drawIndexedIndirect( buffer, 0 );
  47653. } else {
  47654. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstIndex, 0, 0 );
  47655. }
  47656. info.update( object, indexCount, instanceCount );
  47657. } else {
  47658. const { vertexCount, instanceCount, firstVertex } = drawParams;
  47659. const indirect = renderObject.getIndirect();
  47660. if ( indirect !== null ) {
  47661. const buffer = this.get( indirect ).buffer;
  47662. passEncoderGPU.drawIndirect( buffer, 0 );
  47663. } else {
  47664. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  47665. }
  47666. info.update( object, vertexCount, instanceCount );
  47667. }
  47668. };
  47669. if ( renderObject.camera.isArrayCamera && renderObject.camera.cameras.length > 0 ) {
  47670. const cameraData = this.get( renderObject.camera );
  47671. const cameras = renderObject.camera.cameras;
  47672. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' );
  47673. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  47674. const bindingsData = this.get( cameraIndex );
  47675. const indexesGPU = [];
  47676. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  47677. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  47678. data[ 0 ] = i;
  47679. const bindGroupIndex = this.bindingUtils.createBindGroupIndex( data, bindingsData.layout );
  47680. indexesGPU.push( bindGroupIndex );
  47681. }
  47682. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  47683. }
  47684. const pixelRatio = this.renderer.getPixelRatio();
  47685. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  47686. const subCamera = cameras[ i ];
  47687. if ( object.layers.test( subCamera.layers ) ) {
  47688. const vp = subCamera.viewport;
  47689. passEncoderGPU.setViewport(
  47690. Math.floor( vp.x * pixelRatio ),
  47691. Math.floor( vp.y * pixelRatio ),
  47692. Math.floor( vp.width * pixelRatio ),
  47693. Math.floor( vp.height * pixelRatio ),
  47694. context.viewportValue.minDepth,
  47695. context.viewportValue.maxDepth
  47696. );
  47697. passEncoderGPU.setBindGroup( cameraIndex.index, cameraData.indexesGPU[ i ] );
  47698. draw();
  47699. }
  47700. }
  47701. } else {
  47702. draw();
  47703. }
  47704. }
  47705. // cache key
  47706. /**
  47707. * Returns `true` if the render pipeline requires an update.
  47708. *
  47709. * @param {RenderObject} renderObject - The render object.
  47710. * @return {Boolean} Whether the render pipeline requires an update or not.
  47711. */
  47712. needsRenderUpdate( renderObject ) {
  47713. const data = this.get( renderObject );
  47714. const { object, material } = renderObject;
  47715. const utils = this.utils;
  47716. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  47717. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  47718. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  47719. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  47720. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  47721. let needsUpdate = false;
  47722. if ( data.material !== material || data.materialVersion !== material.version ||
  47723. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  47724. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  47725. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  47726. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  47727. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  47728. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  47729. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  47730. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  47731. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  47732. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  47733. data.primitiveTopology !== primitiveTopology ||
  47734. data.clippingContextCacheKey !== renderObject.clippingContextCacheKey
  47735. ) {
  47736. data.material = material; data.materialVersion = material.version;
  47737. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  47738. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  47739. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  47740. data.colorWrite = material.colorWrite;
  47741. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  47742. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  47743. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  47744. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  47745. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  47746. data.sampleCount = sampleCount;
  47747. data.colorSpace = colorSpace;
  47748. data.colorFormat = colorFormat;
  47749. data.depthStencilFormat = depthStencilFormat;
  47750. data.primitiveTopology = primitiveTopology;
  47751. data.clippingContextCacheKey = renderObject.clippingContextCacheKey;
  47752. needsUpdate = true;
  47753. }
  47754. return needsUpdate;
  47755. }
  47756. /**
  47757. * Returns a cache key that is used to identify render pipelines.
  47758. *
  47759. * @param {RenderObject} renderObject - The render object.
  47760. * @return {String} The cache key.
  47761. */
  47762. getRenderCacheKey( renderObject ) {
  47763. const { object, material } = renderObject;
  47764. const utils = this.utils;
  47765. const renderContext = renderObject.context;
  47766. return [
  47767. material.transparent, material.blending, material.premultipliedAlpha,
  47768. material.blendSrc, material.blendDst, material.blendEquation,
  47769. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  47770. material.colorWrite,
  47771. material.depthWrite, material.depthTest, material.depthFunc,
  47772. material.stencilWrite, material.stencilFunc,
  47773. material.stencilFail, material.stencilZFail, material.stencilZPass,
  47774. material.stencilFuncMask, material.stencilWriteMask,
  47775. material.side,
  47776. utils.getSampleCountRenderContext( renderContext ),
  47777. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  47778. utils.getPrimitiveTopology( object, material ),
  47779. renderObject.getGeometryCacheKey(),
  47780. renderObject.clippingContextCacheKey
  47781. ].join();
  47782. }
  47783. // textures
  47784. /**
  47785. * Creates a GPU sampler for the given texture.
  47786. *
  47787. * @param {Texture} texture - The texture to create the sampler for.
  47788. */
  47789. createSampler( texture ) {
  47790. this.textureUtils.createSampler( texture );
  47791. }
  47792. /**
  47793. * Destroys the GPU sampler for the given texture.
  47794. *
  47795. * @param {Texture} texture - The texture to destroy the sampler for.
  47796. */
  47797. destroySampler( texture ) {
  47798. this.textureUtils.destroySampler( texture );
  47799. }
  47800. /**
  47801. * Creates a default texture for the given texture that can be used
  47802. * as a placeholder until the actual texture is ready for usage.
  47803. *
  47804. * @param {Texture} texture - The texture to create a default texture for.
  47805. */
  47806. createDefaultTexture( texture ) {
  47807. this.textureUtils.createDefaultTexture( texture );
  47808. }
  47809. /**
  47810. * Defines a texture on the GPU for the given texture object.
  47811. *
  47812. * @param {Texture} texture - The texture.
  47813. * @param {Object} [options={}] - Optional configuration parameter.
  47814. */
  47815. createTexture( texture, options ) {
  47816. this.textureUtils.createTexture( texture, options );
  47817. }
  47818. /**
  47819. * Uploads the updated texture data to the GPU.
  47820. *
  47821. * @param {Texture} texture - The texture.
  47822. * @param {Object} [options={}] - Optional configuration parameter.
  47823. */
  47824. updateTexture( texture, options ) {
  47825. this.textureUtils.updateTexture( texture, options );
  47826. }
  47827. /**
  47828. * Generates mipmaps for the given texture.
  47829. *
  47830. * @param {Texture} texture - The texture.
  47831. */
  47832. generateMipmaps( texture ) {
  47833. this.textureUtils.generateMipmaps( texture );
  47834. }
  47835. /**
  47836. * Destroys the GPU data for the given texture object.
  47837. *
  47838. * @param {Texture} texture - The texture.
  47839. */
  47840. destroyTexture( texture ) {
  47841. this.textureUtils.destroyTexture( texture );
  47842. }
  47843. /**
  47844. * Returns texture data as a typed array.
  47845. *
  47846. * @async
  47847. * @param {Texture} texture - The texture to copy.
  47848. * @param {Number} x - The x coordinate of the copy origin.
  47849. * @param {Number} y - The y coordinate of the copy origin.
  47850. * @param {Number} width - The width of the copy.
  47851. * @param {Number} height - The height of the copy.
  47852. * @param {Number} faceIndex - The face index.
  47853. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  47854. */
  47855. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  47856. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  47857. }
  47858. /**
  47859. * Inits a time stamp query for the given render context.
  47860. *
  47861. * @param {RenderContext} renderContext - The render context.
  47862. * @param {Object} descriptor - The query descriptor.
  47863. */
  47864. initTimestampQuery( renderContext, descriptor ) {
  47865. if ( ! this.trackTimestamp ) return;
  47866. const type = renderContext.isComputeNode ? 'compute' : 'render';
  47867. if ( ! this.timestampQueryPool[ type ] ) {
  47868. // TODO: Variable maxQueries?
  47869. this.timestampQueryPool[ type ] = new WebGPUTimestampQueryPool( this.device, type, 2048 );
  47870. }
  47871. const timestampQueryPool = this.timestampQueryPool[ type ];
  47872. const baseOffset = timestampQueryPool.allocateQueriesForContext( renderContext );
  47873. descriptor.timestampWrites = {
  47874. querySet: timestampQueryPool.querySet,
  47875. beginningOfPassWriteIndex: baseOffset,
  47876. endOfPassWriteIndex: baseOffset + 1,
  47877. };
  47878. }
  47879. // node builder
  47880. /**
  47881. * Returns a node builder for the given render object.
  47882. *
  47883. * @param {RenderObject} object - The render object.
  47884. * @param {Renderer} renderer - The renderer.
  47885. * @return {WGSLNodeBuilder} The node builder.
  47886. */
  47887. createNodeBuilder( object, renderer ) {
  47888. return new WGSLNodeBuilder( object, renderer );
  47889. }
  47890. // program
  47891. /**
  47892. * Creates a shader program from the given programmable stage.
  47893. *
  47894. * @param {ProgrammableStage} program - The programmable stage.
  47895. */
  47896. createProgram( program ) {
  47897. const programGPU = this.get( program );
  47898. programGPU.module = {
  47899. module: this.device.createShaderModule( { code: program.code, label: program.stage + ( program.name !== '' ? `_${ program.name }` : '' ) } ),
  47900. entryPoint: 'main'
  47901. };
  47902. }
  47903. /**
  47904. * Destroys the shader program of the given programmable stage.
  47905. *
  47906. * @param {ProgrammableStage} program - The programmable stage.
  47907. */
  47908. destroyProgram( program ) {
  47909. this.delete( program );
  47910. }
  47911. // pipelines
  47912. /**
  47913. * Creates a render pipeline for the given render object.
  47914. *
  47915. * @param {RenderObject} renderObject - The render object.
  47916. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  47917. */
  47918. createRenderPipeline( renderObject, promises ) {
  47919. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  47920. }
  47921. /**
  47922. * Creates a compute pipeline for the given compute node.
  47923. *
  47924. * @param {ComputePipeline} computePipeline - The compute pipeline.
  47925. * @param {Array<BindGroup>} bindings - The bindings.
  47926. */
  47927. createComputePipeline( computePipeline, bindings ) {
  47928. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  47929. }
  47930. /**
  47931. * Prepares the state for encoding render bundles.
  47932. *
  47933. * @param {RenderContext} renderContext - The render context.
  47934. */
  47935. beginBundle( renderContext ) {
  47936. const renderContextData = this.get( renderContext );
  47937. renderContextData._currentPass = renderContextData.currentPass;
  47938. renderContextData._currentSets = renderContextData.currentSets;
  47939. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  47940. renderContextData.currentPass = this.pipelineUtils.createBundleEncoder( renderContext );
  47941. }
  47942. /**
  47943. * After processing render bundles this method finalizes related work.
  47944. *
  47945. * @param {RenderContext} renderContext - The render context.
  47946. * @param {RenderBundle} bundle - The render bundle.
  47947. */
  47948. finishBundle( renderContext, bundle ) {
  47949. const renderContextData = this.get( renderContext );
  47950. const bundleEncoder = renderContextData.currentPass;
  47951. const bundleGPU = bundleEncoder.finish();
  47952. this.get( bundle ).bundleGPU = bundleGPU;
  47953. // restore render pass state
  47954. renderContextData.currentSets = renderContextData._currentSets;
  47955. renderContextData.currentPass = renderContextData._currentPass;
  47956. }
  47957. /**
  47958. * Adds a render bundle to the render context data.
  47959. *
  47960. * @param {RenderContext} renderContext - The render context.
  47961. * @param {RenderBundle} bundle - The render bundle to add.
  47962. */
  47963. addBundle( renderContext, bundle ) {
  47964. const renderContextData = this.get( renderContext );
  47965. renderContextData.renderBundles.push( this.get( bundle ).bundleGPU );
  47966. }
  47967. // bindings
  47968. /**
  47969. * Creates bindings from the given bind group definition.
  47970. *
  47971. * @param {BindGroup} bindGroup - The bind group.
  47972. * @param {Array<BindGroup>} bindings - Array of bind groups.
  47973. * @param {Number} cacheIndex - The cache index.
  47974. * @param {Number} version - The version.
  47975. */
  47976. createBindings( bindGroup, bindings, cacheIndex, version ) {
  47977. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  47978. }
  47979. /**
  47980. * Updates the given bind group definition.
  47981. *
  47982. * @param {BindGroup} bindGroup - The bind group.
  47983. * @param {Array<BindGroup>} bindings - Array of bind groups.
  47984. * @param {Number} cacheIndex - The cache index.
  47985. * @param {Number} version - The version.
  47986. */
  47987. updateBindings( bindGroup, bindings, cacheIndex, version ) {
  47988. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  47989. }
  47990. /**
  47991. * Updates a buffer binding.
  47992. *
  47993. * @param {Buffer} binding - The buffer binding to update.
  47994. */
  47995. updateBinding( binding ) {
  47996. this.bindingUtils.updateBinding( binding );
  47997. }
  47998. // attributes
  47999. /**
  48000. * Creates the buffer of an indexed shader attribute.
  48001. *
  48002. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  48003. */
  48004. createIndexAttribute( attribute ) {
  48005. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  48006. }
  48007. /**
  48008. * Creates the GPU buffer of a shader attribute.
  48009. *
  48010. * @param {BufferAttribute} attribute - The buffer attribute.
  48011. */
  48012. createAttribute( attribute ) {
  48013. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  48014. }
  48015. /**
  48016. * Creates the GPU buffer of a storage attribute.
  48017. *
  48018. * @param {BufferAttribute} attribute - The buffer attribute.
  48019. */
  48020. createStorageAttribute( attribute ) {
  48021. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  48022. }
  48023. /**
  48024. * Creates the GPU buffer of an indirect storage attribute.
  48025. *
  48026. * @param {BufferAttribute} attribute - The buffer attribute.
  48027. */
  48028. createIndirectStorageAttribute( attribute ) {
  48029. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  48030. }
  48031. /**
  48032. * Updates the GPU buffer of a shader attribute.
  48033. *
  48034. * @param {BufferAttribute} attribute - The buffer attribute to update.
  48035. */
  48036. updateAttribute( attribute ) {
  48037. this.attributeUtils.updateAttribute( attribute );
  48038. }
  48039. /**
  48040. * Destroys the GPU buffer of a shader attribute.
  48041. *
  48042. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  48043. */
  48044. destroyAttribute( attribute ) {
  48045. this.attributeUtils.destroyAttribute( attribute );
  48046. }
  48047. // canvas
  48048. /**
  48049. * Triggers an update of the default render pass descriptor.
  48050. */
  48051. updateSize() {
  48052. this.colorBuffer = this.textureUtils.getColorBuffer();
  48053. this.defaultRenderPassdescriptor = null;
  48054. }
  48055. // utils public
  48056. /**
  48057. * Returns the maximum anisotropy texture filtering value.
  48058. *
  48059. * @return {Number} The maximum anisotropy texture filtering value.
  48060. */
  48061. getMaxAnisotropy() {
  48062. return 16;
  48063. }
  48064. /**
  48065. * Checks if the given feature is supported by the backend.
  48066. *
  48067. * @param {String} name - The feature's name.
  48068. * @return {Boolean} Whether the feature is supported or not.
  48069. */
  48070. hasFeature( name ) {
  48071. return this.device.features.has( name );
  48072. }
  48073. /**
  48074. * Copies data of the given source texture to the given destination texture.
  48075. *
  48076. * @param {Texture} srcTexture - The source texture.
  48077. * @param {Texture} dstTexture - The destination texture.
  48078. * @param {Vector4?} [srcRegion=null] - The region of the source texture to copy.
  48079. * @param {(Vector2|Vector3)?} [dstPosition=null] - The destination position of the copy.
  48080. * @param {Number} [level=0] - The mip level to copy.
  48081. */
  48082. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  48083. let dstX = 0;
  48084. let dstY = 0;
  48085. let dstLayer = 0;
  48086. let srcX = 0;
  48087. let srcY = 0;
  48088. let srcLayer = 0;
  48089. let srcWidth = srcTexture.image.width;
  48090. let srcHeight = srcTexture.image.height;
  48091. if ( srcRegion !== null ) {
  48092. srcX = srcRegion.x;
  48093. srcY = srcRegion.y;
  48094. srcLayer = srcRegion.z || 0;
  48095. srcWidth = srcRegion.width;
  48096. srcHeight = srcRegion.height;
  48097. }
  48098. if ( dstPosition !== null ) {
  48099. dstX = dstPosition.x;
  48100. dstY = dstPosition.y;
  48101. dstLayer = dstPosition.z || 0;
  48102. }
  48103. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  48104. const sourceGPU = this.get( srcTexture ).texture;
  48105. const destinationGPU = this.get( dstTexture ).texture;
  48106. encoder.copyTextureToTexture(
  48107. {
  48108. texture: sourceGPU,
  48109. mipLevel: level,
  48110. origin: { x: srcX, y: srcY, z: srcLayer }
  48111. },
  48112. {
  48113. texture: destinationGPU,
  48114. mipLevel: level,
  48115. origin: { x: dstX, y: dstY, z: dstLayer }
  48116. },
  48117. [
  48118. srcWidth,
  48119. srcHeight,
  48120. 1
  48121. ]
  48122. );
  48123. this.device.queue.submit( [ encoder.finish() ] );
  48124. }
  48125. /**
  48126. * Copies the current bound framebuffer to the given texture.
  48127. *
  48128. * @param {Texture} texture - The destination texture.
  48129. * @param {RenderContext} renderContext - The render context.
  48130. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  48131. */
  48132. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  48133. const renderContextData = this.get( renderContext );
  48134. let sourceGPU = null;
  48135. if ( renderContext.renderTarget ) {
  48136. if ( texture.isDepthTexture ) {
  48137. sourceGPU = this.get( renderContext.depthTexture ).texture;
  48138. } else {
  48139. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  48140. }
  48141. } else {
  48142. if ( texture.isDepthTexture ) {
  48143. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  48144. } else {
  48145. sourceGPU = this.context.getCurrentTexture();
  48146. }
  48147. }
  48148. const destinationGPU = this.get( texture ).texture;
  48149. if ( sourceGPU.format !== destinationGPU.format ) {
  48150. console.error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  48151. return;
  48152. }
  48153. let encoder;
  48154. if ( renderContextData.currentPass ) {
  48155. renderContextData.currentPass.end();
  48156. encoder = renderContextData.encoder;
  48157. } else {
  48158. encoder = this.device.createCommandEncoder( { label: 'copyFramebufferToTexture_' + texture.id } );
  48159. }
  48160. encoder.copyTextureToTexture(
  48161. {
  48162. texture: sourceGPU,
  48163. origin: [ rectangle.x, rectangle.y, 0 ],
  48164. },
  48165. {
  48166. texture: destinationGPU
  48167. },
  48168. [
  48169. rectangle.z,
  48170. rectangle.w
  48171. ]
  48172. );
  48173. if ( texture.generateMipmaps ) this.textureUtils.generateMipmaps( texture );
  48174. if ( renderContextData.currentPass ) {
  48175. const { descriptor } = renderContextData;
  48176. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  48177. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  48178. }
  48179. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  48180. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  48181. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  48182. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  48183. if ( renderContext.viewport ) {
  48184. this.updateViewport( renderContext );
  48185. }
  48186. if ( renderContext.scissor ) {
  48187. const { x, y, width, height } = renderContext.scissorValue;
  48188. renderContextData.currentPass.setScissorRect( x, y, width, height );
  48189. }
  48190. } else {
  48191. this.device.queue.submit( [ encoder.finish() ] );
  48192. }
  48193. }
  48194. }
  48195. class IESSpotLight extends SpotLight {
  48196. constructor( color, intensity, distance, angle, penumbra, decay ) {
  48197. super( color, intensity, distance, angle, penumbra, decay );
  48198. this.iesMap = null;
  48199. }
  48200. copy( source, recursive ) {
  48201. super.copy( source, recursive );
  48202. this.iesMap = source.iesMap;
  48203. return this;
  48204. }
  48205. }
  48206. /**
  48207. * This version of a node library represents a basic version
  48208. * just focusing on lights and tone mapping techniques.
  48209. *
  48210. * @private
  48211. * @augments NodeLibrary
  48212. */
  48213. class BasicNodeLibrary extends NodeLibrary {
  48214. /**
  48215. * Constructs a new basic node library.
  48216. */
  48217. constructor() {
  48218. super();
  48219. this.addLight( PointLightNode, PointLight );
  48220. this.addLight( DirectionalLightNode, DirectionalLight );
  48221. this.addLight( RectAreaLightNode, RectAreaLight );
  48222. this.addLight( SpotLightNode, SpotLight );
  48223. this.addLight( AmbientLightNode, AmbientLight );
  48224. this.addLight( HemisphereLightNode, HemisphereLight );
  48225. this.addLight( LightProbeNode, LightProbe );
  48226. this.addLight( IESSpotLightNode, IESSpotLight );
  48227. this.addToneMapping( linearToneMapping, LinearToneMapping );
  48228. this.addToneMapping( reinhardToneMapping, ReinhardToneMapping );
  48229. this.addToneMapping( cineonToneMapping, CineonToneMapping );
  48230. this.addToneMapping( acesFilmicToneMapping, ACESFilmicToneMapping );
  48231. this.addToneMapping( agxToneMapping, AgXToneMapping );
  48232. this.addToneMapping( neutralToneMapping, NeutralToneMapping );
  48233. }
  48234. }
  48235. /**
  48236. * This alternative version of {@link WebGPURenderer} only supports node materials.
  48237. * So classes like `MeshBasicMaterial` are not compatible.
  48238. *
  48239. * @augments module:Renderer~Renderer
  48240. */
  48241. class WebGPURenderer extends Renderer {
  48242. /**
  48243. * Constructs a new WebGPU renderer.
  48244. *
  48245. * @param {Object} parameters - The configuration parameter.
  48246. * @param {Boolean} [parameters.logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  48247. * @param {Boolean} [parameters.alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  48248. * @param {Boolean} [parameters.depth=true] - Whether the default framebuffer should have a depth buffer or not.
  48249. * @param {Boolean} [parameters.stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  48250. * @param {Boolean} [parameters.antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  48251. * @param {Number} [parameters.samples=0] - When `antialias` is `true`, `4` samples are used by default. Set this parameter to any other integer value than 0
  48252. * to overwrite the default.
  48253. * @param {Boolean} [parameters.forceWebGL=false] - If set to `true`, the renderer uses it
  48254. * WebGL 2 backend no matter if WebGPU is supported or not.
  48255. */
  48256. constructor( parameters = {} ) {
  48257. let BackendClass;
  48258. if ( parameters.forceWebGL ) {
  48259. BackendClass = WebGLBackend;
  48260. } else {
  48261. BackendClass = WebGPUBackend;
  48262. parameters.getFallback = () => {
  48263. console.warn( 'THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  48264. return new WebGLBackend( parameters );
  48265. };
  48266. }
  48267. const backend = new BackendClass( parameters );
  48268. super( backend, parameters );
  48269. /**
  48270. * The generic default value is overwritten with the
  48271. * standard node library for type mapping. Material
  48272. * mapping is not supported with this version.
  48273. *
  48274. * @type {BasicNodeLibrary}
  48275. */
  48276. this.library = new BasicNodeLibrary();
  48277. /**
  48278. * This flag can be used for type testing.
  48279. *
  48280. * @type {Boolean}
  48281. * @readonly
  48282. * @default true
  48283. */
  48284. this.isWebGPURenderer = true;
  48285. }
  48286. }
  48287. /**
  48288. * A specialized group which enables applications access to the
  48289. * Render Bundle API of WebGPU. The group with all its descendant nodes
  48290. * are considered as one render bundle and processed as such by
  48291. * the renderer.
  48292. *
  48293. * This module is only fully supported by `WebGPURenderer` with a WebGPU backend.
  48294. * With a WebGL backend, the group can technically be rendered but without
  48295. * any performance improvements.
  48296. *
  48297. * @augments Group
  48298. */
  48299. class BundleGroup extends Group {
  48300. /**
  48301. * Constructs a new bundle group.
  48302. */
  48303. constructor() {
  48304. super();
  48305. /**
  48306. * This flag can be used for type testing.
  48307. *
  48308. * @type {Boolean}
  48309. * @readonly
  48310. * @default true
  48311. */
  48312. this.isBundleGroup = true;
  48313. /**
  48314. * This property is only relevant for detecting types
  48315. * during serialization/deserialization. It should always
  48316. * match the class name.
  48317. *
  48318. * @type {String}
  48319. * @readonly
  48320. * @default 'BundleGroup'
  48321. */
  48322. this.type = 'BundleGroup';
  48323. /**
  48324. * Whether the bundle is static or not. When set to `true`, the structure
  48325. * is assumed to be static and does not change. E.g. no new objects are
  48326. * added to the group
  48327. *
  48328. * If a change is required, an update can still be forced by setting the
  48329. * `needsUpdate` flag to `true`.
  48330. *
  48331. * @type {Boolean}
  48332. * @default true
  48333. */
  48334. this.static = true;
  48335. /**
  48336. * The bundle group's version.
  48337. *
  48338. * @type {Number}
  48339. * @readonly
  48340. * @default 0
  48341. */
  48342. this.version = 0;
  48343. }
  48344. /**
  48345. * Set this property to `true` when the bundle group has changed.
  48346. *
  48347. * @type {Boolean}
  48348. * @default false
  48349. * @param {Boolean} value
  48350. */
  48351. set needsUpdate( value ) {
  48352. if ( value === true ) this.version ++;
  48353. }
  48354. }
  48355. /**
  48356. * This module is responsible to manage the post processing setups in apps.
  48357. * You usually create a single instance of this class and use it to define
  48358. * the output of your post processing effect chain.
  48359. * ```js
  48360. * const postProcessing = new PostProcessing( renderer );
  48361. *
  48362. * const scenePass = pass( scene, camera );
  48363. *
  48364. * postProcessing.outputNode = scenePass;
  48365. * ```
  48366. */
  48367. class PostProcessing {
  48368. /**
  48369. * Constructs a new post processing management module.
  48370. *
  48371. * @param {Renderer} renderer - A reference to the renderer.
  48372. * @param {Node<vec4>} outputNode - An optional output node.
  48373. */
  48374. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  48375. /**
  48376. * A reference to the renderer.
  48377. *
  48378. * @type {Renderer}
  48379. */
  48380. this.renderer = renderer;
  48381. /**
  48382. * A node which defines the final output of the post
  48383. * processing. This is usually the last node in a chain
  48384. * of effect nodes.
  48385. *
  48386. * @type {Node<vec4>}
  48387. */
  48388. this.outputNode = outputNode;
  48389. /**
  48390. * Whether the default output tone mapping and color
  48391. * space transformation should be enabled or not.
  48392. *
  48393. * It is enabled by default by it must be disabled when
  48394. * effects must be executed after tone mapping and color
  48395. * space conversion. A typical example is FXAA which
  48396. * requires sRGB input.
  48397. *
  48398. * When set to `false`, the app must control the output
  48399. * transformation with `RenderOutputNode`.
  48400. *
  48401. * ```js
  48402. * const outputPass = renderOutput( scenePass );
  48403. * ```
  48404. *
  48405. * @type {Boolean}
  48406. */
  48407. this.outputColorTransform = true;
  48408. /**
  48409. * Must be set to `true` when the output node changes.
  48410. *
  48411. * @type {Node<vec4>}
  48412. */
  48413. this.needsUpdate = true;
  48414. const material = new NodeMaterial();
  48415. material.name = 'PostProcessing';
  48416. /**
  48417. * The full screen quad that is used to render
  48418. * the effects.
  48419. *
  48420. * @private
  48421. * @type {QuadMesh}
  48422. */
  48423. this._quadMesh = new QuadMesh( material );
  48424. }
  48425. /**
  48426. * When `PostProcessing` is used to apply post processing effects,
  48427. * the application must use this version of `render()` inside
  48428. * its animation loop (not the one from the renderer).
  48429. */
  48430. render() {
  48431. this._update();
  48432. const renderer = this.renderer;
  48433. const toneMapping = renderer.toneMapping;
  48434. const outputColorSpace = renderer.outputColorSpace;
  48435. renderer.toneMapping = NoToneMapping;
  48436. renderer.outputColorSpace = LinearSRGBColorSpace;
  48437. //
  48438. this._quadMesh.render( renderer );
  48439. //
  48440. renderer.toneMapping = toneMapping;
  48441. renderer.outputColorSpace = outputColorSpace;
  48442. }
  48443. /**
  48444. * Frees internal resources.
  48445. */
  48446. dispose() {
  48447. this._quadMesh.material.dispose();
  48448. }
  48449. /**
  48450. * Updates the state of the module.
  48451. *
  48452. * @private
  48453. */
  48454. _update() {
  48455. if ( this.needsUpdate === true ) {
  48456. const renderer = this.renderer;
  48457. const toneMapping = renderer.toneMapping;
  48458. const outputColorSpace = renderer.outputColorSpace;
  48459. this._quadMesh.material.fragmentNode = this.outputColorTransform === true ? renderOutput( this.outputNode, toneMapping, outputColorSpace ) : this.outputNode.context( { toneMapping, outputColorSpace } );
  48460. this._quadMesh.material.needsUpdate = true;
  48461. this.needsUpdate = false;
  48462. }
  48463. }
  48464. /**
  48465. * When `PostProcessing` is used to apply post processing effects,
  48466. * the application must use this version of `renderAsync()` inside
  48467. * its animation loop (not the one from the renderer).
  48468. *
  48469. * @async
  48470. * @return {Promise} A Promise that resolves when the render has been finished.
  48471. */
  48472. async renderAsync() {
  48473. this._update();
  48474. const renderer = this.renderer;
  48475. const toneMapping = renderer.toneMapping;
  48476. const outputColorSpace = renderer.outputColorSpace;
  48477. renderer.toneMapping = NoToneMapping;
  48478. renderer.outputColorSpace = LinearSRGBColorSpace;
  48479. //
  48480. await this._quadMesh.renderAsync( renderer );
  48481. //
  48482. renderer.toneMapping = toneMapping;
  48483. renderer.outputColorSpace = outputColorSpace;
  48484. }
  48485. }
  48486. /**
  48487. * This special type of texture is intended for compute shaders.
  48488. * It can be used to compute the data of a texture with a compute shader.
  48489. *
  48490. * Note: This type of texture can only be used with `WebGPURenderer`
  48491. * and a WebGPU backend.
  48492. *
  48493. * @augments Texture
  48494. */
  48495. class StorageTexture extends Texture {
  48496. /**
  48497. * Constructs a new storage texture.
  48498. *
  48499. * @param {Number} [width=1] - The storage texture's width.
  48500. * @param {Number} [height=1] - The storage texture's height.
  48501. */
  48502. constructor( width = 1, height = 1 ) {
  48503. super();
  48504. /**
  48505. * The image object which just represents the texture's dimension.
  48506. *
  48507. * @type {{width: Number, height: Number}}
  48508. */
  48509. this.image = { width, height };
  48510. /**
  48511. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  48512. *
  48513. * @type {Number}
  48514. */
  48515. this.magFilter = LinearFilter;
  48516. /**
  48517. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  48518. *
  48519. * @type {Number}
  48520. */
  48521. this.minFilter = LinearFilter;
  48522. /**
  48523. * This flag can be used for type testing.
  48524. *
  48525. * @type {Boolean}
  48526. * @readonly
  48527. * @default true
  48528. */
  48529. this.isStorageTexture = true;
  48530. }
  48531. }
  48532. /**
  48533. * This special type of buffer attribute is intended for compute shaders.
  48534. * It can be used to encode draw parameters for indirect draw calls.
  48535. *
  48536. * Note: This type of buffer attribute can only be used with `WebGPURenderer`
  48537. * and a WebGPU backend.
  48538. *
  48539. * @augments StorageBufferAttribute
  48540. */
  48541. class IndirectStorageBufferAttribute extends StorageBufferAttribute {
  48542. /**
  48543. * Constructs a new storage buffer attribute.
  48544. *
  48545. * @param {Number|Uint32Array} count - The item count. It is also valid to pass a `Uint32Array` as an argument.
  48546. * The subsequent parameter is then obsolete.
  48547. * @param {Number} itemSize - The item size.
  48548. */
  48549. constructor( count, itemSize ) {
  48550. super( count, itemSize, Uint32Array );
  48551. /**
  48552. * This flag can be used for type testing.
  48553. *
  48554. * @type {Boolean}
  48555. * @readonly
  48556. * @default true
  48557. */
  48558. this.isIndirectStorageBufferAttribute = true;
  48559. }
  48560. }
  48561. /**
  48562. * A loader for loading node objects in the three.js JSON Object/Scene format.
  48563. *
  48564. * @augments Loader
  48565. */
  48566. class NodeLoader extends Loader {
  48567. /**
  48568. * Constructs a new node loader.
  48569. *
  48570. * @param {LoadingManager?} manager - A reference to a loading manager.
  48571. */
  48572. constructor( manager ) {
  48573. super( manager );
  48574. /**
  48575. * Represents a dictionary of textures.
  48576. *
  48577. * @type {Object<String,Texture>}
  48578. */
  48579. this.textures = {};
  48580. /**
  48581. * Represents a dictionary of node types.
  48582. *
  48583. * @type {Object<String,Node.constructor>}
  48584. */
  48585. this.nodes = {};
  48586. }
  48587. /**
  48588. * Loads the node definitions from the given URL.
  48589. *
  48590. * @param {String} url - The path/URL of the file to be loaded.
  48591. * @param {Function} onLoad - Will be called when load completes.
  48592. * @param {Function} onProgress - Will be called while load progresses.
  48593. * @param {Function} onError - Will be called when errors are thrown during the loading process.
  48594. */
  48595. load( url, onLoad, onProgress, onError ) {
  48596. const loader = new FileLoader( this.manager );
  48597. loader.setPath( this.path );
  48598. loader.setRequestHeader( this.requestHeader );
  48599. loader.setWithCredentials( this.withCredentials );
  48600. loader.load( url, ( text ) => {
  48601. try {
  48602. onLoad( this.parse( JSON.parse( text ) ) );
  48603. } catch ( e ) {
  48604. if ( onError ) {
  48605. onError( e );
  48606. } else {
  48607. console.error( e );
  48608. }
  48609. this.manager.itemError( url );
  48610. }
  48611. }, onProgress, onError );
  48612. }
  48613. /**
  48614. * Parse the node dependencies for the loaded node.
  48615. *
  48616. * @param {Object} json - The JSON definition
  48617. * @return {Object<String,Node>} A dictionary with node dependencies.
  48618. */
  48619. parseNodes( json ) {
  48620. const nodes = {};
  48621. if ( json !== undefined ) {
  48622. for ( const nodeJSON of json ) {
  48623. const { uuid, type } = nodeJSON;
  48624. nodes[ uuid ] = this.createNodeFromType( type );
  48625. nodes[ uuid ].uuid = uuid;
  48626. }
  48627. const meta = { nodes, textures: this.textures };
  48628. for ( const nodeJSON of json ) {
  48629. nodeJSON.meta = meta;
  48630. const node = nodes[ nodeJSON.uuid ];
  48631. node.deserialize( nodeJSON );
  48632. delete nodeJSON.meta;
  48633. }
  48634. }
  48635. return nodes;
  48636. }
  48637. /**
  48638. * Parses the node from the given JSON.
  48639. *
  48640. * @param {Object} json - The JSON definition
  48641. * @return {Node} The parsed node.
  48642. */
  48643. parse( json ) {
  48644. const node = this.createNodeFromType( json.type );
  48645. node.uuid = json.uuid;
  48646. const nodes = this.parseNodes( json.nodes );
  48647. const meta = { nodes, textures: this.textures };
  48648. json.meta = meta;
  48649. node.deserialize( json );
  48650. delete json.meta;
  48651. return node;
  48652. }
  48653. /**
  48654. * Defines the dictionary of textures.
  48655. *
  48656. * @param {Object<String,Texture>} value - The texture library defines as `<uuid,texture>`.
  48657. * @return {NodeLoader} A reference to this loader.
  48658. */
  48659. setTextures( value ) {
  48660. this.textures = value;
  48661. return this;
  48662. }
  48663. /**
  48664. * Defines the dictionary of node types.
  48665. *
  48666. * @param {Object<String,Node.constructor>} value - The node library defined as `<classname,class>`.
  48667. * @return {NodeLoader} A reference to this loader.
  48668. */
  48669. setNodes( value ) {
  48670. this.nodes = value;
  48671. return this;
  48672. }
  48673. /**
  48674. * Creates a node object from the given type.
  48675. *
  48676. * @param {String} type - The node type.
  48677. * @return {Node} The created node instance.
  48678. */
  48679. createNodeFromType( type ) {
  48680. if ( this.nodes[ type ] === undefined ) {
  48681. console.error( 'THREE.NodeLoader: Node type not found:', type );
  48682. return float();
  48683. }
  48684. return nodeObject( new this.nodes[ type ]() );
  48685. }
  48686. }
  48687. /**
  48688. * A special type of material loader for loading node materials.
  48689. *
  48690. * @augments MaterialLoader
  48691. */
  48692. class NodeMaterialLoader extends MaterialLoader {
  48693. /**
  48694. * Constructs a new node material loader.
  48695. *
  48696. * @param {LoadingManager?} manager - A reference to a loading manager.
  48697. */
  48698. constructor( manager ) {
  48699. super( manager );
  48700. /**
  48701. * Represents a dictionary of node types.
  48702. *
  48703. * @type {Object<String,Node.constructor>}
  48704. */
  48705. this.nodes = {};
  48706. /**
  48707. * Represents a dictionary of node material types.
  48708. *
  48709. * @type {Object<String,NodeMaterial.constructor>}
  48710. */
  48711. this.nodeMaterials = {};
  48712. }
  48713. /**
  48714. * Parses the node material from the given JSON.
  48715. *
  48716. * @param {Object} json - The JSON definition
  48717. * @return {NodeMaterial}. The parsed material.
  48718. */
  48719. parse( json ) {
  48720. const material = super.parse( json );
  48721. const nodes = this.nodes;
  48722. const inputNodes = json.inputNodes;
  48723. for ( const property in inputNodes ) {
  48724. const uuid = inputNodes[ property ];
  48725. material[ property ] = nodes[ uuid ];
  48726. }
  48727. return material;
  48728. }
  48729. /**
  48730. * Defines the dictionary of node types.
  48731. *
  48732. * @param {Object<String,Node.constructor>} value - The node library defined as `<classname,class>`.
  48733. * @return {NodeLoader} A reference to this loader.
  48734. */
  48735. setNodes( value ) {
  48736. this.nodes = value;
  48737. return this;
  48738. }
  48739. /**
  48740. * Defines the dictionary of node material types.
  48741. *
  48742. * @param {Object<String,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  48743. * @return {NodeLoader} A reference to this loader.
  48744. */
  48745. setNodeMaterials( value ) {
  48746. this.nodeMaterials = value;
  48747. return this;
  48748. }
  48749. /**
  48750. * Creates a node material from the given type.
  48751. *
  48752. * @param {String} type - The node material type.
  48753. * @return {Node} The created node material instance.
  48754. */
  48755. createMaterialFromType( type ) {
  48756. const materialClass = this.nodeMaterials[ type ];
  48757. if ( materialClass !== undefined ) {
  48758. return new materialClass();
  48759. }
  48760. return super.createMaterialFromType( type );
  48761. }
  48762. }
  48763. /**
  48764. * A special type of object loader for loading 3D objects using
  48765. * node materials.
  48766. *
  48767. * @augments ObjectLoader
  48768. */
  48769. class NodeObjectLoader extends ObjectLoader {
  48770. /**
  48771. * Constructs a new node object loader.
  48772. *
  48773. * @param {LoadingManager?} manager - A reference to a loading manager.
  48774. */
  48775. constructor( manager ) {
  48776. super( manager );
  48777. /**
  48778. * Represents a dictionary of node types.
  48779. *
  48780. * @type {Object<String,Node.constructor>}
  48781. */
  48782. this.nodes = {};
  48783. /**
  48784. * Represents a dictionary of node material types.
  48785. *
  48786. * @type {Object<String,NodeMaterial.constructor>}
  48787. */
  48788. this.nodeMaterials = {};
  48789. /**
  48790. * A reference to hold the `nodes` JSON property.
  48791. *
  48792. * @private
  48793. * @type {Object?}
  48794. */
  48795. this._nodesJSON = null;
  48796. }
  48797. /**
  48798. * Defines the dictionary of node types.
  48799. *
  48800. * @param {Object<String,Node.constructor>} value - The node library defined as `<classname,class>`.
  48801. * @return {NodeLoader} A reference to this loader.
  48802. */
  48803. setNodes( value ) {
  48804. this.nodes = value;
  48805. return this;
  48806. }
  48807. /**
  48808. * Defines the dictionary of node material types.
  48809. *
  48810. * @param {Object<String,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  48811. * @return {NodeLoader} A reference to this loader.
  48812. */
  48813. setNodeMaterials( value ) {
  48814. this.nodeMaterials = value;
  48815. return this;
  48816. }
  48817. /**
  48818. * Parses the node objects from the given JSON.
  48819. *
  48820. * @param {Object} json - The JSON definition
  48821. * @param {Function} onLoad - The onLoad callback function.
  48822. * @return {Object3D}. The parsed 3D object.
  48823. */
  48824. parse( json, onLoad ) {
  48825. this._nodesJSON = json.nodes;
  48826. const data = super.parse( json, onLoad );
  48827. this._nodesJSON = null; // dispose
  48828. return data;
  48829. }
  48830. /**
  48831. * Parses the node objects from the given JSON and textures.
  48832. *
  48833. * @param {Object} json - The JSON definition
  48834. * @param {Object<String,Texture>} textures - The texture library.
  48835. * @return {Object<String,Node>}. The parsed nodes.
  48836. */
  48837. parseNodes( json, textures ) {
  48838. if ( json !== undefined ) {
  48839. const loader = new NodeLoader();
  48840. loader.setNodes( this.nodes );
  48841. loader.setTextures( textures );
  48842. return loader.parseNodes( json );
  48843. }
  48844. return {};
  48845. }
  48846. /**
  48847. * Parses the node objects from the given JSON and textures.
  48848. *
  48849. * @param {Object} json - The JSON definition
  48850. * @param {Object<String,Texture>} textures - The texture library.
  48851. * @return {Object<String,NodeMaterial>}. The parsed materials.
  48852. */
  48853. parseMaterials( json, textures ) {
  48854. const materials = {};
  48855. if ( json !== undefined ) {
  48856. const nodes = this.parseNodes( this._nodesJSON, textures );
  48857. const loader = new NodeMaterialLoader();
  48858. loader.setTextures( textures );
  48859. loader.setNodes( nodes );
  48860. loader.setNodeMaterials( this.nodeMaterials );
  48861. for ( let i = 0, l = json.length; i < l; i ++ ) {
  48862. const data = json[ i ];
  48863. materials[ data.uuid ] = loader.parse( data );
  48864. }
  48865. }
  48866. return materials;
  48867. }
  48868. }
  48869. /**
  48870. * In earlier three.js versions, clipping was defined globally
  48871. * on the renderer or on material level. This special version of
  48872. * `THREE.Group` allows to encode the clipping state into the scene
  48873. * graph. Meaning if you create an instance of this group, all
  48874. * descendant 3D objects will be affected by the respective clipping
  48875. * planes.
  48876. *
  48877. * Note: `ClippingGroup` can only be used with `WebGPURenderer`.
  48878. *
  48879. * @augments Group
  48880. */
  48881. class ClippingGroup extends Group {
  48882. /**
  48883. * Constructs a new clipping group.
  48884. */
  48885. constructor() {
  48886. super();
  48887. /**
  48888. * This flag can be used for type testing.
  48889. *
  48890. * @type {Boolean}
  48891. * @readonly
  48892. * @default true
  48893. */
  48894. this.isClippingGroup = true;
  48895. /**
  48896. * An array with clipping planes.
  48897. *
  48898. * @type {Array<Plane>}
  48899. */
  48900. this.clippingPlanes = [];
  48901. /**
  48902. * Whether clipping should be enabled or not.
  48903. *
  48904. * @type {Boolean}
  48905. * @default true
  48906. */
  48907. this.enabled = true;
  48908. /**
  48909. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  48910. *
  48911. * @type {Boolean}
  48912. * @default false
  48913. */
  48914. this.clipIntersection = false;
  48915. /**
  48916. * Whether shadows should be clipped or not.
  48917. *
  48918. * @type {Boolean}
  48919. * @default false
  48920. */
  48921. this.clipShadows = false;
  48922. }
  48923. }
  48924. 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, DataArrayTexture, DataTexture, DecrementStencilOp, DecrementWrapStencilOp, DepthFormat, DepthStencilFormat, DepthTexture, DirectionalLight, DirectionalLightNode, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicDrawUsage, EnvironmentNode, EqualCompare, EqualDepth, EqualStencilFunc, EquirectUVNode, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExpressionNode, FileLoader, Float16BufferAttribute, Float32BufferAttribute, FloatType, FramebufferTexture, FrontFacingNode, FrontSide, Frustum, 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, Loader, LoopNode, LuminanceAlphaFormat, LuminanceFormat, MRTNode, MatcapUVNode, Material, MaterialLoader, MaterialNode, MaterialReferenceNode, MathUtils, Matrix2, Matrix3, Matrix4, MaxEquation, MaxMipLevelNode, 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, PointLight, PointLightNode, PointUVNode, PointsMaterial, PointsNodeMaterial, PostProcessing, PosterizeNode, PropertyNode, QuadMesh, 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, SphereGeometry, SplitNode, SpotLight, SpotLightNode, SpriteMaterial, SpriteNodeMaterial, SpriteSheetUVNode, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StackNode, StaticDrawUsage, StorageArrayElementNode, StorageBufferAttribute, StorageBufferNode, StorageInstancedBufferAttribute, StorageTexture, StorageTextureNode, SubtractEquation, SubtractiveBlending, TSL, TangentSpaceNormalMap, TempNode, Texture, Texture3DNode, TextureNode, TextureSizeNode, ToneMappingNode, ToonOutlinePassNode, TriplanarTexturesNode, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, UniformArrayNode, UniformGroupNode, UniformNode, UnsignedByteType, UnsignedInt248Type, UnsignedInt5999Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, UserDataNode, VSMShadowMap, VarNode, VaryingNode, Vector2, Vector3, Vector4, VertexColorNode, ViewportDepthNode, ViewportDepthTextureNode, ViewportSharedTextureNode, ViewportTextureNode, VolumeNodeMaterial, WebGLCoordinateSystem, WebGLCubeRenderTarget, WebGPUCoordinateSystem, WebGPURenderer, WebXRController, ZeroFactor, ZeroStencilOp, createCanvasElement, defaultBuildStages, defaultShaderStages, shaderStages, vectorComponents };
粤ICP备19079148号